Retry only failed SQS messages in AWS Lambda

Retry only failed SQS messages in AWS Lambda

One malformed SQS message can make Lambda retry an entire batch. If nine records succeed and the tenth fails, retrying all ten burns invocations and can repeat side effects. A partial batch response lets a worker report the failed message IDs so Lambda can acknowledge the successes.

Set up a disposable queue and worker

Use a standard SQS queue with a dead-letter queue, a Python Lambda function, and an active SQS event source mapping in the same AWS Region. Give the worker execution role permission to consume messages and write CloudWatch Logs. Configure the source queue visibility timeout for at least six times the function timeout, plus any batch window. Use a different queue from production and a small batch size, such as five.

Return the messages that need retrying

Save the following as lambda_function.py and use lambda_function.lambda_handler as the handler. This lab validates the message body and logs only a fixed status plus the message ID.

import json
import logging

logger = logging.getLogger()
logger.setLevel(logging.INFO)


def lambda_handler(event, context):
    retry = []
    for record in event["Records"]:
        message_id = record["messageId"]
        try:
            order = json.loads(record["body"])
            if not isinstance(order, dict) or not order.get("order_id"):
                raise ValueError("missing order ID")
            logger.info("accepted message_id=%s", message_id)
        except (TypeError, ValueError):
            logger.warning("invalid message_id=%s", message_id)
            retry.append({"itemIdentifier": message_id})
    return {"batchItemFailures": retry}

Deploy the handler before enabling partial responses. Replace the mapping ID with the UUID of the lab mapping returned by list-event-source-mappings.

aws lambda list-event-source-mappings \
  --function-name partial-batch-lab \
  --query 'EventSourceMappings[].{UUID:UUID,Queue:EventSourceArn}'

MAPPING_ID=replace-with-lab-mapping-uuid
aws lambda update-event-source-mapping \
  --uuid "$MAPPING_ID" \
  --function-response-types ReportBatchItemFailures
aws lambda get-event-source-mapping --uuid "$MAPPING_ID" \
  --query '{State:State,ResponseTypes:FunctionResponseTypes}'

Verify a mixed batch before watching live retries

From the directory containing the function, run this local test. It produces a deterministic mixed batch even when the live poller receives the lab messages in separate invocations.

python3 - <<'PY'
from lambda_function import lambda_handler

event = {"Records": [
    {"messageId": "ok-1", "body": '{"order_id":"demo-1"}'},
    {"messageId": "bad-1", "body": "invalid JSON"},
    {"messageId": "ok-2", "body": '{"order_id":"demo-2"}'},
]}
assert lambda_handler(event, None) == {
    "batchItemFailures": [{"itemIdentifier": "bad-1"}]
}
PY

Then send a valid message and an invalid message to the lab queue. In CloudWatch Logs, look for an accepted event and retry attempts for the invalid message. After the configured redrive threshold, check that the invalid message appears in the dead-letter queue. Standard SQS delivery remains at least once, so make real side effects idempotent even when partial responses are enabled.

Know what still retries the whole batch

An unhandled function exception, such as a timeout, still fails the entire batch. A correctly shaped response also has no effect until the mapping enables ReportBatchItemFailures. This loop is for standard queues. For FIFO, stop after the first failure and report both failed and unprocessed records so the queue order is preserved.

Clean up the lab

Remove the lab event source mapping before deleting the function, queues, and log group. Remove an IAM role only if it was created for this lab. Lambda invocations, SQS requests, and retained logs can incur charges.

AWS Lambda error handling for SQS · Configure an Amazon SQS event source

Related reading

Techmandra Avatar

Leave a Reply

Your email address will not be published. Required fields are marked *