Idempotency, retries and dead-letter queues
Overview
In distributed systems, failures are routine: a timeout, a restarted pod, a brief network blip, a rate-limited API. The usual cure is to retry. But naive retries can charge customers twice, flood a struggling service, or loop forever on a message that will never succeed. This lesson covers how to retry safely.
The full picture
What to retry
Not every failure deserves a retry:
| Retry | Don’t retry |
|---|---|
| Timeouts, connection resets | 400 Bad Request (the input is wrong) |
| 429 Too Many Requests (after waiting) | 401/403 (credentials or permissions) |
| 500, 502, 503, 504 | 404 (unless eventual consistency is expected) |
| Deadlocks and serialization failures | Validation and business-rule failures |
Permanent failures should fail fast, with a clear error, and in queues go straight to the dead-letter queue.
Backoff and jitter
Retrying immediately, again and again, makes things worse: if a service is overloaded, a wall of instant retries keeps it down. Use exponential backoff: wait 1 s, then 2 s, 4 s, 8 s… up to a cap (say 1–5 minutes).
Add jitter (randomness). If 10,000 clients all failed at the same moment and all retry after exactly 2 s, they hit the service in a synchronised wave. With jitter, retries spread out:
delay = random(0, min(cap, base × 2^attempt)) # "full jitter"Also respect Retry-After headers, and give up after a maximum number of attempts or total time.
Idempotency: making retries safe
A retry is safe only if doing the operation twice has the same effect as doing it once. Timeouts make this unavoidable: when a request times out, you don’t know whether it was processed.
Techniques:
- Idempotency keys: the caller generates a unique key per logical operation (an order ID, a UUID per button press) and sends it with each attempt. The server stores the key with the result; repeated keys get the stored result. Payment APIs such as Stripe use exactly this.
- Unique constraints: a unique index on
(order_id)in the payments table, or on(user_id, email_type)for sent emails, turns a duplicate into a harmless constraint violation. - Processed-message table: record message IDs as they’re handled, in the same transaction as the work.
- Idempotent operations by design: “set balance to X with version 8” rather than “add 10”; “upsert document 981” rather than “append”.
Store idempotency records long enough to cover the retry window (hours to days).
Dead-letter queues
Some messages will never succeed: malformed data, a bug triggered by one specific input, a deleted user. Retrying them forever wastes resources and, in ordered systems, blocks everything behind them. These are poison messages.
A dead-letter queue (DLQ) catches messages that failed too many times (for example maxReceiveCount = 5 on SQS). Good practice:
- include the error, stack trace and attempt count with the message,
- alert when anything lands in the DLQ for important flows,
- provide a tool to inspect and replay messages after fixing the bug,
- never let the DLQ grow silently; it’s lost work in disguise.
For ordered streams (Kafka), a poison message can stall a partition. Common patterns are a retry topic with delays and a DLQ topic, so the main partition keeps moving.
Don’t multiply retries
If a mobile app retries 3 times, the gateway retries 3 times, and the service retries its database call 3 times, one user action can become 27 database attempts during an outage, exactly when the database is weakest. Guidelines:
- retry at one layer, usually closest to the failure,
- use a retry budget (for example, retries may add at most 10% extra load),
- combine with circuit breakers (week 6) that stop calling a failing dependency altogether.
In an interview
Any time you add a queue or call an external service, add one sentence: “Consumers retry transient failures with exponential backoff and jitter, up to five times, then move the message to a DLQ that alerts the on-call engineer; processing is idempotent using the order ID.” It shows you’ve thought about failure, which is exactly what interviewers probe.
Recap
Retry transient failures, not permanent ones, using exponential backoff with jitter and a limit. Make operations idempotent with idempotency keys, unique constraints and processed-ID records, so retries can’t double-apply. Send repeatedly failing messages to a dead-letter queue, alert on it and replay after fixing the cause, and avoid stacking retries at every layer.
Design the retry policy
A consumer sends welcome emails via a third-party email API. Sometimes the API returns 503 or times out; sometimes a message has an invalid email address and the API returns 400. The provider allows 100 requests per second. Design: (a) which errors to retry and which not, (b) the retry schedule, (c) how to avoid sending the same email twice, (d) what happens to messages that keep failing, and (e) what you monitor.
(a)
(b)
(c)
(d)
(e)(a) Retry transient errors: timeouts, 429, 500, 502, 503, 504, connection errors.
Don't retry permanent errors: 400 (invalid email), 401/403 (fix config), 404.
Send those straight to the DLQ (or mark the user's email as invalid).
(b) Exponential backoff with full jitter, e.g. base 1 s doubling to a 5-minute cap:
delay = random(0, min(300 s, 1 s x 2^attempt)), up to ~8 attempts.
Respect Retry-After on 429. Limit total send rate to stay under 100/s
(a token bucket in the consumer).
(c) Idempotency: use a key such as "welcome:{user_id}" - pass it to the provider as
an idempotency key if supported, and record "sent" in our DB with a unique
constraint before/after the call so a redelivered message is skipped.
(d) After the max attempts, move the message to a dead-letter queue with the error
details and attempt count; alert; after fixing the cause, replay from the DLQ.
(e) Monitor: error rate by type, retry count, age of oldest message in the main
queue, DLQ size (alert if > 0 for important flows), provider latency.Summary
- Retry only transient failures (timeouts, 429, 5xx); permanent errors such as 400 should fail fast.
- Use exponential backoff with jitter and a cap, so retries don't hammer a struggling service in synchronised waves.
- Retries are only safe when the operation is idempotent: use idempotency keys, unique constraints and processed-ID tables.
- Limit retries per message and send repeated failures to a dead-letter queue for inspection and replay.
- Retry at one layer only, with a budget; retries at every layer multiply load during an outage.