Lesson 1 of 7 Amazon Kinesis and Amazon MSK

Streaming Data in Real Time with Kinesis Data Streams

This lesson explains Amazon Kinesis Data Streams, the core AWS service for real-time streaming when a pipeline needs ordering, several independent consumers and the ability to replay data, as in clickstream, IoT, log and change-data pipelines.

Learning outcomes

After completing this lesson, you will be able to:

  • Explain how a data stream differs from batch processing and from a queue.
  • Size a stream from shard limits and choose a capacity mode.
  • Explain how partition keys decide ordering and cause hot shards.
  • Use retention and replay to reprocess data.
  • Identify the metrics that show a stream is unhealthy.

What a data stream is

Batch processing collects data over a period, such as a day, and processes it all at once, so results are hours old. Streaming processes each piece of data within seconds of its creation, which is needed when the value of data falls quickly: a fraud check during a payment, a live dashboard of website activity or an alert from a sensor. The data arrives as a continuous sequence of small records, such as one click, one GPS reading or one log line.

Amazon Kinesis Data Streams is a managed service that stores such records durably, in the order they arrived, so that applications can read them. Applications that write records are producers, and applications that read them are consumers. Unlike a queue, a stream does not delete a record when one consumer reads it: the record stays available for the retention period, so several consumers can each read every record independently, and a consumer can go back and read records again. Each record carries a partition key, chosen by the producer, and its data payload.

Three requirements together point to Kinesis Data Streams in exam scenarios: records must be processed in order for each key, several applications must read the same data, and the data must be replayable after a failure. The rest of this lesson explains how a stream provides these through shards, partition keys and retention.

Sort into groups

Batch or streaming?

Exam skills 1.1.1 · 1.1.2

Decide whether each requirement calls for streaming or batch processing.

Log in to try this activity Interactive activities are free with an account.

Shards and capacity modes

A Kinesis data stream is divided into shards, and each shard has a fixed capacity. A shard accepts up to 1 MB or 1,000 records per second of writes. Standard consumers share 2 MB per second of reads from each shard, so adding consumers divides that bandwidth between them. Consumers registered for enhanced fan-out each receive their own 2 MB per second per shard, pushed to them over HTTP/2 with about 70 ms latency, which suits several applications reading the same stream. Each record's partition key decides its shard, so records with the same key stay in order. The following table summarises the limits.

Per shardLimit
Writes1 MB or 1,000 records per second
Reads (standard consumers)2 MB per second, shared
Reads (enhanced fan-out)2 MB per second for each registered consumer, pushed over HTTP/2 with about 70 ms latency

A stream runs in one of two capacity modes. In on-demand mode, Kinesis adds and removes shards automatically and charges per gigabyte, which suits new or unpredictable traffic. In provisioned mode, you choose the number of shards and change it by splitting or merging them, which costs less for steady traffic. The following table compares the modes.

ModeHow it scalesBest for
On-demandShards scale automatically; charged per GBUnpredictable traffic
ProvisionedYou choose the shard count and reshard (split or merge)Steady traffic, at lower cost

1MB/s

Writes per shard

1,000records/s

Writes per shard

2MB/s

Reads per shard, shared by standard consumers

2MB/s

Reads per shard for each enhanced fan-out consumer

Fill in the value

Sizing a stream

Exam skills 1.1.1 · 1.1.9

Work out shard counts from the per-shard limits.

Log in to try this activity Interactive activities are free with an account.

Partition keys and ordering

Each record's partition key is hashed to choose a shard. Records with the same key go to the same shard and are read in order. A low-cardinality key, such as a device type where one type dominates, creates a hot shard that throttles while others sit idle. Choose high-cardinality keys such as a device or user ID.

The following diagram sizes a stream of 5,000 GPS readings per second from delivery vans and compares the load on each shard when the partition key is the depot ID and when it is the van ID.

Sizing the van stream and fixing its hot shard. Writes need three shards by size and five by record count, and reads need three, so five shards are required. With the depot ID as partition key, one shard receives about 3,000 records per second against a limit of 1,000 and throttles; with the van ID, each shard receives about 1,000.
With 5,000 records per second over five shards, an even spread puts each shard at its write limit.
Scenario questions

Choosing a partition key

Exam skills 1.1.1 · 1.1.9

Choose the partition key for each stream.

Log in to try this activity Interactive activities are free with an account.

Retention and replay

Records are kept for 24 hours by default, and the retention period can be extended up to 365 days at extra cost. Because reading does not remove records, a consumer chooses where to start reading in each shard with a shard iterator type: LATEST reads only new records, TRIM_HORIZON starts from the oldest record still retained, and AT_TIMESTAMP starts from a point in time.

