Data engineers often default to configuring a DynamoDB Stream with an AWS Lambda function that processes records in batches. When the function succeeds, the stream checkpoint advances; when it fails, the entire batch is retried until it either succeeds or hits the maximum retry limit, potentially leading to a "poison pill" scenario where a single malformed record blocks the entire shard. If you simply catch exceptions inside your handler and swallow them, you risk silent data loss because the checkpoint advances despite the failure.
The solution is to leverage the ReportBatchItemFailures feature. This allows the Lambda service to understand which specific records in a batch failed, enabling it to checkpoint only the successfully processed records and re-process only the failed ones.
Why this matters: Without partial batch failure handling, a single bad record can stall an entire partition of your stream, leading to significant latency in downstream systems. Implementing this pattern ensures that your pipeline remains resilient to transient errors and isolated data quality issues without manual intervention.
How it actually works
When you enable ReportBatchItemFailures, your Lambda function must return a specific JSON structure indicating the IDs of the failed records. The Lambda service then filters out the successful records and retries the function only with the records reported as failed.
flowchart LR
ddb["DynamoDB Table"] --> stream["DynamoDB Stream"]
stream --> lambda["AWS Lambda"]
lambda -- "Partial Batch Response" --> stream
lambda --> downstream["Downstream System"]
To implement this, you must configure your event source mapping to include the ReportBatchItemFailures flag. If you are using AWS CDK v2, the configuration looks like this:
from aws_cdk import aws_lambda as _lambda
from aws_cdk import aws_lambda_event_sources as events
# Assuming 'my_function' is your Lambda Function construct
# and 'my_table' is your DynamoDB Table construct
my_function.add_event_source(events.DynamoEventSource(
my_table,
starting_position=_lambda.StartingPosition.LATEST,
batch_size=100,
bisect_batch_on_function_error=False,
report_batch_item_failures=[_lambda.FailureResponseCondition.ITEM_FAILURE]
))
Inside your Python handler, you iterate through the records and track failures:
def handler(event, context):
batch_item_failures = []
for record in event['Records']:
try:
# Process individual record
process_record(record)
except Exception:
# Log the error and add the record ID to the failures list
batch_item_failures.append({"itemIdentifier": record['eventID']})
# Return the structure expected by the Lambda service
return {"batchItemFailures": batch_item_failures}
To verify this is working, observe your CloudWatch Logs. When a failure occurs, you should see your custom error logs for the specific eventID. You can then check the ApproximateArrivalTimestamp of the retry attempts to confirm that only the failed records are being sent back to your function.
Design choices and tradeoffs
Partial Batch Responses, not Bisect on Error. The BisectBatchOnFunctionError feature splits a failing batch into two and retries both. While useful for simple failures, it is less precise than ReportBatchItemFailures because it doesn't allow you to identify the specific record causing the issue. Use bisecting only if your processing logic is entirely atomic and you cannot identify the culprit.
Idempotent processing, not Exactly-once semantics. Even with partial batch reporting, DynamoDB Streams do not guarantee exactly-once delivery. If your Lambda function fails after processing a record but before sending the response, the stream may redeliver that record. Your downstream consumer must be idempotent—check if the record already exists or use an "upsert" operation—to avoid duplication.
Synchronous reporting, not Asynchronous dead-letter queues. You might be tempted to catch all errors and push them to an SQS dead-letter queue (DLQ) to keep the stream moving. While this keeps the pipeline running, it disconnects the failed record from its original shard context, making it harder to maintain order during subsequent replays. ReportBatchItemFailures keeps the error handling within the stream’s natural lifecycle.
Failure modes
Exceeding the Batch Failure limit. If your batch contains too many failures, the response object size might exceed the allowed limit. While the batchItemFailures list is constrained by the maximum batch size, ensure you aren't logging excessive metadata within that list.
Infinite Retry Loops. If a specific record fails due to a permanent issue (e.g., a schema violation in the downstream system), simply returning the failure will cause the record to loop indefinitely until the stream retention period expires. You must implement a strategy to eventually drop or move these records to a "poison pill" store after a certain number of retries. Check the approximateReceiveCount in the record metadata to determine how many times a record has been retried.
Configuration Mismatch. If you enable ReportBatchItemFailures in your code but your function does not return the batchItemFailures key, the Lambda service will treat the entire batch as a success. This leads to data loss. Always unit test your handler to verify the return structure matches the schema exactly.
When to reach for it (and when not to)
Use this pattern when your downstream sink is external (e.g., an API, a different database, or a third-party service) and individual record processing is prone to transient failure. It is the gold standard for maintaining stream health without sacrificing data integrity.
Do not use this if your processing is naturally batch-oriented (e.g., you are aggregating records and writing them to S3). In those cases, a single record failure often invalidates the entire batch aggregation anyway. In such scenarios, catching the exception and moving the entire batch to a DLQ is often cleaner.
Clean up
If you created resources for testing, ensure you delete them to avoid ongoing costs:
- Delete the Lambda function:
aws lambda delete-function --function-name <your-function-name> - Remove the event source mapping:
aws lambda delete-event-source-mapping --uuid <your-mapping-uuid> - Delete the DynamoDB table:
aws dynamodb delete-table --table-name <your-table-name>
Conclusion
By configuring ReportBatchItemFailures, you move from "all-or-nothing" batch processing to a fine-grained, resilient architecture. This change reduces the risk of blocking your stream and provides a clear mechanism for handling poisoned records. Your next step should be to implement a "poison record" counter within your handler, moving records to a storage bucket after a threshold is reached to break the retry loop.
References
- AWS Lambda Event Source Mapping: Handling Batch Item Failures
- DynamoDB Streams and AWS Lambda Triggers
- AWS CDK EventSourceMapping documentation
About the examples: automated checks confirmed that the Python blocks parse and that 3 AWS CLI commands match the AWS service API models (operation and parameter names). The examples have not been run end to end, so test them in a non-production environment before relying on them.
Cover photo by MARIOLA GROBELSKA on Unsplash.
This article was drafted with AI assistance and is intended for technical review and fact-checking before publication.
Top comments (1)
The configuration mismatch is the failure mode that scares me most here — returning no batchItemFailures key while the mapping expects it means the whole batch reads as success and the bad records just vanish. Silent data loss is worse than a stalled stream. The piece I'd love to see you take further: a record that fails permanently — a schema violation downstream — will keep its shard blocked while it retries, and approximateReceiveCount only tells you it's looping. Where do you put that record after N attempts? A DLQ breaks the stream's ordering for its shard, but leaving it in place blocks everything behind it. How do you quarantine a poison record without giving up the ordering the stream is there to protect?