devuplabs.cloud
Free previewConcept guide12 min read

Data Streams

Read this before the Kinesis hands-on lab, or any time you need to understand real-time data streaming on AWS, what Kinesis Data Streams is, how it differs from SQS, and when to choose it.

The Problem Kinesis Solves

SQS is a great message queue. But it has a fundamental constraint: each message is consumed by exactly one consumer and then deleted. If you need five different systems to process the same event, a payment event that must go to fraud detection, analytics, audit logging, the invoice service, and a real-time dashboard simultaneously. SQS requires you to fan out via SNS or maintain five separate queues. More importantly, SQS is a queue of discrete tasks. It is not a log. Once a message is consumed and deleted, it's gone. You cannot go back and re-read the last hour of events. You cannot replay messages after a bug is fixed. You cannot add a new consumer six months from now and have it process historical data. Kinesis Data Streams solves a different class of problem: continuously ingesting and processing high-volume, ordered streams of data where multiple consumers need the same data, and where the ability to replay is essential. Typical use cases:

  • Application clickstream data (every user action, in order, at scale)
  • Financial transaction streams (every payment event, in real time)
  • IoT sensor readings (thousands of devices emitting readings per second)
  • Log aggregation (application logs from hundreds of servers, centralised)
  • Real-time metrics pipeline (metrics in, dashboards out, sub-second latency)

What Kinesis Data Streams Is

Amazon Kinesis Data Streams (KDS) is a real-time data streaming service. Producers write records to a stream. Multiple independent consumers read from the stream in parallel. Records are retained for a configurable period (1–365 days), enabling replay. Key properties:

  • Real-time: records are available to consumers within milliseconds of being written
  • Ordered within a shard: records with the same partition key always go to the same shard, in the order they were written
  • Multi-consumer: multiple independent consumer applications read the same stream simultaneously, each maintaining their own position
  • Replay: consumers can re-read data from any point within the retention window
  • Durable: data is replicated across 3 AZs within a region
  • Retention: 24 hours by default, configurable up to 365 days

Core Concepts

Stream

A stream is the top-level resource. It has a name, a shard count, and a retention period. Producers write to it; consumers read from it. A stream is region-specific.

Record

The unit of data in Kinesis. Every record has:

  • Partition key: a string used to determine which shard the record goes to (via MD5 hash). Choose partition keys with high cardinality to distribute load evenly across shards.
  • Data: the actual payload. Up to 1MB per record.
  • Sequence number: assigned by Kinesis on ingestion. Unique within a shard, monotonically increasing. Used by consumers to track their position.

Shard

The fundamental throughput unit of a Kinesis stream. A shard provides:

  • Write: 1MB/second or 1,000 records/second (whichever is hit first)
  • Read: 2MB/second

A stream with 10 shards handles 10MB/s writes and 20MB/s reads. If your throughput exceeds the shard capacity, you get ProvisionedThroughputExceededException and must add more shards (resharding).

Shards are the key sizing decision in Kinesis.

Too few: producers get throttled, records dropped. Too many: you pay for unused capacity. Calculate needed shards from your expected peak throughput: shards needed = ceil(max(peak_MB_per_sec / 1, peak_records_per_sec / 1000)) For reads: if you have 5 consumers each reading 2MB/s, you need enough shards for 5 × 2MB/s = 10MB/s of read capacity, at least 5 shards. Enhanced fan-out (covered below) removes this constraint.

Partition Key

The partition key determines which shard a record lands on. Kinesis hashes the partition key to a 128-bit integer and maps it to a shard. Records with the same partition key always go to the same shard, this is how ordering is guaranteed within a logical grouping. Choose partition keys based on what ordering you need:

  • Order per customer: use customerId as partition key
  • Order per device: use deviceId
  • Order per invoice: use invoiceId
  • Maximum distribution (no ordering needed): use a random UUID or timestamp

Hot shard problem: if most of your traffic has the same partition key (e.g. all events for one viral user), one shard gets all the write traffic while others sit idle. Monitor IncomingBytes and IncomingRecords per shard.


Producers: Writing to Kinesis

Producers write records using the Kinesis API:

  • PutRecord: write one record. Simple but not efficient for high throughput.
  • PutRecords: write up to 500 records in a single API call. Use this for all production producers, it's significantly more efficient and reduces API call overhead.

AWS provides higher-level producer libraries:

  • Kinesis Producer Library (KPL): aggregates small records into larger ones before sending (aggregation), and batches multiple records per shard per API call (collection). Dramatically increases effective throughput. Best choice for high-volume producers in Java.
  • AWS SDK: direct API calls. Fine for moderate throughput or non-Java environments.
  • Kinesis Agent: a Java daemon that monitors log files and ships them to Kinesis. Useful for EC2 log aggregation without code changes.