This makes a pipeline replayable. If a bug in a consumer wrote wrong results for the last six hours, the fixed consumer can read the same six hours again and overwrite them, as long as the records are still within the retention period. A longer retention period therefore buys more time to detect and correct such problems.

24hours

Default retention

365days

Maximum retention, for replay

Match the pairs

Shard iterators

Exam skills 1.1.1 · 1.1.11

Match each requirement with the shard iterator type that meets it.

Log in to try this activity Interactive activities are free with an account.

Producers and consumers

Producers write records to a stream. Applications can call PutRecord, or PutRecords for batches, through the SDK. The Kinesis Producer Library (KPL) adds batching, aggregation of small records and automatic retries for high throughput. The Kinesis Agent sends log files from servers, and services such as CloudWatch Logs subscriptions and DynamoDB can write to a stream directly.

Consumers read the records. A Lambda event source mapping polls the stream and invokes a function with batches. Applications built with the Kinesis Client Library (KCL) share shards between workers and record their progress, called checkpoints, in DynamoDB. Amazon Data Firehose delivers the stream to storage, Managed Service for Apache Flink analyses it, and Glue streaming jobs and Redshift streaming ingestion load it for processing and analytics. The following table summarises the options.

ProducersConsumers
SDK PutRecord / PutRecordsLambda event source mappings
Kinesis Producer Library (KPL): batching, aggregation, retriesKCL applications (checkpoints in DynamoDB)
Kinesis Agent for log filesAmazon Data Firehose, Managed Service for Apache Flink
CloudWatch Logs subscriptions, DynamoDBGlue streaming jobs, Redshift streaming ingestion
Sort into groups

Producer or consumer?

Exam skills 1.1.1

Decide whether each tool writes to or reads from a Kinesis data stream.

Log in to try this activity Interactive activities are free with an account.

Monitoring and fixes

Two kinds of CloudWatch metric show whether a stream is healthy. GetRecords.IteratorAgeMilliseconds measures how far behind the newest record consumers are. A steadily rising value means they cannot keep up, and if it approaches the retention period, records will expire before they are processed. WriteProvisionedThroughputExceeded and ReadProvisionedThroughputExceeded count requests rejected because a shard's limits were reached, which is throttling. The following table summarises the metrics.

MetricMeaning
GetRecords.IteratorAgeMillisecondsHow far consumers are behind; rising means they cannot keep up
WriteProvisionedThroughputExceeded, ReadProvisionedThroughputExceededThrottling

Each symptom has its own remedy. Write throttling with spare total capacity points to a hot shard, which a better partition key fixes; throttling on every shard needs more shards or on-demand mode. A rising iterator age with no throttling means the consumer itself is too slow, so it needs larger batches or more parallel processing, and read throttling caused by several consumers sharing a shard is fixed with enhanced fan-out. Separately from health, records can be encrypted at rest with server-side encryption using an AWS KMS key.

Troubleshooting

An unhealthy stream

Exam skills 1.1.1 · 3.3.4

Diagnose each stream problem, choosing again until you find the fix.

Log in to try this activity Interactive activities are free with an account.
Worked example

Sizing a stream and fixing a hot shard

Delivery vans send GPS readings: 5,000 records per second of 0.5 KB each (2.5 MB/s), read by a real-time map and a fraud detector.

Write limit per shard: 1 MB/s or 1,000 records/s
  by size:     2.5 MB/s / 1 MB/s     = 3 shards (rounded up)
  by records:  5,000 / 1,000         = 5 shards   <- the deciding limit
Read limit per shard: 2 MB/s shared by standard consumers
  2 consumers x 2.5 MB/s = 5 MB/s   / 2 MB/s = 3 shards
Answer: 5 shards (or on-demand mode)

A week later, producers see ProvisionedThroughputExceededException although total traffic is within limits. The partition key is the depot ID, and one depot handles 60% of vans, so one shard takes most of the load. Changing the key to the van ID spreads records evenly while keeping each van's readings in order.

Check yourself

Which requirements together point to Kinesis Data Streams rather than Firehose?

Show answer

Ordering per key, several independent consumers and the ability to replay data. Firehose only delivers data to a destination.

Exam Tips

Remember for the exam

  • Ordering per key, several consumers and replay together point to Kinesis Data Streams.
  • One shard takes in 1 MB or 1,000 records per second and serves 2 MB per second.
  • Hot-shard throttling is fixed with a higher-cardinality partition key or more shards.
  • When several consumers each need the full throughput, use enhanced fan-out.
  • To detect consumers falling behind, watch the iterator age.
  • Unpredictable traffic suits on-demand mode; steady traffic suits provisioned mode.