Sub topic 18
Processing queue messages with Lambda and partial batch failures
This chapter assumes you know how SQS visibility timeouts, receive counts, and dead-letter queues work. It also assumes you can read a basic Lambda handler in Python.
How Lambda consumes a queue
You don't write a polling loop for Lambda. You create an event source mapping, a Lambda-managed resource that polls the queue with long polling, collects messages into a batch, and invokes your function with that batch. Lambda deletes the messages itself if the invocation succeeds. If the invocation fails, Lambda leaves them in the queue, and they become visible again when the visibility timeout expires.
The event your function receives has a Records list. Each record carries the fields you will use most:
messageId: the unique ID of the message, used to report failures.body: the message payload as a string.receiptHandle: the handle SQS uses to delete the message. Lambda handles deletion, so you rarely touch it.attributes: system attributes, includingApproximateReceiveCount.messageAttributes: the custom attributes you sent.
The all-or-nothing problem
By default, a batch succeeds or fails as a unit. If your function raises an exception on one message out of ten, the whole batch returns to the queue. The nine messages that already succeeded are processed again. With idempotent consumers this wastes work. Without them, it causes duplicate side effects.
Reporting partial batch failures
Turn on ReportBatchItemFailures on the event source mapping. Your function then returns the IDs of the messages that failed. Lambda deletes every other message in the batch and returns only the failed ones to the queue.
import json
def process(order):
print("processing", order)
def handler(event, context):
failures = []
for record in event["Records"]:
try:
process(json.loads(record["body"]))
except Exception:
failures.append({"itemIdentifier": record["messageId"]})
# Requires ReportBatchItemFailures on the event source mapping
return {"batchItemFailures": failures}The response rules matter:
- An empty
batchItemFailureslist means every message succeeded. - A list of IDs means only those messages are retried.
- If the function raises an unhandled exception, the whole batch is treated as failed. Catch exceptions per record.
- If an
itemIdentifieris empty, null, or not a message ID from the batch, Lambda treats the whole batch as failed.
Creating the event source mapping
The FunctionResponseTypes setting is what activates partial batch responses. Without it, Lambda ignores your batchItemFailures and still retries the whole batch.
import boto3
sqs = boto3.client("sqs")
lambda_client = boto3.client("lambda")
queue_url = sqs.get_queue_url(QueueName="orders")["QueueUrl"]
queue_arn = sqs.get_queue_attributes(
QueueUrl=queue_url, AttributeNames=["QueueArn"]
)["Attributes"]["QueueArn"]
mapping = lambda_client.create_event_source_mapping(
EventSourceArn=queue_arn,
FunctionName="process-orders",
BatchSize=10,
MaximumBatchingWindowInSeconds=5,
FunctionResponseTypes=["ReportBatchItemFailures"],
ScalingConfig={"MaximumConcurrency": 10},
)
print(mapping["UUID"])The function's execution role needs sqs:ReceiveMessage, sqs:DeleteMessage, and sqs:GetQueueAttributes on the queue. The managed policy AWSLambdaSQSQueueExecutionRole grants these.
Settings that must agree with each other
Several settings interact, and getting them wrong causes duplicate processing or messages landing in the dead-letter queue unnecessarily.
| Setting | Where | Guidance |
|---|---|---|
| Visibility timeout | Queue | At least six times the function timeout, plus the batching window. This leaves room for retries of throttled or slow invocations. |
| `maxReceiveCount` | Redrive policy on the queue | Use 5 or more. Lambda receives a message again after throttling, so a low value can send healthy messages to the dead-letter queue. |
| `BatchSize` | Event source mapping | Up to 10 for FIFO queues. Up to 10,000 for standard queues, which requires a batching window. |
| `MaximumBatchingWindowInSeconds` | Event source mapping | Waits to fill a batch. It trades latency for fewer invocations. |
| `MaximumConcurrency` | Event source mapping | Caps concurrent batches for a queue so one queue cannot consume all the account's concurrency. |
Where the dead-letter queue goes
Configure the dead-letter queue on the source SQS queue through its redrive policy, as in the earlier chapter on dead-letter queues. A dead-letter queue configured on the Lambda function applies only to asynchronous invocations, and it plays no part when Lambda polls SQS.
FIFO queues
On a FIFO queue, order within a message group must be preserved. If message 3 of a group fails, you must not report message 4 of that group as successful, because it would be deleted and processed out of order. The rule is to stop at the first failure in each group and report that message and every later message in the same group as failed. Messages from other groups can still succeed.
import json
def process(order):
print("processing", order)
def handler(event, context):
failures = []
failed_groups = set()
for record in event["Records"]:
group = record["attributes"]["MessageGroupId"]
if group in failed_groups:
failures.append({"itemIdentifier": record["messageId"]})
continue
try:
process(json.loads(record["body"]))
except Exception:
failed_groups.add(group)
failures.append({"itemIdentifier": record["messageId"]})
return {"batchItemFailures": failures}Common errors
- The whole batch is retried despite returning failures.
FunctionResponseTypesis missing on the mapping. - Messages are processed twice while the function is still running. The visibility timeout is shorter than the function timeout.
- Healthy messages end up in the dead-letter queue. The cause is usually throttling combined with a low
maxReceiveCount. - A poison message blocks a FIFO group. The group cannot advance until the message is deleted or moved to the dead-letter queue, so set a redrive policy.
- Duplicates still appear. SQS delivers at least once, and a function can finish its work but fail before Lambda deletes the message. Keep the handler idempotent.
Exercise
A standard queue has a 30-second visibility timeout. Your Lambda function has a 25-second timeout and a 5-second batching window, and it returns batchItemFailures. Messages are processed twice even when no errors occur. What should you change, and why?
Show answer
Raise the queue's visibility timeout. A common recommendation is at least six times the function timeout plus the batching window, so at least 155 seconds here. Slow or throttled invocations can outlast 30 seconds, and the message becomes visible and is received again while the first invocation is still running. Keeping the handler idempotent is still required, because SQS can deliver duplicates even with correct settings.
Exercise
Your handler processes a batch of 10 and message 7 fails. You return {"batchItemFailures": [{"itemIdentifier": "<id of message 7>"}]}, but Lambda retries all 10 messages. What is the most likely cause?
Show answer
The event source mapping does not have ReportBatchItemFailures in FunctionResponseTypes. Without it, Lambda ignores the response body and treats any failed invocation as a failure of the whole batch.