Service integrations (no code needed): CloudWatch Logs, DynamoDB Streams, IoT Core, and Kinesis Data Firehose can all write directly to a Kinesis stream.


Consumers: Reading from Kinesis

This is where Kinesis differs most significantly from SQS. Multiple independent consumers read the same data simultaneously, each maintaining their own checkpoint (position in the stream).

Shared throughput (classic)

The default consumption model. All consumers of a stream share the 2MB/s read capacity per shard. If you have 5 consumers and 5 shards, each consumer gets 2MB/s per shard, but they share it, so effectively 400KB/s each. At high consumer counts this becomes a bottleneck.

Enhanced fan-out

Each registered consumer gets its own dedicated 2MB/s per shard pipe, independent of other consumers. Kinesis pushes records to the consumer (push model) rather than the consumer polling (pull model). Sub-100ms latency. Cost: $0.015 per shard-hour + $0.013 per GB of data retrieved. More expensive than shared throughput but essential when you have many consumers or need the lowest latency.

Use enhanced fan-out when: you have more than 2–3 consumers, you're hitting read throttling, or you need consistent sub-second latency.

Consumer types

Lambda via Event Source Mapping: Lambda polls the stream on your behalf. Invokes your function with a batch of records from one or more shards. One Lambda invocation per shard per batch interval. Simplest option, no polling code, no checkpoint management.

Kinesis Client Library (KCL): a Java library that manages shard enumeration, checkpointing (via DynamoDB), load balancing across consumer workers, and failover. Best for high-throughput, complex processing logic, or non-Lambda consumers.

GetRecords API (DIY): you poll shards directly using GetShardIterator + GetRecords. Complete control, but you manage checkpointing, shard discovery, and failover yourself. Only use if KCL doesn't fit your language/environment.


Checkpointing: Tracking Position

Unlike SQS (where deletion marks completion), Kinesis consumers track their position via checkpoints: a pointer to the last successfully processed sequence number per shard. If a consumer crashes and restarts, it resumes from its last checkpoint: no messages lost, no re-reading from the beginning. Checkpoint storage:

  • Lambda: managed automatically by the Event Source Mapping
  • KCL: stores checkpoints in a DynamoDB table (one row per shard)
  • DIY: your responsibility, store sequence numbers in DynamoDB, Redis, or your database

At-least-once delivery: if your consumer crashes after processing but before checkpointing, records are re-delivered after restart. Your processing logic must be idempotent. Use the sequence number as an idempotency key.


Shard Iterators: Where to Start Reading

When a consumer begins reading, it specifies where in the shard to start via a shard iterator type:

  • TRIM_HORIZON: start from the oldest available record (beginning of the retention window). Use when a new consumer needs to process all historical data.
  • LATEST: start from the next record written after the consumer starts. Use when you only care about new data.
  • AT_SEQUENCE_NUMBER: start from a specific record. Use for precise replay.
  • AFTER_SEQUENCE_NUMBER: start from the record after a specific one.
  • AT_TIMESTAMP: start from a specific timestamp. Use for targeted replay after a bug fix.

Resharding: Scaling the Stream

As your throughput grows, you add shards (split). As it shrinks, you merge shards to reduce cost.

Split: divide one shard into two. The original shard becomes a parent; the two new shards are children. Existing data remains in the parent until its retention period expires, consumers must process the parent before the children.

Merge: combine two adjacent shards into one. The two originals become parents; the merged shard is the child. Resharding is not instant, it takes a few seconds to a minute. During resharding, the stream continues to accept writes. Old shards become CLOSED (no new writes) and EXPIRED (after retention).

Auto-scaling shards: Kinesis does not auto-scale shards. You must monitor WriteProvisionedThroughputExceeded and ReadProvisionedThroughputExceeded metrics and reshard manually or via custom automation (Lambda + CloudWatch Alarm + Kinesis scaling API).


Retention and Replay

Retention is one of Kinesis's most powerful features and the clearest differentiator from SQS.

  • Default: 24 hours
  • Extended: up to 7 days (additional cost)
  • Long-term: up to 365 days (higher cost)

What you can do with retention:

  • Replay after a bug: consumer had a bug for the last 3 hours. Fix the bug. Rewind to 3 hours ago using AT_TIMESTAMP and re-process.
  • Add a new consumer retroactively: a new analytics service needs the last 7 days of events. Point it at TRIM_HORIZON and let it catch up.
  • Audit: retain all events for 365 days for compliance. Query any point in time.

Cost implication: extended retention ($0.023 per shard-hour beyond 24h) adds up at scale. Only enable long retention on streams where replay is genuinely needed.


