# Queues, retries and dead letter queues

> When to retry, when to give up, and what to do with messages that will never work. The decisions behind a queue that doesn't get stuck.

- URL: https://urimarti.com/en/blog/colas-reintentos-y-dead-letter-queues/
- Date: 2026-12-02
- Language: en
- Tags: colas, resiliencia, eventos
- Author: Oriol Martí

Queues have a reputation for fixing everything. A slow external service, a traffic spike, a heavy task that doesn't fit in an HTTP request: "put it on a queue". And it's a good idea. But a queue doesn't make the work succeed, it only postpones it. What decides whether the system holds up is what happens when a message **fails**.

My position: **an unbounded retry is an infinite loop with a better reputation**. Retrying is fine for errors that fix themselves. For everything else you have to decide up front how many times, with how much waiting, and where the things that can't be fixed go.

## Transient vs permanent errors

The first decision isn't how many times to retry, but **whether retrying makes sense at all**. A retry only helps when the error can go away without anyone doing anything.

| Type | Examples | What to do |
| --- | --- | --- |
| **Transient** | Timeout, dropped connection, `429 Too Many Requests`, `502`, `503`, `504`, a database lock | Retry with a wait |
| **Permanent** | `400` for invalid data, `401`/`403` for a revoked token, `404` for something that no longer exists, JSON that doesn't match the schema | Don't retry: send to the DLQ or discard with a clear log |
| **Unclear** | A generic `500`, `409 Conflict`, errors your code doesn't know | A few retries and, if it persists, to the DLQ |

Retrying a permanent error isn't harmless. A message with malformed data retried every few seconds burns invocations, floods the logs with noise and, if the queue processes in order, **blocks everything behind it**.

That's why the consumer has to tell them apart. A `try/catch` that rethrows everything isn't enough: every error you catch should land in one of the three rows of the table.

## Backoff, jitter and limits

When an error is transient, the worst thing you can do is retry immediately. If the target service is overloaded, every instant retry adds load exactly when it can least take it.

### Exponential backoff

Each attempt waits longer than the previous one: 1 s, 2 s, 4 s, 8 s... A brief failure is resolved in the first attempts, and a long one doesn't turn into a bombardment.

### Jitter: don't let everyone retry at once

Backoff alone isn't enough. If the service goes down and a thousand messages fail in the same second, with the same backoff all thousand come back in the same second: at 1 s, at 2 s, at 4 s. They're synchronised waves that knock the service down again every time it tries to get back up.

The fix is to add randomness. The variant that usually works best is **full jitter**: wait a random time between zero and the exponential limit.

```text
wait = random(0, min(cap, base · 2^attempt))

attempt 1:  between 0 and 2 s
attempt 2:  between 0 and 4 s
attempt 3:  between 0 and 8 s
...
attempt 8:  between 0 and 60 s   ← the cap stops the growth
```

The waves become a spread-out trickle. If the target service returns a `Retry-After` header, that wait wins over the calculated one: it's telling you when it'll have capacity again.

### Limits: how many times, and in which layer

Every retry needs two limits: a **maximum number of attempts** and a **cap on the wait**. Without the first, the message never leaves the loop. Without the second, exponential backoff ends up waiting for hours.

And there's a third limit almost nobody sets: **retry in a single layer**. If the HTTP client retries 3 times, the consumer retries 3 times and the queue redelivers 3 times, a single message can generate 27 calls to the service that was down.

```text
HTTP client:   3 attempts ─┐
consumer:      × 3        ─┼─▶  up to 27 calls per message
queue (SQS):   × 3        ─┘
```

My rule: short, immediate retries in the client (one or two, for millisecond network blips), and the retries with a wait, in the queue. The queue already knows how to wait without holding a process.

### What it looks like in SQS

In SQS, a message the consumer doesn't delete becomes visible again once the **visibility timeout** expires, and each delivery counts as a receive. Two details cause most of the problems:

- **The visibility timeout must be longer than the processing time.** If a message takes 40 s and the timeout is 30 s, another consumer receives it while the first is still working on it. With Lambda, AWS recommends at least 6 times the function timeout.
- **Failures are reported per message, not per batch.** If Lambda processes 10 messages and one fails, without `ReportBatchItemFailures` all 10 come back. The 9 that succeeded are processed again.

## Dead letter queue: the inbox nobody wants to check

Some messages will never work, however many times they're retried: a product deleted at the source, a user who revoked access, a format your code didn't expect. That's what the **dead letter queue (DLQ)** is for: a separate queue where a message goes once it exceeds the maximum number of attempts.

```text
              ┌────────────────┐    processed ok    ┌──────────┐
 producer  ──▶│   main queue   │──────────────────▶ │  deleted │
              └───────┬────────┘                    └──────────┘
                      │ fails
                      ▼
               receives < max? ──yes──▶ back to the queue (with delay)
                      │
                      no
                      ▼
              ┌────────────────┐    alarm    ┌───────────────────┐
              │      DLQ       │───────────▶ │ someone checks it │
              └───────┬────────┘             └─────────┬─────────┘
                      │                                │ fixes the cause
                      └─────────── redrive ◀───────────┘
```

The DLQ does two jobs. It protects the main queue, because the poison message stops occupying the consumers. And it keeps the message, because **discarding it would mean losing something someone was waiting for**: an order that wasn't synced, an email that wasn't sent, a payment that wasn't recorded.

Three decisions when configuring it:

- **The maximum number of receives** (`maxReceiveCount` in SQS). Low (3-5) for errors that tend to be permanent. Higher if you depend on an external service that goes down often and you don't want a ten-minute outage to fill the DLQ.
- **Retention.** In SQS standard queues, a message keeps its original enqueue timestamp when it moves to the DLQ. If the main queue retains for 4 days and the DLQ does too, a message that took 3 days to fail disappears from the DLQ one day later. The DLQ must retain longer than the source queue; I usually use the maximum, 14 days.
- **One DLQ per queue.** Sharing a DLQ across different queues mixes messages with different formats and causes, and makes it harder to send them back where they belong.

The danger of the DLQ is the name I gave this section: **it's the inbox nobody checks**. A DLQ without an alarm doesn't solve errors, it hides them. The system looks healthy because the main queue is flowing, while orders that never arrived pile up in the DLQ.

## Idempotency as a prerequisite

Everything above assumes something worth saying out loud: **if you retry, you will process messages more than once**. Not as a rare edge case, but as a normal part of how the system works:

- SQS standard queues guarantee **at-least-once** delivery, not exactly-once.
- A consumer can finish the work and die before deleting the message. The message comes back and the work is repeated.
- A timeout doesn't tell you whether the operation failed or finished and the response was lost.
- Reprocessing from the DLQ is, by definition, a second delivery.

That's why idempotency isn't an optional improvement: it's **what makes retrying safe**. Without it, every retry is a bet that the previous attempt didn't get to do anything.

There are two ways to get it, and I usually combine them:

- **Final state instead of changes.** The message doesn't say "subtract 3 from stock", it says "stock should be 12". Applying it ten times gives the same result as applying it once. It's what I do in [the Build the Drop sync](/en/blog/anatomia-de-un-saas-serverless/).
- **An identifier per message.** Each message carries a stable key and the consumer records which ones it has processed. If one it has already seen arrives, it acknowledges it without repeating the effect. It's the same technique as [idempotency keys in payments](/en/blog/pagos-que-no-cobran-dos-veces/), applied to a queue.

If an operation can't be made idempotent (for example, an external API that doesn't accept idempotency keys and creates a resource on every call), it's better **not to retry it automatically**: the message goes to the DLQ and someone decides.

## Alerts and reprocessing

A well-configured queue fails silently if nobody is watching it. The alarms I always set:

