DynamoDB Streams

Difficulty: Advanced

Question

What are DynamoDB Streams, how do they work with Lambda, and what are common use cases and pitfalls?

Answer

DynamoDB Streams is a change data capture feature that records every item-level insert, update and delete on a table as an ordered stream of records, kept for 24 hours. Consumers such as AWS Lambda read these records in near real time, which lets you react to database changes (send notifications, update a search index, replicate data) without adding that logic to the write path.

What a stream record contains

You choose a StreamViewType when enabling the stream:

View typeRecord contains
KEYS_ONLYOnly the key attributes of the changed item
NEW_IMAGEThe item as it looks after the change
OLD_IMAGEThe item as it looked before the change
NEW_AND_OLD_IMAGESBoth, so you can compute exactly what changed

Each record also has an eventName (INSERT, MODIFY, REMOVE) and a sequence number.

Ordering and delivery guarantees

  • Each change appears in the stream exactly once.
  • Records for the same item (same partition key) are in the order the writes happened.
  • The stream is split into shards that follow the table's partitions. There is no ordering across different items in different shards.
  • Records are retained for 24 hours. If a consumer is stuck longer, data is lost.

How Lambda consumes a stream

Lambda uses an event source mapping that polls each shard and invokes your function with batches. Important settings:

  • BatchSize and MaximumBatchingWindowInSeconds: trade latency for efficiency.
  • Error handling: by default a failing batch is retried until it succeeds or expires, which blocks the shard. Use BisectBatchOnFunctionError, MaximumRetryAttempts, MaximumRecordAgeInSeconds and an on-failure destination (SQS or SNS) to avoid poison-pill records stalling everything.
  • ReportBatchItemFailures: return only the failed record ids so successful ones are not reprocessed.
  • ParallelizationFactor (up to 10): process several batches per shard concurrently while preserving per-key order.
  • Filter criteria: invoke only for, say, MODIFY events where status became SHIPPED.

Lambda reads from DynamoDB Streams at no extra stream read cost. AWS recommends no more than two simultaneous readers per shard, so fan-out to many consumers usually goes through EventBridge Pipes, SNS or Kinesis.

Real use cases

  • Order notifications: when an order item's status changes to OUT_FOR_DELIVERY, a Lambda sends an SMS or push notification.
  • Search sync: replicate product changes to OpenSearch for full-text search.
  • Aggregates: keep a running count of orders per restaurant in another table.
  • Audit trail: write old and new images to S3 for compliance.
  • Transactional outbox: write the business record and let the stream publish the event, avoiding dual-write inconsistencies.
  • Global tables use streams internally for cross-Region replication.

DynamoDB Streams vs Kinesis Data Streams for DynamoDB

You can instead send changes to a Kinesis data stream: retention up to 365 days, more consumers and enhanced fan-out, but records can be duplicated or out of order, so consumers must handle that. Use DynamoDB Streams for simple Lambda triggers and Kinesis when you need long retention or many independent consumers.

Pitfalls

  • Consumers must be idempotent, because Lambda retries batches.
  • A handler that writes back to the same table can trigger itself in an infinite loop; guard with a condition or filter.
  • Enabling a stream on an existing table only captures changes from that point forward.
Change data capture with DynamoDB Streams. Every write becomes a stream record that Lambda reads per shard in order.
  1. App writes to table: PutItem, UpdateItem or DeleteItem.
  2. Stream record created: INSERT, MODIFY or REMOVE with chosen images.
  3. Shard (24h retention): Ordered per item key.
  4. Lambda event source mapping: Polls, batches, filters and retries.
  5. Downstream action: Notify, index, aggregate or archive.

Code examples

Lambda handler with partial batch failures

import json

def handler(event, context):
    failures = []
    for record in event["Records"]:
        try:
            if record["eventName"] != "MODIFY":
                continue
            new = record["dynamodb"]["NewImage"]
            old = record["dynamodb"].get("OldImage", {})
            # Attribute values arrive in DynamoDB JSON, e.g. {"S": "SHIPPED"}
            if new["status"]["S"] == "SHIPPED" and old.get("status", {}).get("S") != "SHIPPED":
                notify_customer(new["orderId"]["S"])
        except Exception:
            # Only this record will be retried
            failures.append({"itemIdentifier": record["dynamodb"]["SequenceNumber"]})
    return {"batchItemFailures": failures}

def notify_customer(order_id):
    print(json.dumps({"notify": order_id}))

With ReportBatchItemFailures enabled on the event source mapping, returning the failed sequence numbers means Lambda retries from the first failed record instead of reprocessing the whole batch.

Key points

  • Streams capture item-level changes, retained for 24 hours.
  • View types: KEYS_ONLY, NEW_IMAGE, OLD_IMAGE, NEW_AND_OLD_IMAGES.
  • Each change appears exactly once and is ordered per item key.
  • Configure bisect, retry limits, on-failure destinations and partial batch responses to avoid stuck shards.
  • Use Kinesis Data Streams for DynamoDB when you need long retention or many consumers.

Common follow-up questions

  • What happens if your Lambda keeps failing on one stream record?
  • How would you implement the transactional outbox pattern with DynamoDB?
  • How would you fan out stream events to five different services?
  • How do you avoid an infinite loop when the stream handler writes to the same table?

Interview tips

  • State the 24-hour retention and per-item ordering explicitly; precise guarantees impress.
  • Talk about poison-pill records and how to configure error handling; it shows production experience.
  • Connect it to an event-driven pattern like the outbox to show architectural thinking.

Concepts covered

Change Data Capture, Stream View Types, Lambda Event Source Mapping, Shards, Event-driven Architecture, Kinesis Data Streams

More AWS & Cloud Fundamentals questions