A Lambda function reading a DynamoDB stream shows IteratorAge climbing, and downstream data is stale for some keys but not others. You have a hard deadline: stream records are kept for 24 hours, then they're gone.
With default settings a failing batch is retried until its records expire. One bad record can hold a shard for a day, then everything queued behind it starts expiring too.
Find out which failure you have
FN=orders-projector
aws lambda list-event-source-mappings --function-name "$FN" \
--query 'EventSourceMappings[].{uuid:UUID,state:State,last:LastProcessingResult,batch:BatchSize,pf:ParallelizationFactor,retries:MaximumRetryAttempts,age:MaximumRecordAgeInSeconds,bisect:BisectBatchOnFunctionError,resp:FunctionResponseTypes,dest:DestinationConfig,src:EventSourceArn}'
for M in IteratorAge Errors Throttles ConcurrentExecutions; do
aws cloudwatch get-metric-statistics --namespace AWS/Lambda --metric-name $M \
--dimensions Name=FunctionName,Value="$FN" \
--start-time "$(date -u -d '6 hours ago' +%FT%TZ)" --end-time "$(date -u +%FT%TZ)" \
--period 300 --statistics Maximum Sum --output table
done
| Pattern | Cause | Fix |
|---|---|---|
IteratorAge rises at one second per second, Errors steady and low | Poison record blocking a shard | Bisect, bounded retries, failure destination |
IteratorAge rises, Throttles above zero | Reserved or account concurrency exhausted | Raise or rebalance concurrency |
IteratorAge rises, no errors or throttles | Function too slow for the write rate | Parallelization factor, batch tuning, faster downstream |
| Age high only while one item is heavily updated | Hot partition key | Change the data model; parallelism can't split one key |
| Age is zero, but changes are missing | No-op writes, filters, or LATEST gap | See the last section |
| Mapping state is fine, nothing arrives after a table change | Stream disabled and re-enabled, so it has a new ARN | Create a mapping on the new ARN |
IteratorAge is a function-level maximum. It tells you the worst shard, not how many are blocked. Turn on per-mapping counts:
aws lambda update-event-source-mapping --uuid <esm-uuid> \
--metrics-config Metrics=EventCount
This adds PolledEventCount, FilteredOutEventCount, InvokedEventCount, FailedInvokeEventCount, DroppedEventCount and OnFailureDestinationDeliveredEventCount. A non-zero DroppedEventCount means data loss in your projection unless a failure destination caught it.
How retries actually behave
Two failure paths look alike and follow different rules:
- Function returned an error:
MaximumRetryAttemptsandMaximumRecordAgeInSecondsboth apply. - Function was never invoked (throttled): retry attempts don't count. Only record age or stream expiry ends it.
So a low retry limit won't free a throttled shard.
Bisecting has its own trap. BisectBatchOnFunctionError halves the failing batch and doesn't consume the retry quota. But with MaximumRetryAttempts at -1, it isolates the bad record and then retries it until it expires. Bisect needs a finite retry limit to unblock anything.
ReportBatchItemFailures treats the lowest returned sequence number as the checkpoint and retries everything from there, including records that succeeded. Returning an ID you don't mean to, or an empty one, retries the whole batch. Stop at the first failure and return only that one.
def handler(event, context):
for record in event["Records"]:
seq = record["dynamodb"]["SequenceNumber"]
try:
apply_change(record) # must be idempotent
except Exception:
print({"failed_seq": seq, "event_id": record["eventID"]})
return {"batchItemFailures": [{"itemIdentifier": seq}]}
return {"batchItemFailures": []}
Warning
Deploy code that returns this shape before enabling
ReportBatchItemFailures. Without the setting, Lambda ignores the response and the batch counts as a success, so swallowed exceptions become lost changes.
Unblock the shard
1. Create a failure destination
SQS and SNS destinations receive metadata only. An S3 destination also includes the original payload, which survives the stream's 24 hours, so prefer S3 for change data.
The function's execution role needs s3:PutObject and s3:ListBucket on the bucket, or sqs:SendMessage for a queue.
2. Bound the retries
Caution
Don't set
MaximumRecordAgeInSecondson a mapping that is already behind. Every record older than the value is discarded from the mapping, including the good ones in your backlog. Use retry attempts to unblock, and set age only after you have caught up.
aws lambda update-event-source-mapping --uuid <esm-uuid> \
--maximum-retry-attempts 5 \
--bisect-batch-on-function-error \
--function-response-types ReportBatchItemFailures \
--destination-config '{"OnFailure":{"Destination":"arn:aws:s3:::orders-stream-failures"}}'
Updates can take several minutes to apply. Don't delete and recreate the mapping to speed things up: you lose the checkpoint. Disabling is safe, because a re-enabled mapping resumes from the last processed record, provided it hasn't expired.
3. Catch up
aws lambda update-event-source-mapping --uuid <esm-uuid> \
--parallelization-factor 10
This allows up to 10 concurrent batches per shard and keeps order per partition key. Check concurrency first: the worst case is open shards × factor.
aws dynamodbstreams describe-stream --stream-arn <stream-arn> \
--query 'length(StreamDescription.Shards[?SequenceNumberRange.EndingSequenceNumber==null])'
aws lambda get-function-concurrency --function-name "$FN"
Large streams return paged shard lists; follow LastEvaluatedShardId. Parent shards are processed before their children, so a blocked parent also delays the child shards created after a split.
Replay failed batches
With an SQS or SNS destination, read the records back by shard and sequence number while they still exist. The record carries them in DDBStreamBatchInfo:
import boto3
streams = boto3.client("dynamodbstreams")
def read_batch(info):
it = streams.get_shard_iterator(
StreamArn=info["streamArn"],
ShardId=info["shardId"],
ShardIteratorType="AT_SEQUENCE_NUMBER",
SequenceNumber=info["startSequenceNumber"],
)["ShardIterator"]
end = int(info["endSequenceNumber"])
while it:
page = streams.get_records(ShardIterator=it, Limit=1000)
for r in page["Records"]:
if int(r["dynamodb"]["SequenceNumber"]) > end:
return
yield r
it = page.get("NextShardIterator")
TrimmedDataAccessException means the records have expired. Rebuild those items from the table instead.
Warning
Replayed records are older than changes the projection may already have applied. Guard the write, for example with a version attribute on the item and a conditional update, or replay by reading the current item from the table rather than applying the old image.
Less obvious causes
Too many readers. No more than two processes should read the same shard at once, and AWS recommends one Lambda function for global tables. A third consumer causes read throttling. Fan out from one function to EventBridge or SNS, or use Kinesis Data Streams for DynamoDB.
LATEST gaps. A mapping created or updated with LATEST can miss events while it starts. Use TRIM_HORIZON with an idempotent function.
No-op writes. A PutItem or UpdateItem that changes nothing writes no stream record. "Touch" updates need an attribute that changes.
Filters. DynamoDB numbers arrive as strings, and numeric operators aren't supported in DynamoDB stream filters. A wrong filter drops records without an error, so watch FilteredOutEventCount after each change.
TTL in global tables. Only the Region that performed the TTL delete sets userIdentity. Replicated deletes elsewhere look like ordinary deletes.
Prevent it next time
- Create every mapping with bisect, finite retries, partial responses and an S3 failure destination.
- Alarm on
IteratorAgeat 15 minutes, and page at 6 hours. Also alarm onDroppedEventCountandDestinationDeliveryFailures. - Set reserved concurrency to cover open shards × parallelization factor with headroom.
- Keep a tested backfill job that rebuilds the projection from the table. It's the only recovery after 24 hours.
- Before disabling a stream or changing its view type, let the mapping drain. Re-enabling creates a new ARN.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get