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, poll-based), and have attached an execution role to a function. Lambda handles failures differently for each invocation type, so the first step is to work out which type is calling your function.
Retry behavior depends on the invocation type
| Invocation type | Who retries | Default behavior |
|---|---|---|
| Synchronous (API Gateway, direct invoke) | The caller | Lambda returns the error. It does not retry. |
| Asynchronous (S3, SNS, EventBridge) | Lambda | Up to 2 retries after the first attempt, with delays between them. |
| Poll-based (SQS, Kinesis, DynamoDB Streams) | The event source mapping | SQS: the message returns to the queue after the visibility timeout. Streams: the batch is retried until it succeeds or the records expire. |
Asynchronous failures: DLQs and destinations
After the retries are used up, Lambda discards an asynchronous event unless you configure somewhere for it to go. You have two options.
- A dead-letter queue (DLQ) is an SQS queue or SNS topic that receives only failed events. It is the older mechanism.
- A destination can receive both successes and failures, and can be SQS, SNS, EventBridge or another Lambda function. Destinations also carry more context, such as the error message and the number of attempts.
Prefer destinations for new work. You can also lower the retry count or set a maximum event age (up to 6 hours) on the function's asynchronous configuration.
Poll-based failures: the whole batch is retried
Lambda hands an SQS function a batch of messages. If the handler raises an error, the whole batch becomes visible again. The messages that already succeeded are processed a second time. Two practices reduce the damage.
- Make processing idempotent, so handling the same message twice has the same effect as handling it once.
- Report partial batch failures, so only the failed messages are retried.
The handler below returns the IDs of the messages that failed.
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}This works only if you enable ReportBatchItemFailures in the FunctionResponseTypes setting of the event source mapping. If you leave it off, Lambda ignores the response and treats a successful return as a fully processed batch. A bad message is then silently dropped.
Poison messages and the SQS redrive policy
A message that always fails is called a poison message. SQS retries it until its receive count exceeds maxReceiveCount in the queue's redrive policy. It then moves to a dead-letter queue configured on the source queue. This DLQ belongs to SQS, not to the Lambda function. Setting a DLQ on the function itself does nothing for SQS failures.
Set the queue's visibility timeout to at least six times the function timeout. A shorter value lets a message reappear while it is still being processed.
Common mistakes
- Configuring the DLQ on the function when the trigger is SQS.
- Returning the partial failure response without enabling
ReportBatchItemFailures. - Assuming synchronous calls are retried by Lambda. The caller must retry.
- Writing non-idempotent handlers, then seeing duplicate side effects after a retry.
Exercise
An SQS-triggered function processes batches of 10 messages. One message always fails, and the function raises an exception for the whole batch. What happens to the other 9 messages, and how do you fix it?
Show answer
All 10 messages return to the queue after the visibility timeout, so the 9 good ones are processed again, and this repeats until the bad message exceeds maxReceiveCount and moves to the queue's DLQ. To fix it, catch errors per record, return the failed messageIds in batchItemFailures, and enable ReportBatchItemFailures on the event source mapping. Also make the handler idempotent and configure a redrive policy with a DLQ on the source queue.
Exercise
An asynchronous invocation from S3 fails three times (the first attempt and two retries). Where does the event go if you configured nothing, and where do you configure a place for it to go?
Show answer
It is discarded. Configure an on-failure destination (or a DLQ) in the function's asynchronous invocation settings, and give the execution role permission to send to it.