Kinesis Data Streams vs. SQS vs. SNS

These three services are the most commonly confused in AWS architectures.

DimensionKinesis Data StreamsSQSSNS
ModelOrdered log (stream)Queue (work list)Pub/sub (broadcast)
Consumers per recordMany (each reads independently)OneMany (all subscribers)
OrderingGuaranteed per partition keyBest-effort (Standard) / Strict (FIFO)No ordering guarantee
Retention1–365 days (configurable)Up to 14 daysNone (fire and forget)
ReplayYes (within retention window)No (consumed = deleted)No
Throughput modelProvisioned shards (1MB/s write per shard)Effectively unlimitedEffectively unlimited
Consumer modelPull (shared) or push (enhanced fan-out)PullPush
Message sizeUp to 1MB per recordUp to 256KB per messageUp to 256KB per message
ScalingManual (add/remove shards)AutomaticAutomatic
Cost modelPer shard-hour + per PUT unitPer requestPer publish + per delivery

Choose Kinesis when: multiple consumers need the same data, ordering matters, you need replay, or you're processing high-throughput continuous data streams.

Choose SQS when: one consumer processes each message, ordering doesn't matter (or use FIFO), you don't need replay, and you want simplicity.

Choose SNS when: you need to broadcast a single event to multiple systems immediately, with no persistence requirement.


Kinesis Data Streams vs. Kinesis Data Firehose

Kinesis has multiple services with similar names. They solve different problems:

Kinesis Data Streams (KDS): a real-time stream you manage. You write producers. You write consumers. You manage shards. You get full control and very low latency (\<1 second). Use when you need custom processing logic or very low latency.

Kinesis Data Firehose: a managed delivery pipeline. You configure a source (KDS, MSK, or direct PUT) and a destination (S3, Redshift, OpenSearch, Splunk, HTTP endpoint). Firehose buffers data, optionally transforms it via Lambda, and delivers in batches (60 second minimum interval). No consumers to write. No shards to manage. Use when you need to land streaming data into a storage system with minimal code.

javascript
KDS:      ProducerKinesis StreamYour consumer code → any destination
Firehose: ProducerFirehose       → (optional Lambda transform) → S3 / Redshift / OpenSearch

Common pattern: KDS → Lambda (real-time processing) + KDS → Firehose → S3 (raw archival). Both consumers read from the same stream simultaneously.


Common Patterns

Real-time event processing

javascript
ApplicationKDSLambda → update DynamoDB / trigger alerts

Every user action processed within seconds. Lambda scales with shard count.

Multi-consumer fan-out

javascript
Payment events → KDS
  ├── Consumer A (fraud detection, reads independently)
  ├── Consumer B (analytics aggregation)
  └── Consumer C (audit log to S3 via Firehose)

All three read the same records. None affect the others.

Log aggregation

javascript
100 EC2 instances (Kinesis Agent) → KDSLambda (parse + enrich) → OpenSearch

Centralised log pipeline without managing Logstash or Fluentd infrastructure.

Replay after incident

javascript
Bug discovered at 14:00. Bug introduced at 11:00.
Fix deployed at 14:30.
Consumer rewound to AT_TIMESTAMP 11:00 → replays 3.5 hours of events → data corrected.

Cost Model

  • Shard-hour: $0.015 per shard per hour (~$10.80/month per shard)
  • PUT payload units: $0.014 per million PUT payload units (25KB each; a 1KB record = 1 unit, a 26KB record = 2 units)
  • Extended retention (beyond 7 days): $0.023 per shard-hour
  • Enhanced fan-out: $0.015 per shard-hour + $0.013 per GB retrieved
  • Free tier: none. Kinesis has no free tier.

Example: 10 shards, 24h retention, 100 million records/day at 1KB average:

  • Shard cost: 10 shards × 24h × $0.015 = $3.60/day
  • PUT cost: 100M records × $0.014/million = $1.40/day
  • Total: ~$5/day (~$150/month)

For comparison, SQS at 100M messages/day = ~$40/day (after free tier). Kinesis can be cheaper at high throughput because the per-record cost is very low once shards are provisioned.


Summary

Kinesis Data Streams is an ordered, replayable, multi-consumer log.

Think of it as a conveyor belt: producers put items on the belt, and multiple independent observers watch the belt simultaneously, each at their own pace. Items stay on the belt for up to 365 days. Any observer can rewind to any point and re-watch. The belt is divided into lanes (shards), items with the same label always go to the same lane, in order. You provision the number of lanes upfront based on your expected throughput. Use it when you need real-time processing, multiple consumers reading the same data, guaranteed ordering within a key, or the ability to replay events.

Unlock all 24 AWS services & 291+ lab sessions (~180 hours)

Pricing