Difficulty: Advanced
What are DynamoDB Streams, how do they work with Lambda, and what are common use cases and pitfalls?
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.
You choose a StreamViewType when enabling the stream:
| View type | Record contains |
|---|---|
KEYS_ONLY | Only the key attributes of the changed item |
NEW_IMAGE | The item as it looks after the change |
OLD_IMAGE | The item as it looked before the change |
NEW_AND_OLD_IMAGES | Both, so you can compute exactly what changed |
Each record also has an eventName (INSERT, MODIFY, REMOVE) and a sequence number.
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.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.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.
OUT_FOR_DELIVERY, a Lambda sends an SMS or push notification.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.
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.
Change Data Capture, Stream View Types, Lambda Event Source Mapping, Shards, Event-driven Architecture, Kinesis Data Streams