AI Hints
Home›System Design Tutorial›Robust Messaging
System Design · Lesson 70 of 120

Dead-Letter Queues

Where bad messages go.

⏱ 2 min read▶ Video at 1:23:51🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

Some messages can never succeed. Maybe the data is broken, or refers to a product that was deleted. If the consumer keeps retrying forever, it blocks everything behind it. A dead letter queue solves this.

Dead-Letter Queues
From the video: Dead-Letter Queues
  • Some messages always fail
  • Retrying forever blocks the rest
  • A dead-letter queue

Retry, then park it

The consumer tries each message a few times. If it still fails, the message moves to a separate dead letter queue, and the consumer carries on. Here, message B has broken data. Run it. A and C are processed normally. B fails three times, and is parked, so it doesn't block the queue.

dlq.pypython
queue = ["A", "B", "C"]
dead_letters = []
MAX_TRIES = 3

def handle(msg):
    if msg == "B":
        raise ValueError("broken data")
    print("processed", msg)

for msg in queue:
    for attempt in range(1, MAX_TRIES + 1):
        try:
            handle(msg)
            break
        except ValueError:
            if attempt == MAX_TRIES:
                dead_letters.append(msg)
print("dead letters:", dead_letters)
Output
processed A
processed C
dead letters: ['B']

Using a dead-letter queue

A dead letter queue isn't a bin. It's a waiting room. Set an alert when messages land there. Look at them, fix the bug or the data, and then replay them back into the main queue. Never just ignore it.

keyvalue
Alertwhen anything arrives
Inspectwhy did it fail?
Fixthe bug or the data
Replayback into the queue

Summary

A dead letter queue holds messages that fail too many times, so they don't block the others. Alert on it, fix, and replay. Next, what happens when producers are faster than consumers.

Key takeaways
  • Retry a few times
  • Then park the message
  • Alert, fix, replay
Next up: Backpressure — when producers are faster