Sub topic 10
Dead-letter queues and redrive policies
This chapter assumes you know the SQS message lifecycle (send, receive, delete), how the visibility timeout works, and that standard queues deliver at least once. The examples use Python with boto3.
The problem: poison messages
A consumer that fails to process a message doesn't delete it. When the visibility timeout expires, SQS makes the message visible again and another receive picks it up. If the failure is permanent, such as malformed JSON or a reference to a record that no longer exists, the message cycles forever. It wastes compute and can hide healthy messages behind it. A message like this is called a poison message.
A dead-letter queue (DLQ) is an ordinary SQS queue that receives messages the source queue has given up on. A redrive policy on the source queue defines when to give up.
How the redrive policy works
SQS keeps a ReceiveCount for every message. It goes up each time the message is received and not deleted. The redrive policy has two fields:
deadLetterTargetArn: the ARN of the DLQ.maxReceiveCount: how many receives are allowed before SQS moves the message.
With maxReceiveCount set to 5, a message can be received five times. The next receive attempt finds that the count would exceed the limit, so SQS moves the message to the DLQ instead of returning it.
The receive count rises whenever a message is received and not deleted. This includes consumer crashes, timeouts, and code that reads a message and then ignores it.
Creating the pair
The DLQ is created first, because the source queue needs its ARN. The code below uses the pattern from the earlier chapters and adds a policy on the DLQ that controls which queues may use it.
import json
import boto3
sqs = boto3.client("sqs")
def arn_of(url):
return sqs.get_queue_attributes(
QueueUrl=url, AttributeNames=["QueueArn"]
)["Attributes"]["QueueArn"]
# DLQ keeps messages for the maximum 14 days (in seconds)
dlq_url = sqs.create_queue(
QueueName="orders-dlq",
Attributes={"MessageRetentionPeriod": "1209600"},
)["QueueUrl"]
dlq_arn = arn_of(dlq_url)
queue_url = sqs.create_queue(
QueueName="orders",
Attributes={
"VisibilityTimeout": "60",
"RedrivePolicy": json.dumps(
{"deadLetterTargetArn": dlq_arn, "maxReceiveCount": "5"}
),
},
)["QueueUrl"]
# Only the orders queue may dead-letter into this DLQ
sqs.set_queue_attributes(
QueueUrl=dlq_url,
Attributes={
"RedriveAllowPolicy": json.dumps(
{"redrivePermission": "byQueue", "sourceQueueArns": [arn_of(queue_url)]}
)
},
)redrivePermission accepts allowAll (the default), denyAll, and byQueue. With byQueue you may list up to 10 source queue ARNs.
Rules that catch people out
- Matching types. A standard queue needs a standard DLQ, and a FIFO queue needs a FIFO DLQ. Both queues must be in the same account and Region.
- Retention is measured from the original send. In a standard queue, the retention clock keeps running from the original enqueue time and does not restart when the message moves. A message that spent three of four days in the source queue has one day left in a DLQ with four-day retention. Give the DLQ the longest retention you can, up to 14 days, and always more than the source queue. In a FIFO queue the clock does restart on the move.
- The receive count resets. In the destination queue, a redriven message starts again at a count of zero.
- maxReceiveCount of 1 is too aggressive. Any transient error sends the message to the DLQ. Values from 3 to 5 absorb temporary failures such as a brief database outage.
- The visibility timeout still governs retry spacing. With a 60-second timeout and
maxReceiveCountof 5, a message that always fails is dead-lettered after about five minutes. - FIFO ordering. In a FIFO queue, a failing message blocks its message group until it is moved. Later messages in that group wait behind it.
Inspecting and redriving
A message in the DLQ is a record of a failure, so read it before you resend it. System attribute DeadLetterQueueSourceArn tells you which queue it came from. Once the bug is fixed, you can send the messages back with a message move task, which does the work server-side.
import boto3
sqs = boto3.client("sqs")
dlq_url = sqs.get_queue_url(QueueName="orders-dlq")["QueueUrl"]
source_url = sqs.get_queue_url(QueueName="orders")["QueueUrl"]
def arn_of(url):
return sqs.get_queue_attributes(
QueueUrl=url, AttributeNames=["QueueArn"]
)["Attributes"]["QueueArn"]
# Peek at a failed message (it stays in the DLQ unless deleted)
resp = sqs.receive_message(
QueueUrl=dlq_url,
MaxNumberOfMessages=1,
VisibilityTimeout=30,
MessageSystemAttributeNames=["All"],
)
for msg in resp.get("Messages", []):
print(msg["Body"], msg["Attributes"].get("DeadLetterQueueSourceArn"))
# After fixing the consumer: move everything back, 10 messages per second
task = sqs.start_message_move_task(
SourceArn=arn_of(dlq_url),
DestinationArn=arn_of(source_url),
MaxNumberOfMessagesPerSecond=10,
)
print(task["TaskHandle"])
status = sqs.list_message_move_tasks(SourceArn=arn_of(dlq_url))["Results"][0]
print(status["Status"], status.get("ApproximateNumberOfMessagesMoved"))The source of a move task must be a DLQ. If you omit DestinationArn, messages go back to the queue they originally came from.
Redrive without a fix creates a loop. The messages fail again, consume five more receives each, and land back in the DLQ. Throttle with MaxNumberOfMessagesPerSecond so a large backlog does not flood a consumer that is still recovering.
Operating a DLQ
A DLQ that nobody watches only hides failures. Create a CloudWatch alarm on ApproximateNumberOfMessagesVisible for the DLQ, with a threshold of 0, so any message triggers a notification. Chapter 19 covers monitoring in detail.
Summary of settings
| Setting | Where | Purpose |
|---|---|---|
| `RedrivePolicy` | Source queue | Names the DLQ and `maxReceiveCount` |
| `RedriveAllowPolicy` | DLQ | Limits which queues may dead-letter into it |
| `MessageRetentionPeriod` | DLQ | Should exceed the source queue's retention |
| `start_message_move_task` | API call on DLQ | Moves messages back after a fix |
Exercise
A standard queue has a four-day retention period and a maxReceiveCount of 3. Its DLQ also has four-day retention. A message fails three times over its first three days and is moved to the DLQ. Roughly how long can you wait before redriving it, and what would you change?
Show answer
About one day. Standard queues measure retention from the original send time, so the move does not restart the clock, and the message expires four days after it was first sent. Set the DLQ's MessageRetentionPeriod to 14 days (1209600 seconds), which is longer than the source queue's, and alarm on the DLQ so someone acts early.