AlgoViz

Amazon Kinesis Data Streams

medium 26 min

Kinesis Data Streams is a managed log on AWS.

Video lesson · Chapter 1 of 5

A click chooses a shard

0:00 / 3:54

Kinesis shards in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 1 min.

What it is

Amazon Kinesis Data Streams is a managed service for collecting and reading streams of records in real time. A stream is made of shards, and each shard is an append-only log with a fixed capacity.

Producers send a record and a partition key. The key decides the shard. Consumers read each shard in order and remember how far they got. Reading does not remove anything: records stay until the retention period ends.

Why it exists

Clicks, logs and sensor readings arrive all the time and several teams want the same data. A shared log lets each team read at its own pace and read again after a bug fix. The general idea is in log-based queues.

Running such a log yourself means brokers, disks, replication and upgrades. Kinesis takes that work away. In exchange you accept its limits, its API and its place: one AWS Region.

A short history

  1. November 2013

    AWS announces Amazon Kinesis for real-time processing of streaming data.

  2. August 2018

    Enhanced fan-out arrives: each registered consumer gets its own read throughput, pushed over HTTP/2.

  3. November 2020

    A large Kinesis event in us-east-1 becomes a well-known lesson. It has its own page.

Words to know

Shard
The unit of capacity and of order: 1 MB/s or 1,000 records/s in, 2 MB/s out.
Partition key
Text of up to 256 characters that is hashed with MD5 to choose a shard.
Sequence number
The position Kinesis gives a record inside its shard.
Enhanced fan-out
A dedicated, pushed 2 MB/s per shard for one registered consumer.
KPL and KCL
AWS libraries: the Producer Library packs records, the Client Library shares shards among workers.
Checkpoint
The last sequence number a consumer has finished.
Resharding
Splitting or merging shards to change capacity.

How it works

Step through the idea, or press Play.

Step 1 of 3

Put with a key. The hash of the key chooses one shard

Understand it

Start here

The canal with locks

Imagine a canal with a lock. The sign says how many boats it lets through each minute. When too many boats come, the canal is split into two lanes, each with its own lock. The colour of a boat decides its lane.

Boats, lanes and a clerk
3 a minuteOne lane, one lock

Boats of one colour keep their order. Between lanes there is no order at all.

What you get

Why teams choose it

  • No cluster

    No brokers, disks or upgrades. You choose a capacity mode and a retention.

  • Low delay

    About 70 ms on average with enhanced fan-out. About 200 ms for one shared consumer, more with several.

  • Durable

    Each record is copied synchronously to three Availability Zones.

  • Elastic

    On-demand streams accommodate up to twice the peak write rate of the last 30 days.

Good fits are clickstreams, log and metric collection, device telemetry and live dashboards: many small records, several readers, and the wish to replay.

Architecture

From producer to consumer

One stream, several readers

Producers put records into a Kinesis stream that holds two shards. A group of KCL workers reads the shards and saves checkpoints in DynamoDB. A Lambda function and Firehose read the same stream. Firehose writes to S3.
Every consumer sees all records. Each keeps its own position.
  1. 1

    Put

    The producer calls PutRecord or PutRecords with data and a partition key, or uses the KPL.

  2. 2

    Route

    The key is hashed with MD5 to a 128-bit number. The shard whose range contains it takes the record.

  3. 3

    Store

    The record is replicated across three zones. The answer holds the shard id and the sequence number.

  4. 4

    Read

    A consumer gets an iterator and polls with GetRecords, or receives pushed records with SubscribeToShard.

  5. 5

    Checkpoint

    After processing, the KCL writes the sequence number to a DynamoDB table. On failover another worker starts there.

One write

A success means the record is durable. A timeout means you do not know, so you retry and may create a duplicate.

Keys

Partition keys decide everything

Key strategies

KeyOrderSpreadUse it for
User idPer userGood unless one user is hugeClickstreams, sessions
RandomNoneBestIndependent events
User id plus a saltPer salted part onlySplits hot usersKnown heavy users
MinutePer minuteTerrible: one shard at a timeAlmost never
Hash of the id, modulo 10,000Per bucketSame as the idRarely useful: Kinesis hashes anyway
A time bucket sends all current traffic to one shard. That is a hot shard by design.

A shard is throttling

Salting breaks the order of that key, so make it a decision and not a reflex.

Capacity

How many shards?

Shards for a provisioned stream

N=⌈max⁡(W1 MB/s, rec/s1000, R2 MB/s)⌉N = \left\lceil \max\left(\frac{W}{1\,\text{MB/s}},\ \frac{\text{rec/s}}{1000},\ \frac{R}{2\,\text{MB/s}}\right) \right\rceil
WW is the write rate at peak. RR is the write rate times the number of shared consumers. For 10 MB/s in, 6,000 records/s and 2 shared consumers: max(10, 6, 10) = 10. Add headroom, because keys never spread perfectly.

Why packing small records matters

1000recs×200 B=0.2 MBs⇒packed: 1 MBs, 5×1000 \tfrac{\text{rec}}{\text{s}} \times 200\,\text{B} = 0.2\,\tfrac{\text{MB}}{\text{s}} \quad\Rightarrow\quad \text{packed: } 1\,\tfrac{\text{MB}}{\text{s}},\ 5\times
Without packing, 200-byte records hit the record limit at a fifth of the byte limit. The KPL aggregates many user records into one Kinesis record.

Capacity modes

ModeYou chooseScalingFits
ProvisionedShard countYou: UpdateShardCount, SplitShard, MergeShardsSteady, predictable load
On-demand StandardNothingAutomatic, from 4 MB/s write by defaultUnknown or spiky load
On-demand AdvantageAn account setting per RegionAutomatic, plus warm throughput you set ahead of an eventLarge or many streams; a minimum commitment applies
You can switch a stream between on-demand and provisioned twice in 24 hours without stopping traffic.

On-demand splits a shard within 15 minutes when traffic passes 500 KB/s on it. Traffic that more than doubles the old peak inside 15 minutes can still be throttled. Retry with backoff.

Resharding

Split and merge

A split

The real range is 0 to 2 to the power of 128 minus 1. The parent takes no more writes but stays readable until its records expire.
  1. 1

    Split one shard in two

    SplitShard, with the hash key where the second child begins.

  2. 2

    Merge two into one

    MergeShards works only on shards whose ranges touch.

  3. 3

    Or set a number

    UpdateShardCount goes to at most double or at least half of the current count in one call.

  4. 4

    Wait

    Resharding is asynchronous. The stream is UPDATING until it is ACTIVE again.

  5. 5

    Read parents first

    To keep the order of a key, finish the parent before its children. The KCL does this for you.

Reading

Shared polling or a dedicated pipe

Two kinds of stream consumer

Shared (GetRecords)Enhanced fan-out
Throughput2 MB/s per shard for all togetherUp to 2 MB/s per shard for each
DeliveryPull, 5 calls per second per shardPush over HTTP/2, SubscribeToShard
Average delayAbout 200 ms alone, about 1 s with fiveAbout 70 ms
How manyLimited by the shared rate20 registered, or 50 with On-demand Advantage in supported Regions
Extra costNonePer consumer-shard hour and data in most modes
Three shared consumers get about 667 KB/s each. With enhanced fan-out the same three could take 6 MB/s from one shard.

A worker reads a shard

Checkpoint after processing. If the worker dies before that, the records come again.

Where an iterator can start

  1. 1

    TRIM_HORIZON

    The oldest record still kept.

  2. 2

    LATEST

    Only records written from now on.

  3. 3

    AT or AFTER_SEQUENCE_NUMBER

    At a known position, or just after it.

  4. 4

    AT_TIMESTAMP

    At a moment in time. Useful for replays.

Guarantees

Order, duplicates and retention

Kinesis guarantees

  • Records of one shard are read in order
  • The same key goes to the same shard, until a reshard
  • A successful write is stored in three zones
  • Records stay for the whole retention period

Kinesis does not

  • Order records across shards
  • Deduplicate: a producer retry stores a second copy
  • Deliver exactly once
  • Compact: it cannot keep only the last value per key

Duplicates come from two places: a producer that retries after a timeout, and a consumer that restarts from its last checkpoint. Put your own unique id inside the record, because a retry gets a new sequence number. Then make the write conditional on that id. See idempotency.

Retention is 24 hours by default and can be raised to 365 days. Longer history belongs in S3, through Firehose or the built-in delivery to S3 and Iceberg tables.

Numbers

Limits to know

LimitValue
Write per shard1 MB/s or 1,000 records/s, whichever comes first
Read per shard2 MB/s shared, up to 2 MB/s per enhanced fan-out consumer
GetRecords10,000 records or 10 MB per call, 5 calls per second per shard
After a 10 MB GetRecords callCalls in the next 5 seconds fail
Record size1 MiB by default, can be raised to 10 MiB for occasional large records
Iterator lifetime5 minutes
Retention24 hours to 365 days
Shard quota20,000 in three large Regions, 1,000 or 6,000 elsewhere, adjustable
On-demand ceiling10 GB/s write in three large Regions, 200 MB/s elsewhere by default
Service level agreement99.9% monthly uptime per Region
The three large Regions are N. Virginia, Oregon and Ireland. Check the quotas page before you promise a number.

