Skip to content

Retries and dead-letter queues

A message is not gone until it is acknowledged

Section titled “A message is not gone until it is acknowledged”

If a queue deleted a message as soon as it handed it to a consumer, a consumer that crashed half way would take the message with it. So queues do not delete on delivery. A consumer receives a message, does the work, and then acknowledges it, and only then is the message removed. RabbitMQ’s tutorial says it plainly: if a consumer terminates without sending an acknowledgement, the broker understands that the message was not fully processed and puts it back in the queue, to deliver it to another consumer.

Amazon SQS does the same with a clock. When a consumer receives a message, it stays in the queue but becomes invisible to the others for the visibility timeout. If the consumer does not delete the message before the timeout runs out, whether because of an error, a crash or a connection problem, the message becomes visible again and can be received by the same or another consumer. The default for a queue is 30 seconds and it can be changed, and the longest it can be extended to is 12 hours from the first receive. A timeout that is too long delays the retry. One that is too short makes the message reappear while the first consumer is still working on it.

The retry is free: the consumer does not have to do anything, the clock does it. It has a price, which the next lesson is about: the message may be done more than once.

Not every failure is a crash that a retry cures. A poison message fails every time, because it is malformed or because it triggers a bug. If the queue always puts it back, it circulates for ever, takes a share of the consumers’ capacity every time it comes round, and never leaves.

The usual answer is a limit on the number of receives and a place to put what exceeds it. A dead-letter queue is a second queue that the source queue sends a message to when it has been received too many times without being deleted. In SQS the limit is the maxReceiveCount of a redrive policy: the number of times a consumer can receive a message before it is moved. The documentation advises setting it high enough to allow sufficient retries, because a limit of 1 would send a message to the dead-letter queue after a single failure.

The dead-letter queue does not fix anything. It keeps the failed messages apart, so that the main queue keeps flowing and a person or a program can look at them: SQS’s documentation lists examining the logs for the exceptions, analysing the content of the messages, and moving them back to the source queue once the cause is fixed (redrive). It also advises setting the retention of the dead-letter queue longer than that of the source queue, because in a standard queue a message keeps the time it was first enqueued.

Mental model. An acknowledgement says “this is done”. Silence means “try again”, after the visibility timeout. A limit on attempts says “stop trying, and keep it somewhere that someone will look”. A queue that retries without a limit turns one bad message into permanent load.

The lab sends 10 a second to four consumers that take 5 each, so capacity is not the problem. Consumer crashes make 20% of receives end in a crash, Poison messages are 5% of the messages, which fail every time, the Visibility timeout is 5 s and Attempts before dead letter is 3. Read Work done, Dead-letter queue and the detail under Waiting in the queue.

Consumers crash and some messages fail every time. Failed messages come back after the visibility timeout, and give up in the dead-letter queue.

Traffic
10 per second

With backpressure on, the queue holds at most 100 messages and producers are slowed to what it accepts. Without it, the queue just grows.

Consumers
Consumers
4
5 per second
Failures and delivery
20%
5%
0%
5 s
3

Share of receives where the consumer crashes before it finishes. The message comes back after the visibility timeout, and a retry may succeed.

Share of messages that fail every time they are tried. Only the dead-letter queue gets rid of them.

Share of finished messages whose acknowledgement never reaches the queue: the work was done, and the message comes back anyway.

Time controls
Time: 10 s

One second of model time passes each half second while the lab runs. Step and Skip move time on by hand.

What is happening

Producers send 10 a second and the consumers can take 20, so the queue does not grow.

Waiting in the queue
026 in flight, invisible until their timeout
Work done
7474 different messages, 0 runs repeated
Dead-letter queue
0gave up after 3 attempts
Accepted from producers
100backpressure is off, nothing is refused
The queue: one square per message, waiting first, then in flight.
Messages waiting over time
035110 seconds

Waiting in the queue Dead-letter queue

Where every message is, after 10 s
StateMessagesWhat it means
Waiting in the queue0Visible in the queue, ready to be received.
In flight26Received and invisible until the visibility timeout, waiting for an acknowledgement.
Acknowledged74Done and deleted from the queue.
Work repeated0Times a message already processed was processed again, because its acknowledgement was lost.
Dead-letter queue0Gave up after the allowed number of attempts, kept apart to be looked at.
Refused0Not accepted because the queue was full, with backpressure on. The producer is slowed down.

Illustrative values, not benchmarks of any real product.

Model notes

Assumptions

  • The lab advances one second at a time. A consumer receives up to its rate each second and finishes each message in the same second; processing time, the network and the broker itself are not modelled.
  • A message is hidden for the visibility timeout after each receive. A crash or a lost acknowledgement makes it reappear, and after the allowed number of attempts it moves to the dead-letter queue. A random draw, seeded so the same settings give the same run, decides each outcome.

Simplifications

  • The work queue does not track the order of messages: retries are received first, which stands for the oldest. Order is shown in the stream, where a partition keeps its messages in the order they were appended.
  • Exactly-once processing, transactions, replicated brokers, retention, message size and a consumer that is slow rather than dead are not modelled. The numbers are floors and illustrations, not measurements of a product.

Parameter values are illustrative. They are not benchmarks of any real product.

Press Skip 30 s twice, to 70 s. The queue has accepted 700 messages, 631 are done, 40 are in the dead-letter queue and 29 are in flight, hidden until their timeout runs out. Those add up: 631 + 40 + 29 is 700. Every message is in one of three states: finished, given up on, or waiting for a retry. No message is lost, and none is done twice, because the lab’s crashes happen before the work is done.

