Processing Streams with AWS Lambda
The most common stream consumer is an AWS Lambda function connected through an event source mapping.
Introduction
The most common stream consumer is an AWS Lambda function connected through an event source mapping. Lambda polls each shard, invokes your function with batches of records, and retries on failure. Getting the failure-handling settings right is what separates a reliable pipeline from one that stalls on a single bad record.
Purpose of this lesson
You will write an idempotent Lambda handler, configure partial batch responses, and route poison records to a failure destination.
Understanding the topic
Event source mapping settings that matter:
BatchSizeandMaximumBatchingWindowInSeconds— trade latency for fewer invocations.StartingPosition—LATESTfor new pipelines,TRIM_HORIZONto process the retained 24 hours.FunctionResponseTypes: ["ReportBatchItemFailures"]— return only failed records so successful ones are not reprocessed.BisectBatchOnFunctionError,MaximumRetryAttempts,MaximumRecordAgeInSeconds— stop a poison record from blocking the shard forever.DestinationConfig.OnFailure— send metadata about discarded batches to SQS or SNS for investigation.FilterCriteria— invoke only for matching records (for example, MODIFY events where status changed to SHIPPED).
Syntax reference
Event source mapping with failure handling and a filter:
aws lambda create-event-source-mapping \--function-name order-shipped-publisher \--event-source-arn "$STREAM_ARN" \--starting-position LATEST \--batch-size 100 \--maximum-batching-window-in-seconds 2 \--function-response-types ReportBatchItemFailures \--bisect-batch-on-function-error \--maximum-retry-attempts 5 \--destination-config '{"OnFailure":{"Destination":"arn:aws:sqs:us-east-1:123456789012:orders-stream-dlq"}}' \--filter-criteria '{"Filters":[{"Pattern":"{\"eventName\":[\"MODIFY\"],\"dynamodb\":{\"NewImage\":{\"status\":{\"S\":[\"SHIPPED\"]}}}}"}]}'
Informative example
Handler: publish an event when an order ships, reporting failures per record:
import type { DynamoDBStreamEvent, DynamoDBBatchResponse } from "aws-lambda";import { unmarshall } from "@aws-sdk/util-dynamodb";import type { AttributeValue } from "@aws-sdk/client-dynamodb";import { EventBridgeClient, PutEventsCommand } from "@aws-sdk/client-eventbridge";const events = new EventBridgeClient({});export const handler = async (event: DynamoDBStreamEvent): Promise<DynamoDBBatchResponse> => {const batchItemFailures: DynamoDBBatchResponse["batchItemFailures"] = [];for (const record of event.Records) {try {if (record.eventName !== "MODIFY") continue;const oldImage = unmarshall(record.dynamodb!.OldImage as Record<string, AttributeValue>);const newImage = unmarshall(record.dynamodb!.NewImage as Record<string, AttributeValue>);if (oldImage.status === newImage.status || newImage.status !== "SHIPPED") continue;await events.send(new PutEventsCommand({Entries: [{Source: "shop.orders",DetailType: "OrderShipped",// Downstream consumers de-duplicate on orderId + sequence number.Detail: JSON.stringify({ orderId: newImage.PK, sequence: record.dynamodb!.SequenceNumber }),}],}));} catch (err) {console.error("failed", record.dynamodb?.SequenceNumber, err);batchItemFailures.push({ itemIdentifier: record.dynamodb!.SequenceNumber! });}}return { batchItemFailures };};
Monitoring strategy
Alarm on the Lambda IteratorAge metric (how far behind the consumer is), Errors, and messages arriving in the on-failure queue.
Failure scenarios
What goes wrong in production:
- A record that always throws blocks its shard; without retry limits Lambda retries it until the record expires after 24 hours.
- Throwing from the handler without partial batch responses reprocesses every record in the batch, causing duplicate side effects.
- Downstream throttling (EventBridge, OpenSearch) causes retries and growing iterator age.
Best practices
- Always enable
ReportBatchItemFailuresand return failed sequence numbers. - Set
MaximumRetryAttemptsand an on-failure destination. - Use filter criteria to avoid paying for invocations that do nothing.
- Make side effects idempotent (conditional writes, de-duplication keys).
Common mistakes
- Catching and swallowing errors so failures are silently lost.
- Heavy synchronous work per record that cannot keep up with write volume.
- Forgetting that the on-failure destination receives metadata about the batch, not the records themselves — you re-read them from the stream (within 24 hours) or log them.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1IntermediateQuestionHow do you stop one bad record from blocking a DynamoDB stream?+
Answer
2IntermediateQuestionWhy must stream consumers be idempotent?+
Answer
Hands-on exercise
Hands-on: write a stream handler that maintains a CUSTOMER#<id> / STATS item with orderCount using ADD orderCount :one on INSERT of an order summary. Make it idempotent by storing the last processed sequence number per order and using a condition expression.
Summary
Lambda event source mappings turn streams into reliable pipelines when you use partial batch responses, bounded retries, failure destinations, filters, and idempotent handlers.