Amazon Kinesis

Difficulty: Advanced

Question

What is Amazon Kinesis used for, how do Kinesis Data Streams work internally, and how does it compare with SQS?

Answer

Amazon Kinesis is AWS's family of services for collecting and processing streaming data in real time: clickstreams, application logs, IoT telemetry, payment events. The core service, Kinesis Data Streams, is a durable, ordered, replayable log split into shards, where many consumers can read the same data independently. Related services are Amazon Data Firehose (formerly Kinesis Data Firehose) for delivering streams to S3, Redshift, or OpenSearch without code, Amazon Managed Service for Apache Flink (formerly Kinesis Data Analytics) for stream processing, and Kinesis Video Streams.

How Kinesis Data Streams works

  • A stream is made of shards. Each shard accepts up to 1 MB/s or 1,000 records per second of writes, and serves 2 MB/s of reads shared across standard consumers.
  • Producers send records with a partition key. Kinesis hashes the key to pick a shard, so all records with the same key (for example the same userId or merchantId) land in the same shard in order.
  • Records are retained for 24 hours by default, extendable up to 365 days. Consumers track their position (a sequence number) and can replay from any point within retention.
  • Enhanced fan-out gives each registered consumer its own 2 MB/s per shard, pushed over HTTP/2, so adding consumers does not slow the others.
  • Capacity modes: provisioned (you choose the shard count) or on-demand (Kinesis scales shards automatically and bills by data volume).

Consuming the stream

  • AWS Lambda with an event source mapping: Lambda polls each shard and invokes your function with batches. You can tune batch size, batching window, parallelization factor, and on-failure behaviour (bisect batch, max retries, an on-failure destination).
  • Kinesis Client Library (KCL) apps on EC2 or containers, which handle shard leases and checkpointing.
  • Firehose to land raw data in S3 for the data lake.
  • Managed Service for Apache Flink for windowed aggregations, joins, and fraud detection rules.

Kinesis vs SQS vs Kafka

AspectKinesis Data StreamsSQSAmazon MSK (Kafka)
ModelOrdered, replayable logQueue; message deleted after processingOrdered, replayable log
Multiple consumers of the same dataYesNo (one consumer per message)Yes
OrderingPer shard (partition key)FIFO queues onlyPer partition
ReplayYes, within retentionNoYes
OperationsFully managed, AWS-nativeFully managedManaged brokers or MSK Serverless

Use SQS to distribute independent work items, Kinesis when several systems need the same ordered event stream (analytics, fraud checks, notifications all reading payment events), and MSK if you want the Kafka ecosystem and APIs.

Gotchas

  • Hot shards: a low-cardinality partition key (like country) pushes most traffic into one shard and triggers ProvisionedThroughputExceededException. Use high-cardinality keys.
  • A failing record blocks its shard for a Lambda consumer until it succeeds or expires, unless you configure retry limits and an on-failure destination.
  • Consumers must be idempotent: retries and replays mean duplicates are possible.
Kinesis Data Streams pipeline. Producers write by partition key, shards keep order, and several consumers read the same data independently.
  1. Producers: Apps, SDK, or Kinesis Agent send records with a partition key.
  2. Partition key hashed to a shard: Same key always lands in the same shard, in order.
  3. Shards retain records: 24 hours by default, up to 365 days.
  4. Consumers: Lambda, KCL apps, Flink, each tracking its own position.
  5. Firehose to S3: Raw events archived to the data lake.

Code examples

Producer with boto3 and a Lambda consumer

import base64, json
import boto3

kinesis = boto3.client("kinesis")

# Producer: same merchant_id -> same shard -> ordered events
def publish_payment(event):
    kinesis.put_record(
        StreamName="payment-events",
        Data=json.dumps(event).encode(),
        PartitionKey=event["merchant_id"],
    )

# Consumer: Lambda event source mapping delivers batches per shard
def handler(event, context):
    failures = []
    for rec in event["Records"]:
        try:
            payload = json.loads(base64.b64decode(rec["kinesis"]["data"]))
            print(payload["txn_id"], payload["amount_paise"])
        except Exception:
            failures.append({"itemIdentifier": rec["kinesis"]["sequenceNumber"]})
            break  # stop so later records in this shard keep their order
    return {"batchItemFailures": failures}

Returning batchItemFailures (with ReportBatchItemFailures enabled) makes Lambda retry from the failed record instead of reprocessing the whole batch.

Key points

  • Kinesis Data Streams is an ordered, replayable log divided into shards
  • Per shard: 1 MB/s or 1,000 records/s in, 2 MB/s out (enhanced fan-out gives 2 MB/s per consumer)
  • Partition key decides the shard; ordering is guaranteed only within a shard
  • Retention 24 hours by default, up to 365 days; consumers can replay
  • Firehose delivers to destinations; Managed Service for Apache Flink processes streams

Common follow-up questions

  • How do you decide how many shards a stream needs?
  • What is the difference between Kinesis Data Streams and Data Firehose?
  • How would you handle a hot shard?
  • When would you pick SQS instead of Kinesis?

Interview tips

  • Explain shards and partition keys; that mechanism is what interviewers want to hear
  • Contrast Kinesis with SQS on replay and multiple consumers; it is the most common follow-up
  • Use the current service names (Amazon Data Firehose, Managed Service for Apache Flink) to show you are up to date

Concepts covered

Kinesis Data Streams, Shards, Partition Key, Amazon Data Firehose, Stream Processing

More AWS & Cloud Fundamentals questions