| Alarm | SQS metric | What it means |
| --- | --- | --- |
| **The DLQ has messages** | `ApproximateNumberOfMessagesVisible` > 0 on the DLQ | Something won't fix itself |
| **The queue is ageing** | `ApproximateAgeOfOldestMessage` on the main queue | Consumers can't keep up or are stuck |
| **Failures are rising** | Consumer errors (for example, Lambda `Errors`) | An external service is starting to fail, before it reaches the DLQ |

The first is the most important and the most ignored. A single message in the DLQ deserves someone's attention. If the DLQ receives so many messages that the alarm fires every day and nobody pays attention, the problem isn't the alarm: there's a permanent error being treated as transient.

And when the alarm fires, reprocessing always follows the same order:

1. **Look at the messages and find the cause.** What they have in common: a customer, a data type, a time window.
2. **Fix the cause.** Deploy the fix, renew the token, correct the source data.
3. **Move the messages back to the source queue.** In SQS you can do it from the console (*redrive*) or with `StartMessageMoveTask`, at a controlled rate so you don't cause another spike.
4. **Check they don't come back.** If they return to the DLQ, that wasn't the cause.

Reprocessing without fixing the cause just sends the messages round one more time. And reprocessing without idempotency can duplicate whatever did half-succeed. Step 3 is only safe if the rest of this post is done.

## What I take away

**Classify before you retry.** A transient error is retried with a wait. A permanent one is set aside. Treating them the same is the cause of most stuck queues.

**Backoff with jitter, with limits, and in a single layer.** Without jitter, retries arrive in waves. Without limits, they never end. With several layers retrying, they multiply.

**A DLQ without an alarm is a place where errors disappear.** Its job is to keep messages until someone looks at them, and that only happens if something raises the alarm.

**Idempotency comes first.** Retries, at-least-once delivery and reprocessing all mean every message will be processed more than once. If the consumer can't handle that, the rest of the configuration doesn't matter.

A good queue isn't one that never fails. It's one where every failure has somewhere to go and someone who finds out.

## Prompt

```text
Act as a senior backend architect: review how my application processes queue messages and propose concrete changes to retries, dead letter queues and idempotency.

For each consumer:
- Classify the errors it can receive as transient (timeouts, 429, 5xx, dropped connections) or permanent (validation, 400, 401, 403, 404, data that doesn't exist). Permanent errors are not retried: they go straight to the DLQ or are discarded with a clear log line.
- Retries with exponential backoff and full jitter (random wait between 0 and min(cap, base · 2^attempt)), with a maximum number of attempts and a cap on the wait. If the target service returns Retry-After, honour it.
- Retry in a single layer. If the HTTP client, the consumer and the queue each retry on their own, attempts multiply.
- Every queue has its own DLQ, with a receive limit (in SQS, maxReceiveCount in the redrive policy) and a longer retention than the source queue.
- The visibility timeout is longer than the maximum time to process a message (with Lambda + SQS, at least 6 times the function timeout). When processing batches, report failures per message (ReportBatchItemFailures) so the whole batch isn't repeated.

Idempotency, first of all:
- Assume every message will be processed more than once. Each message carries a stable identifier and the consumer records which ones it has processed, or writes express a final state ("stock is 12") instead of a change ("subtract 3").

Operations:
- Alarm when the DLQ has any message and when the oldest message in the main queue is older than the business tolerates.
- A reprocessing procedure: inspect the DLQ messages, fix the cause and move them back to the source queue (in SQS, redrive from the console or StartMessageMoveTask).

Don't:
- Unbounded retries, or immediate retries with no wait.
- A DLQ without an alarm: it's a place where errors silently disappear.

Verify: what happens to a message that always fails (it must end up in the DLQ after N attempts), what happens if a message is processed twice (the result doesn't change) and what happens if the target service is down for ten minutes (the queue grows and drains on its own when it's back).

Before starting, ask me anything you can't infer (queue provider, external services, how much delay is acceptable) and explain each decision.
```
