Process SQS messages reliably with retries and a DLQ
Build a queue consumer that survives retries and duplicates, sends poison messages to a dead-letter queue and replays them.
By Invicly Tech, , in AWS Cloud Engineering. About 11 minutes to read.
In short
Amazon SQS holds messages until a worker is ready, so a burst of uploads does not overwhelm the processing code. Standard queues deliver every message at least once, which means sometimes twice, and a failing message comes back again and again. A reliable consumer sets the right visibility timeout, reports only the failed messages in a batch, ignores duplicates and parks poison messages in a dead-letter queue that you can replay later.
Think of it like this: SQS is a ticket rail in a restaurant kitchen: a cook takes a ticket, it is hidden while they cook, and if they never mark it done it goes back on the rail.
Explained simply
A queue is a waiting line for work. In our file service, each upload creates a message saying which file to process. A worker takes messages from the queue one batch at a time. If uploads arrive faster than the worker can handle, they simply wait in the queue instead of being lost.
When a worker receives a message, SQS hides it for a while, called the visibility timeout. If the worker finishes, it deletes the message. If it crashes or takes too long, the message becomes visible again and another try happens. That is how SQS retries without any extra code.
Some messages will never succeed, for example a corrupt file. Without a limit, they would loop forever. A dead-letter queue catches them: after a set number of tries, SQS moves the message aside so the rest of the work keeps flowing, and a person can look at it.
Standard queues may deliver the same message twice, rarely but really. So the worker must be idempotent: doing the same job twice gives the same result as doing it once. Once a bug is fixed, you move the dead-lettered messages back to the main queue, which is called a redrive.
Press Play on a diagram to walk through it one step at a time.
- 1Sent
Producer calls SendMessage
- 2Received
Hidden for the visibility timeout
- 3Processed
Worker deletes it on success
- 4Retried
Reappears if not deleted in time
- 5Dead-lettered
Moved after maxReceiveCount receives
- 6Redriven
Sent back to the source after a fix
- 1Handler logic
Idempotent, deterministic outputs
- 2Partial batch response
Only failed messages retried
- 3Visibility timeout
Long enough for the slowest normal job
- 4Redrive policy and DLQ
Poison messages parked after N tries
- 5Alarms and redrive
Humans notified, messages replayed after a fix
In depth
Choosing the visibility timeout
The visibility timeout starts when a consumer receives a message. Default is 30 seconds, and you can set 0 seconds to 12 hours on the queue, or change it for one message with ChangeMessageVisibility. If processing takes longer than the timeout, the message reappears and a second worker starts the same job while the first is still running. Set it comfortably above your slowest normal processing time. With a Lambda event source mapping, AWS recommends at least six times the function timeout, because Lambda may retry on throttling and the batching window also counts. Long polling, with WaitTimeSeconds up to 20, cuts empty receives and cost for consumers you write yourself.
- Default 30 s, maximum 12 hours
- Lambda: at least 6x the function timeout
- Extend per message for long jobs
- Long polling: WaitTimeSeconds up to 20
Batches and partial failures
Lambda polls SQS for you and calls your function with a batch, by default up to 10 messages for a standard queue. If the function throws an error, every message in the batch becomes visible again, including the nine that worked. Partial batch responses fix this. Add ReportBatchItemFailures to the event source mapping's FunctionResponseTypes, then return a batchItemFailures list with the messageId of each failed record. Lambda deletes the rest. An empty list means all succeeded. If you return an invalid response, Lambda treats the whole batch as failed. For FIFO queues, stop at the first failure and return it plus every message after it, to keep order.
- Lambda service to SQS queue: Poll and receive messages m1, m2, m31Poll and receive messages m1, m2, m3
- Lambda service to Your function: Invoke with batch of 32Invoke with batch of 3
- Your function to Lambda service: Return batchItemFailures: [m2]3Return batchItemFailures: [m2]
- Lambda service to SQS queue: Delete m1 and m34Delete m1 and m3
- SQS queue to Lambda service: m2 visible again after the timeout5m2 visible again after the timeout
Dead-letter queues and redrive
A redrive policy on the source queue names the DLQ ARN and maxReceiveCount. Each receive increments the message's ApproximateReceiveCount; once it exceeds the limit, SQS moves the message to the DLQ. The DLQ must be the same type as the source, standard or FIFO, in the same account and Region. Give the DLQ a longer retention than the source, up to the 14-day maximum, because the enqueue timestamp is kept when a message moves. A maxReceiveCount of 5 or more leaves room for throttles and brief outages. Alarm on ApproximateNumberOfMessagesVisible for the DLQ being above zero. After fixing the cause, start a redrive from the console or with StartMessageMoveTask, optionally with a rate limit so you do not flood the worker.
- Same queue type, account and Region
- Longer retention on the DLQ
- maxReceiveCount of at least 5
- Alarm when the DLQ is not empty
- Redrive with a velocity limit
Making the handler idempotent
Duplicates come from at-least-once delivery, from visibility timeouts that end too early and from redrives of messages that partly succeeded. The cure is to make repeats harmless. Use a stable idempotency key: the S3 object key plus version ID or ETag is better than the SQS message ID, because a re-sent event gets a new message ID. Before doing work, record the key in DynamoDB with a conditional put, attribute_not_exists(pk). If the put fails, the job was already claimed or done, so skip it. Write outputs to deterministic places, such as a results path built from the same key, so a second run overwrites with identical data. Powertools for AWS Lambda has an idempotency utility that wraps this pattern. FIFO queues also deduplicate, but only within a 5-minute window.
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Set the visibility timeout~35m
- 2Report partial batch failures~35m
- 3Configure a dead-letter queue~35m
- 4Make the handler idempotent~35m
- 5Redrive messages from the DLQ~35m
Key points
- The visibility timeout must be longer than processing takes; with Lambda, AWS recommends at least six times the function timeout.
- With Lambda, return batchItemFailures so only failed messages are retried, not the whole batch.
- A redrive policy moves a message to the DLQ after maxReceiveCount failed receives.
- Standard queues can deliver a message more than once, so the handler must be idempotent.
- After fixing the bug, redrive messages from the DLQ back to the source queue.
Key terms
Tap a card to flip it. 0/6 known
Examples
def handler(event, context):
failures = []
for record in event["Records"]:
try:
process(record["body"]) # must be idempotent
except Exception:
failures.append({"itemIdentifier": record["messageId"]})
return {"batchItemFailures": failures}
# needs FunctionResponseTypes = ReportBatchItemFailures on the event source mappingWithout ReportBatchItemFailures enabled, Lambda ignores this response and retries the whole batch.
Set up a queue with a DLQ and trigger Lambda
Prerequisites: a sandbox account with a budget alert and a Lambda function named process-file whose role can read SQS. Step 1: create the DLQ with 14-day retention. Step 2: create the main queue with a 180-second visibility timeout (function timeout 30 s times six) and a redrive policy with maxReceiveCount 5. Step 3: connect Lambda with batch size 10 and partial batch responses. Evidence: send a message with a body your code rejects and watch it appear in the DLQ after five receives. SQS and Lambda costs for this lab are tiny. Cleanup: delete the event source mapping and both queues.
DLQ=$(aws sqs create-queue --queue-name files-dlq \
--attributes MessageRetentionPeriod=1209600 --query QueueUrl --output text)
DLQ_ARN=$(aws sqs get-queue-attributes --queue-url $DLQ \
--attribute-names QueueArn --query Attributes.QueueArn --output text)
aws sqs create-queue --queue-name files-work --attributes '{"VisibilityTimeout":"180",
"RedrivePolicy":"{\"deadLetterTargetArn\":\"'$DLQ_ARN'\",\"maxReceiveCount\":\"5\"}"}'
aws lambda create-event-source-mapping --function-name process-file \
--event-source-arn arn:aws:sqs:eu-west-1:<account-id>:files-work \
--batch-size 10 --function-response-types ReportBatchItemFailuresFix a bug and replay the DLQ
Situation: a release could not parse PDFs with spaces in their names, and 40 messages are in files-dlq. Step 1: read a few messages without deleting them to confirm the cause. Step 2: deploy the fix and test it with one new upload. Step 3: start a redrive back to the source queue at 10 messages per second. Step 4: watch list-message-move-tasks until it reports COMPLETED and check that the DLQ is empty and 40 results exist. Because the handler is idempotent, any file that had partly succeeded is safe to run again.
aws sqs receive-message --queue-url $DLQ --max-number-of-messages 3 \
--visibility-timeout 0
aws sqs start-message-move-task \
--source-arn arn:aws:sqs:eu-west-1:<account-id>:files-dlq \
--max-number-of-messages-per-second 10
aws sqs list-message-move-tasks \
--source-arn arn:aws:sqs:eu-west-1:<account-id>:files-dlqQuick reference
- Visibility timeout: default 30 s, max 12 h; with Lambda use at least 6x the function timeout
- Retention: default 4 days, 1 minute to 14 days; give the DLQ the longest
- Enable ReportBatchItemFailures and return batchItemFailures with failed messageIds
- RedrivePolicy = deadLetterTargetArn + maxReceiveCount (start at 5 or more)
- Redrive: console DLQ redrive or aws sqs start-message-move-task
- Idempotency key: S3 key plus version or ETag, claimed with attribute_not_exists
- Maximum message size is 1 MiB; put large payloads in S3 and send a pointer
Common mistakes
- A visibility timeout shorter than the work, so a second worker picks up a message that is still being processed.
- Raising an exception for one bad record, which sends all ten messages in the batch back to the queue.
- Setting maxReceiveCount to 1, so a single throttle or timeout dead-letters a healthy message.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
A Lambda consumer has a 45-second timeout. What visibility timeout should the source queue have, and why?
- Exercise 2medium
Write a Python handler that processes SQS records, skips records whose idempotency key is already claimed in DynamoDB, and reports only failures.
- Exercise 3hard
The claim-then-process pattern above has a gap: if process fails after the claim, a retry will skip the job forever. Describe a fix.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Does SQS guarantee exactly-once delivery?
- Standard queues give at-least-once delivery. FIFO queues deduplicate messages within a 5-minute window, but your handler should still be idempotent.
- What is the difference between a DLQ and retries?
- Retries happen automatically when a message becomes visible again. The DLQ is where a message goes once it has failed more times than maxReceiveCount allows.
- Can I test SQS consumers locally?
- Yes. You can unit test the handler with a sample event JSON, and an AWS emulator can stand in for SQS; check its licence terms. A real sandbox queue also costs very little at lab volumes.