Errors you will meet

ErrorMeaningDo
Provisioned Throughput ExceededA shard limit was hitBack off with jitter, look for hot keys
Expired IteratorMore than 5 minutes oldAsk for a new one from the checkpoint
KMS ThrottlingThe encryption key is called too oftenRaise the KMS quota, batch records
Resource In UseStream is updating, or a second subscription came too soonWait and retry

Operations

Running it

Shell
aws kinesis create-stream --stream-name my-events \  --stream-mode-details StreamMode=ON_DEMANDaws kinesis wait stream-exists --stream-name my-eventsaws kinesis put-record --stream-name my-events \  --partition-key user-7 --cli-binary-format raw-in-base64-out \  --data '{"event":"click"}'# keep a week, then change capacity of a provisioned streamaws kinesis increase-stream-retention-period \  --stream-name my-events --retention-period-hours 168aws kinesis update-shard-count --stream-name my-prov \  --target-shard-count 8 --scaling-type UNIFORM_SCALING
Commands for AWS CLI version 2.

What to watch

  1. 1

    IteratorAgeMilliseconds

    How far the slowest reader is behind. If it nears the retention period, data will be lost.

  2. 2

    Write throttles

    WriteProvisionedThroughputExceeded, and the same per shard with enhanced monitoring.

  3. 3

    Bytes and records per shard

    Enhanced monitoring shows a hot shard that the stream average hides.

  4. 4

    Consumer errors

    A bad record in a batch can block a shard in Lambda. Set retries, bisecting and an on-failure destination.

Disaster

Another Region

A stream lives in one Region and has no built-in copy elsewhere. You build the copy: a Lambda function or another consumer reads stream A and writes to stream B.

Copy to a standby Region

Sequence numbers differ in the copy. Switch over by event id or timestamp, accept some duplicates, and alert on the replicator's lag.

Warm standby runs consumers in both Regions and switches quickly. Cold standby only copies data and starts consumers when needed. Firehose can archive records to S3, but it does not write into another data stream.

Choose

When Kinesis, and when not

Choose Kinesis

  • Several consumers read the same live data
  • You are on AWS and use Lambda, Firehose or managed Flink
  • Load varies and nobody wants to run brokers
  • Clicks, devices, logs, metrics
  • You want to replay days or months

Choose something else

  • Strict order over everything
  • Built-in exactly-once transactions
  • Very low volume: SQS or SNS is simpler
  • Several clouds or your own data centre
  • Log compaction
  • Full control of the cluster
  • A tight budget for a large, steady stream

The alternatives

ToolSameDifferentBest for
Apache KafkaPartitioned log, many readersYou run it. Compaction, transactions, no fixed partition rateControl, any cloud, ecosystem
Amazon MSKManaged on AWSKafka API. Brokers to size, or a serverless formKafka compatibility
Amazon SQSManaged, scalesA queue: a message is removed after processing, FIFO queues for orderTasks and decoupling
Google Pub/SubManaged, many subscribersOrdering keys, no shards to sizeGoogle Cloud
See Apache Kafka for the other side of the comparison.

Strengths

  • Nothing to patch or replicate
  • Lambda, Firehose and CloudWatch fit directly
  • On-demand growth
  • Three-zone storage
  • Up to a year of replay

Costs

  • A proprietary API
  • Fixed limits per shard
  • At-least-once only
  • No compaction
  • Shard hours, retention and fan-out add up at scale

Summary

The whole topic in one minute.

A Kinesis stream is a set of shards. The MD5 hash of the partition key picks the shard, order holds only inside a shard, and records stay for 24 hours by default and up to 365 days. A write is stored in three Availability Zones.

Plan for the limits: 1 MB or 1,000 records per second into a shard, 2 MB per second out of it, shared unless consumers use enhanced fan-out. Delivery is at least once, so consumers must be idempotent. On-demand mode adds shards for you, but nothing rescues a single key that is hotter than a shard.

  • The partition key hash chooses the shard. Order exists only inside it.
  • A shard takes 1 MB/s or 1,000 records/s and gives 2 MB/s.
  • Shared consumers divide that 2 MB/s. Enhanced fan-out does not.
  • Expect duplicates and partial failures. Use your own event id.
  • More shards never fix one hot key.
  • Watch the iterator age against the retention.

Sources