Poison messages are 5% of what is sent, so about 35 of the 700 are expected to be poison, and they account for most of the 40. The rest are normal messages that crashed on all three attempts. The chance of that is 0.2 × 0.2 × 0.2, which is 0.8%, so a few of the 665 normal ones are expected to be unlucky in this way. A retry cures a crash, but not a message that fails on its own.

A poison message takes time to be given up on. It is received, hidden for 5 s, received again, hidden for 5 s, received a third time, hidden for 5 s, and then moved: 3 × 5, which is 15 s after its first receive. Raise Visibility timeout and each retry waits longer, and the message stays in flight for longer. The status line tells you the result: messages gave up after 3 attempts.

A queue that retries by clock is one half. The other is the worker. The C# example below is a small background worker: it takes messages from a queue, and a handler that fails sends the message back after a pause that doubles each time (1 s, then 2 s), which is exponential backoff, and after 3 attempts the message goes to a list of dead letters. It uses a fake clock, so the pauses are instants, and one message of the four is a poison message.

C# exampleA background worker with retries, backoff and a dead-letter list
background-worker.cs
// A background worker: it takes messages from a queue, retries failures with backoff,
// and moves a message to a dead-letter list after too many attempts.
using ShardCraft.Playground;
var clock = new FakeClock();
var bus = new MessageBus();
var done = new List<string>();
var deadLetters = new List<string>();
const int maxAttempts = 3;
foreach (var job in new[] { "resize-1", "flaky-2", "resize-3", "poison-4" })
bus.Publish(job);
// "flaky" fails once, then works. "poison" always fails.
bool Handle(Message m) => m.Body.StartsWith("poison") ? false : !(m.Body.StartsWith("flaky") && m.Attempt == 1);
while (bus.TryReceive(out var message))
{
if (Handle(message))
{
done.Add(message.Body);
Console.WriteLine($"t={clock.UtcNow:mm:ss} ok {message.Body} (attempt {message.Attempt})");
continue;
}
if (message.Attempt >= maxAttempts)
{
deadLetters.Add(message.Body);
Console.WriteLine($"t={clock.UtcNow:mm:ss} dead-letter {message.Body} after {message.Attempt} attempts");
continue;
}
// Exponential backoff: wait 1 s, then 2 s, before putting the message back.
var wait = TimeSpan.FromSeconds(Math.Pow(2, message.Attempt - 1));
Console.WriteLine($"t={clock.UtcNow:mm:ss} failed {message.Body} (attempt {message.Attempt}), retry in {wait.TotalSeconds:0} s");
var pause = clock.Delay(wait);
clock.Advance(wait); // virtual time: the pause ends at once
await pause;
bus.Nack(message);
}
Console.WriteLine($"done: {string.Join(", ", done)}");
Console.WriteLine($"dead letters: {string.Join(", ", deadLetters)}");
// A real worker runs forever (BackgroundService), takes several messages in parallel,
// and keeps a message invisible while it is being processed. Retries mean a handler can run twice: make it idempotent.
Output
t=00:00 ok resize-1 (attempt 1)
t=00:00 failed flaky-2 (attempt 1), retry in 1 s
t=00:01 ok resize-3 (attempt 1)
t=00:01 failed poison-4 (attempt 1), retry in 1 s
t=00:02 ok flaky-2 (attempt 2)
t=00:02 failed poison-4 (attempt 2), retry in 2 s
t=00:04 dead-letter poison-4 after 3 attempts
done: resize-1, resize-3, flaky-2
dead letters: poison-4

This is the exact code that produced this output, run with the .NET SDK when the site was built. Nothing runs in your browser.

In the output, flaky-2 fails once and succeeds on attempt 2, poison-4 fails 3 times and ends in the dead letters, and the two others pass at once. The page’s code is never run in the browser: the output was produced by a CI run of the same file.

What happens if the handler is not safe to repeat?

Section titled “What happens if the handler is not safe to repeat?”

Every retry runs the handler again on a message that may have partly worked. If the handler charges a card and then crashes before the acknowledgement, the retry charges the card again. The queue cannot know. A short timeout makes it worse: a message that is only slow reappears and is handled by a second consumer while the first is still working. The SQS documentation says that its at-least-once delivery means there is no absolute guarantee that a message will not be delivered more than once during the visibility timeout period, and suggests extending the timeout from the worker while it is working.

So retries are safe only if the handler is idempotent: running it twice has the same effect as running it once. That is the next lesson’s subject, and the idempotency module goes into the techniques.

  • A message is deleted when it is acknowledged, not when it is delivered. If no acknowledgement arrives before the visibility timeout, it comes back.
  • A poison message fails every time. A limit on attempts and a dead-letter queue keep it from circulating for ever, and keep it where someone can look.
  • In the lab, after 70 s, 700 messages were accepted: 631 done, 40 in the dead-letter queue, 29 in flight. A poison message is given up on 15 s after its first receive, 3 × 5.
  • A worker backs off between retries, 1 s then 2 s in the example, and sends a message to the dead letters after 3 attempts.
  • A retry runs the handler again, so the handler must be safe to repeat.

Next: delivery semantics, and what at-least-once costs the consumer.

Your progress

Built by GhaziAlibi.

© ShardCraft. All rights reserved.