Updated Nov 23, 20265 min read

Lambda and SQS Partial Batch Failures with ReportBatchItemFailures

Why one bad message makes Lambda retry a whole SQS batch, how ReportBatchItemFailures fixes it, the response shapes that count as total failure, the FIFO rule, and how per-message handlers avoid the problem.

Illustration for Lambda and SQS Partial Batch Failures with ReportBatchItemFailures

When a Lambda function reads from SQS, it receives a batch of up to the event source mapping's batch size, ten by default. A standard queue can go up to 10,000 per batch once a batching window of at least one second is set, within the 6 MB invocation payload limit. If the function throws on one of them, Lambda treats the whole batch as failed, and in a batch of ten all ten return to the queue, including the nine that already succeeded.

Partial batch responses fix this by letting the function report only the messages that failed. This guide shows the setting, the response format and the cases that quietly turn it off.

What happens to a batch when one message fails?

Per the Lambda documentation on SQS error handling, if your function throws an exception the entire batch is considered a complete failure. Lambda backs off, and after the queue's visibility timeout every message in the batch reappears, so a handler that already sent nine emails sends them again.

The Lambda SQS event source documentation describes the batching settings behind this. Every handler behind a batch event source needs to be safe to run twice, and a single poison message that always fails keeps pulling its healthy neighbors back into the queue until the message reaches the receive count of the dead-letter queue.

How do you turn on partial batch responses?

Add ReportBatchItemFailures to the event source mapping, then change the function to catch errors per message and return the IDs of those that failed.

aws lambda update-event-source-mapping \ --uuid 1234abcd-0000-0000-0000-example \ --function-response-types "ReportBatchItemFailures"
import type { SQSBatchResponse, SQSEvent } from "aws-lambda"; export const handler = async (event: SQSEvent): Promise<SQSBatchResponse> => { const batchItemFailures: SQSBatchResponse["batchItemFailures"] = []; for (const record of event.Records) { try { await processOrder(JSON.parse(record.body)); } catch (err) { console.error("failed", record.messageId, err); batchItemFailures.push({ itemIdentifier: record.messageId }); } } return { batchItemFailures }; };

Lambda deletes every message that is not in batchItemFailures and leaves the listed ones to reappear after the visibility timeout. The same page notes that with the setting on, Lambda does not scale down polling when invocations fail, which is what you want when some failures are expected.

Which responses count as a total failure?

Lambda treats a batch as a complete success when the function returns an empty or null batchItemFailures list, or an empty or null response. It treats the batch as a complete failure when the response is invalid JSON, when an itemIdentifier is an empty string or null, when the key name is wrong, or when the value is a message ID that does not exist in the batch.

The wrong key name is the common one: the field is itemIdentifier inside batchItemFailures, and a typo makes every batch fail and every message reprocess. The NumberOfMessagesDeleted metric dropping to zero and a rising ApproximateAgeOfOldestMessage are the signs, per the same documentation.

What changes for FIFO queues?

On a FIFO queue the function should stop at the first failure and return that message and every unprocessed message after it in batchItemFailures, since processing later messages from the same group out of order would break the ordering the queue exists to provide. The loop above needs a break after the first failure for FIFO sources, and the messages after it get returned unprocessed. Group IDs and what a stuck message does to its group are covered in SQS FIFO message group IDs.

How does Encore handle one failing message?

Encore brings infrastructure from code, and a Subscription handler receives one message per call, so there is no batch to partially fail: an error retries that message alone, under the subscription's retry policy, and then sends it to a dead-letter queue. Per the AWS infrastructure docs, Pub/Sub runs on SNS and SQS with dead-letter queues configured, and the platform creates the queue and the subscription. Encore provisions an IAM role for the service with access to that queue.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.
Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

The order processor from above as a subscription, where a bad message fails alone:

// orders/orders.ts import { api, APIError } from "encore.dev/api"; import { Topic, Subscription } from "encore.dev/pubsub"; import { Bucket } from "encore.dev/storage/objects"; interface OrderPlaced { orderId: string; items: { sku: string; quantity: number }[]; } const placed = new Topic<OrderPlaced>("order-placed", { deliveryGuarantee: "at-least-once" }); const receipts = new Bucket("order-receipts", { versioned: false }); export const place = api( { expose: true, method: "POST", path: "/orders" }, async (req: OrderPlaced): Promise<{ queued: boolean }> => { if (req.items.length === 0) throw APIError.invalidArgument("order has no items"); await placed.publish(req); return { queued: true }; }, ); // One message per call: throwing retries this order only, and the rest of the burst is unaffected. new Subscription(placed, "write-receipt", { retryPolicy: { minBackoff: "10s", maxBackoff: "2m", maxRetries: 4 }, handler: async (order) => { const key = `${order.orderId}.txt`; // A redelivery finds the receipt and stops, so the work is safe to repeat. if (await receipts.exists(key)) return; const lines = order.items.map((i) => `${i.sku} x ${i.quantity}`); await receipts.upload(key, Buffer.from(lines.join("\n")), { contentType: "text/plain" }); }, });

A message that exhausts maxRetries moves to the dead-letter queue and the others carry on, which is the behavior ReportBatchItemFailures approximates in a Lambda. The retry fields and their clamping per cloud are described in the Pub/Sub docs. Locally, encore run starts Pub/Sub and a bucket, so a failing message can be tested with a handler that throws.

To deploy, connect your AWS account as described in Connect your cloud account and push with git push encore.

A coding agent that adds a queue consumer writes the topic, the handler and its retry policy in one change, with no event source mapping or response format to get wrong.

Best fit: Teams processing SQS messages that want each message retried and dead-lettered on its own, with the queue and permissions declared next to the handler.

What should you check on an existing Lambda consumer?

Confirm that the event source mapping lists ReportBatchItemFailures, that the code returns itemIdentifier exactly, and that a FIFO consumer stops at its first failure. Then look at NumberOfMessagesDeleted after a deploy, since a drop to zero says the response format is being rejected.

Frequently asked questions

What is ReportBatchItemFailures in Lambda?

It is a response type on the SQS event source mapping that lets your function say which messages in a batch failed. Lambda deletes the rest of the batch from the queue and returns only the failed messages, so successful messages are not processed again.

What happens if a Lambda function throws an error on an SQS batch?

Without partial batch responses, the entire batch counts as failed and every message becomes visible again after the visibility timeout, including those that were already processed. Handlers that are not idempotent then run twice for those messages.

What response counts as a total failure with partial batch responses?

An invalid JSON response, or an itemIdentifier that is empty, null, has a wrong key name or does not match a message ID in the batch. An empty or null batchItemFailures list counts as complete success.

How do I process queue messages one at a time with their own retries?

With Encore you declare a Subscription on a Topic, and the handler receives one message per call, so returning an error retries only that message, with a retry policy and dead-letter queue. On AWS the deploy provisions the SNS topic, SQS queue and permissions in your account.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders