Lambda Consumers & Dead-Letter Queues

Let Lambda poll the queue for you, and park messages that keep failing.

1 min read

Lambda as the consumer

Add an SQS event source mapping and Lambda polls the queue for you, invokes your function with a batch of messages, and deletes them when the function succeeds. It also scales the number of concurrent pollers with the queue depth.

Dead-letter queues (DLQs)

A message that fails over and over (a "poison message") would otherwise retry until it expires. A redrive policy moves it to a dead-letter queue after maxReceiveCount attempts, so it stops blocking work and you can inspect it later. You can redrive messages from the DLQ back to the source after fixing the bug.

JSON
{ "deadLetterTargetArn": "arn:aws:sqs:us-east-1:123456789012:notesnap-jobs-dlq", "maxReceiveCount": "5" }

Try it

consumer.py
import json

def lambda_handler(event, context):
    failures = []
    for record in event["Records"]:
        try:
            job = json.loads(record["body"])
            summarize(job["noteKey"])  # your processing logic
        except Exception as err:
            print(f"Failed {record['messageId']}: {err}")
            failures.append({"itemIdentifier": record["messageId"]})

    # Only the failed messages go back to the queue; the rest are deleted.
    return {"batchItemFailures": failures}
Tip

Enable ReportBatchItemFailures on the event source mapping and return batchItemFailures as above. Without it, one bad message makes the whole batch retry, including messages that already succeeded.

Best practices

  • Always attach a DLQ and set a CloudWatch alarm on its message count.
  • Set the queue's visibility timeout to at least 6× the function timeout (AWS's recommendation for Lambda).
  • Use maximum concurrency on the event source mapping to protect downstream services from overload.

Key takeaways

  • Lambda event source mappings poll SQS and deliver batches to your function.
  • DLQs catch messages that fail repeatedly, so alarm on them.
  • Return batchItemFailures so only failed messages are retried.

Check your understanding

Pick an answer to see the explanation.

  1. 1. One message in a batch of 10 always fails. Without partial batch responses, what happens?

Next in “Make it production-ready”
You finished SQS. Continue with the SNS tutorial