Sub topic 8
Handling failures: retries, DLQs, destinations and partial batch responses
This chapter assumes you can write a handler, know the three invocation types (synchronous, asynchronous and poll-based), and understand execution roles. The retry rules differ for each invocation type, so the first step in handling a failure is to know which type triggered the function.
Failure behavior depends on the invocation type
Lambda does not have one retry policy. Who retries a failed invocation depends on how the function was called.
| Invocation type | Example triggers | Who retries | Where failed events go |
|---|---|---|---|
| Synchronous | API Gateway, `Invoke` with `RequestResponse` | The caller | Nowhere. The caller gets the error. |
| Asynchronous | S3, SNS, EventBridge, `Invoke` with `Event` | Lambda's internal queue | DLQ or on-failure destination |
| Poll-based | SQS, Kinesis, DynamoDB Streams | The event source mapping | SQS redrive queue, or on-failure destination for streams |
Synchronous invocation
With a synchronous call, Lambda runs the function once and returns the result or the error to the caller. Lambda does not retry. If API Gateway calls your function and it raises an exception, API Gateway returns a 5xx response to the client. A client or an SDK may retry, but that is the caller's decision.
Two consequences follow:
- If a client retries a
POST, your function may run twice for one logical request. Make write operations idempotent. An idempotent operation gives the same result when repeated. A common technique is to accept an idempotency key from the client and use a conditional write. - Returning a 4xx or 5xx response from the handler (for example
{"statusCode": 400}) is not a function error. Lambda records the invocation as successful because the handler returned normally. Only an unhandled exception, a timeout or a crash counts as a function error.
Asynchronous invocation
For asynchronous invocation, Lambda places the event in an internal queue and returns 202 Accepted to the caller straight away. The caller never sees the function's result. If the function fails, Lambda retries.
The defaults are:
- Up to 2 retries after the first attempt, so 3 attempts in total. You can set
MaximumRetryAttemptsfrom 0 to 2. - Lambda keeps the event for up to 6 hours. You can lower
MaximumEventAgeInSeconds(60 to 21600). - The first retry waits about 1 minute and the second about 2 minutes.
- If the function is throttled or the system returns an error before your code runs, Lambda keeps retrying within the maximum event age.
Because the same event can be delivered more than once, handlers must tolerate duplicates. Lambda also guarantees at-least-once delivery, not exactly-once.
Dead-letter queues
A dead-letter queue (DLQ) is an SQS queue or SNS topic that receives events that exhausted their retries. You set it with DeadLetterConfig. The execution role needs sqs:SendMessage or sns:Publish on the target. The DLQ receives the original event payload. Error details go in message attributes, such as ErrorCode and ErrorMessage.
Destinations
Destinations are the newer mechanism. You configure an on-success target and an on-failure target for asynchronous invocations. Supported targets are SQS, SNS, Lambda, EventBridge and (for failures) S3.
A destination record is richer than a DLQ message. It contains the original request, the response or error, the number of attempts and a timestamp. Destinations also support the success path, which a DLQ does not.
| Feature | DLQ | Destinations |
|---|---|---|
| Handles failures | Yes | Yes |
| Handles successes | No | Yes |
| Includes error and response details in the body | No (attributes only) | Yes |
| Targets | SQS, SNS | SQS, SNS, Lambda, EventBridge, S3 (failure only) |
AWS recommends destinations for new designs. If both are configured, a failed event is sent to both.
Poll-based invocation and batches
For SQS, Kinesis and DynamoDB Streams, Lambda runs pollers that read records and invoke your function with a batch. The mapping between the source and your function is the event source mapping. The key point is that the batch succeeds or fails as a unit unless you say otherwise.
SQS
When the function returns without an error, Lambda deletes the whole batch from the queue. When the function raises an error, none of the messages are deleted. After the visibility timeout expires they become visible again and are retried. A message that keeps failing is retried until it hits the queue's maxReceiveCount, and then SQS moves it to the queue's own redrive policy DLQ.
This produces a common problem. If one message in a batch of 10 is bad, the function fails, and all 10 messages return to the queue. The 9 good messages are processed again, and again on every retry. This wastes work and can cause duplicate side effects.
Three settings matter here:
- Set the queue's visibility timeout to at least six times the function timeout. Lambda's guidance is this ratio so a message is not retried while the function is still working on it.
- Configure a redrive policy with a dead-letter queue on the source queue. A DLQ configured on the Lambda function itself has no effect for SQS, because the invocation is not asynchronous.
- Set
maxReceiveCounthigh enough to survive transient errors, commonly 3 to 5.
Partial batch responses
Partial batch responses let the function report which records failed, so Lambda only returns those. To use them, enable ReportBatchItemFailures in the event source mapping's FunctionResponseTypes. Then return a batchItemFailures list from the handler.
import json
def process(message):
if "order_id" not in message:
raise ValueError("missing order_id")
def handler(event, context):
failures = []
for record in event["Records"]:
try:
process(json.loads(record["body"]))
except Exception:
failures.append({"itemIdentifier": record["messageId"]})
return {"batchItemFailures": failures}The handler catches errors per record and collects the messageId of each failure. Lambda then deletes the successful messages and leaves the listed ones in the queue.
Edge cases to know:
- An empty
batchItemFailureslist means the whole batch succeeded. - If the function raises an unhandled exception, Lambda treats the whole batch as failed, as before.
- If you return an
itemIdentifierthat is not in the batch, or the response has a malformed shape, Lambda treats the whole batch as failed. - The feature does nothing if
ReportBatchItemFailuresis not enabled. The handler above would then return a value that Lambda ignores, and a batch with a swallowed error would be deleted. This silently loses messages.
For FIFO queues, stop processing after the first failure and report that record and all later ones. This preserves message ordering within a message group.
Kinesis and DynamoDB Streams
Streams behave differently, because records are ordered per shard. If a batch fails, Lambda retries it until the records expire or the retry limit is reached. A single bad record can block the whole shard. This is often called a poison pill.
The event source mapping offers these controls:
| Setting | Effect |
|---|---|
| `MaximumRetryAttempts` | Stops retrying after N attempts (default is infinite for streams) |
| `MaximumRecordAgeInSeconds` | Discards records older than this age |
| `BisectBatchOnFunctionError` | Splits a failing batch in two and retries each half, which isolates the bad record |
| `DestinationConfig.OnFailure` | Sends metadata about the discarded batch to SQS, SNS, or S3 |
| `FunctionResponseTypes` | Enables `ReportBatchItemFailures`, using sequence numbers as identifiers |
For streams, the on-failure destination receives a description of the batch (shard, sequence number range and error), not the records themselves. You read the records back from the stream using those sequence numbers, so you must do so before the stream's retention expires.
Configuring this in SAM
The following template fragment combines a source queue with a redrive policy, partial batch responses and an asynchronous function with a failure destination. It assumes src/ contains both handlers.
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
OrdersDLQ:
Type: AWS::SQS::Queue
OrdersQueue:
Type: AWS::SQS::Queue
Properties:
VisibilityTimeout: 60
RedrivePolicy:
deadLetterTargetArn: !GetAtt OrdersDLQ.Arn
maxReceiveCount: 3
OrderWorker:
Type: AWS::Serverless::Function
Properties:
Handler: worker.handler
Runtime: python3.12
CodeUri: src/
Timeout: 10
Events:
FromQueue:
Type: SQS
Properties:
Queue: !GetAtt OrdersQueue.Arn
BatchSize: 10
FunctionResponseTypes:
- ReportBatchItemFailures
FailedEventsQueue:
Type: AWS::SQS::Queue
AsyncHandler:
Type: AWS::Serverless::Function
Properties:
Handler: async_app.handler
Runtime: python3.12
CodeUri: src/
EventInvokeConfig:
MaximumRetryAttempts: 1
MaximumEventAgeInSeconds: 3600
DestinationConfig:
OnFailure:
Type: SQS
Destination: !GetAtt FailedEventsQueue.ArnThe visibility timeout of 60 seconds is six times the function timeout of 10 seconds. SAM adds the permission to send to the destination queue to the function's role for you.
Operating a dead-letter path
A DLQ is only useful if someone looks at it. Put an alarm on the DLQ's ApproximateNumberOfMessagesVisible metric so a non-zero value notifies you. For asynchronous functions, also watch the AsyncEventsDropped metric, which counts events Lambda discarded after retries when no DLQ or destination was set.
To reprocess messages from an SQS DLQ, you can use the console's DLQ redrive feature or the StartMessageMoveTask API, which moves messages back to the source queue. Fix the bug first, or the messages will fail and return to the DLQ.
Common mistakes
- Treating a returned error response as a function failure. A handler that returns
{"statusCode": 500}has succeeded as far as Lambda is concerned, and nothing is retried. - Putting the DLQ on an SQS-triggered function instead of on the queue.
- Swallowing exceptions in a handler for a stream or SQS source without using partial batch responses, which marks the batch as successful.
- Assuming exactly-once processing. All three retry paths can deliver an event more than once.
- Letting a poison record block a stream shard because no retry limit, age limit or bisecting is set.
Exercise
An SQS-triggered function receives batches of 10 messages. Your handler catches each record's exception and returns {"batchItemFailures": [...]}. In production, messages that fail are still being deleted and never reach the DLQ. What is the most likely cause, and how do you fix it?
Show answer
The event source mapping does not have ReportBatchItemFailures in FunctionResponseTypes, so Lambda ignores the returned list and treats the invocation as a success, which deletes the whole batch. Add FunctionResponseTypes: [ReportBatchItemFailures] to the SQS event source mapping (in SAM, under the event's Properties). Also confirm the source queue has a redrive policy with a DLQ.
Exercise
A function is invoked asynchronously by S3 and fails every time because of a bug. Using default settings, how many attempts does Lambda make, and what must you configure to keep the failed events for later inspection?
Show answer
Lambda makes 3 attempts: the first and 2 retries, provided the event is younger than 6 hours. To keep the failed events, configure a dead-letter queue (SQS or SNS) or, preferably, an on-failure destination (SQS, SNS, Lambda, EventBridge or S3) on the function's asynchronous invocation configuration. The execution role also needs permission to send to that target.