Idempotency, retries and dead-letter queues

Topic 8 of 9 in Week 4: Caching, queues and content delivery10 min readIntermediateFree course

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

Retries, idempotency and dead-letter queues. A message flows from the main queue to a consumer that checks the message ID. The consumer records it in a processed-IDs store to skip duplicates and performs the side effect, such as a charge, email or database write. If processing fails, the message goes to retry with backoff at 1, 2 and 4 seconds and so on, plus jitter, and is requeued to the main queue. After 5 attempts, the consumer gives up and sends it to a dead-letter queue. An idempotency key means the same message processed twice has the effect of once. Dead-letter messages trigger an alert; fix the bug, then replay them.

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:

Text
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.

Exercise

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.

Text
(a)
(b)
(c)
(d)
(e)

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.