Making retries safe
Every distributed system retries; most do it wrong. This path makes retries harmless.
When you finish, you should be able to say
Say why a retry can double-charge a customer, and name the three things that stop it.
The route
7 blocks (5 fundamental, 2 senior), then the practice problem.
- Never wait foreverFundamental
- Retry transient failures carefullyFundamental
- Make retries safeFundamental
- Decouple producer from consumerFundamental
- Drop duplicate eventsSenior
- Park poison messagesFundamental
- Stop calling a failing dependencySenior
- Notification System
Next, step 1 adds SMS sender worker (outlined). A box fills in when you tick “I can explain this” on the block that introduces it; plain boxes come from the problem itself.
A retry only exists because something timed out, so set the deadline first.
A hung downstream call ties up threads until the whole service stalls.
Say it like this: Every network call gets a timeout shorter than the deadline of whoever called me, and the deadline travels with the request, so a hung dependency costs one thread for a bounded time instead of the whole pool forever.
Adds to the design: SMS sender worker
Check yourself: How do you pick the number?
Start from the dependency’s p99 under normal load and add a margin, then check it fits inside the caller’s remaining deadline. A timeout well above p99 only protects against hangs; one near p50 turns normal variance into failures.
How to retry without turning one slow service into an outage for everyone.
A timeout or 503 fails the whole request, or naive retries pile on a struggling service.
Say it like this: Transient failures are normal, so every outbound call retries a bounded number of times with exponential backoff and full jitter, but only when the call is idempotent and the error is retryable, so retries fix blips instead of amplifying outages.
Adds to the design: Delay queue
Check yourself: Which errors do you retry?
Only ones that might succeed on a second try: connection errors, timeouts, 502/503/504, 429 with Retry-After, and broker-level redelivery. Never 400, 401, 403, 404 or 422; those tell you the request itself is wrong.
The property that makes a repeated request harmless; without it the rest of the path is unsafe.
A retried request or redelivered message creates a duplicate order, charge or notification.
Say it like this: Every retry path in this system can deliver the same request twice, so the client sends an idempotency key and the server stores the result under it, which turns a duplicate into a cheap replay instead of a second charge.
Adds to the design: Idempotency keys
Check yourself: What should the server return on a duplicate?
The same status and body as the first response, so the client cannot tell it was a replay. If the first attempt is still running, return 409 Conflict with a hint to retry, because returning success before the work finished would be a lie.
Queues deliver at least once, which means every consumer is being retried whether it asked or not.
The request path waits on slow work (email, resize, analytics) or on a service that may be down.
Say it like this: The request only needs the write to be durable, not the email to be sent, so I enqueue a job and return 202; workers drain the queue at their own pace and a slow provider never blocks the API.
Adds to the design: Channel queues
Check yourself: How does the client find out the work is done?
When you cannot make the handler idempotent, drop the duplicate before it does harm.
At-least-once delivery double counts clicks, views and payments.
Say it like this: The click stream is at-least-once, so every event carries a unique id and the counter drops ids it has seen within a window longer than the retry window, which keeps the counts honest without making the producers exactly-once.
Adds to the design: Sent markers
Check yourself: Why is exactly-once delivery not the answer?
A broker can guarantee exactly-once between its own topics, but the consumer still writes to an external store, and that write plus the offset commit are two systems. Idempotent application at the consumer is what gives exactly-once effect; delivery stays at-least-once.
Some messages fail every time; this is where they go so they stop blocking the rest.
One malformed message fails forever and blocks or wastes a worker.
Say it like this: A message that fails every retry must not block the queue or vanish, so after N attempts the broker moves it to a dead-letter queue that pages someone and can be replayed once the bug is fixed.
Adds to the design: Dead-letter queue
Check yourself: How many attempts before dead-lettering?
Enough to ride out a short outage of the dependency, which with exponential backoff is usually five to eight attempts over ten to thirty minutes. Beyond that, something is actually broken and a human should look. Permanent errors get zero retries.
Finish by stopping retries altogether when the dependency is clearly down.
A dead service makes every caller wait for a timeout, cascading the outage.
Say it like this: When a dependency is down, waiting for every call to time out is the thing that spreads the outage, so a breaker watches the error rate, opens after a threshold, fails fast with a fallback, and probes periodically to close again.
Adds to the design: Circuit breaker
Check yourself: What is the difference between a breaker and a retry?
A retry tries harder for one request; a breaker stops trying for all requests. They work together: retries handle blips lasting milliseconds, the breaker handles outages lasting seconds or minutes and keeps retries from amplifying them.
Putting it together
How the blocks above combine into one design for Notification System. The numbers on the boxes are the steps that introduce each part.
Safe notification delivery, assembled from the path Each number is a step of this path; a box with two numbers is shaped by both blocks. The ring colour is the block's category, as on the route map. Boxes without a number come from the problem itself. Point at a step below, or at a bubble, to see where it appears.
A producer's retried call is absorbed by the idempotency key, queues carry each delivery to a sender pool, and every provider call is bounded, deduplicated, retried with backoff, parked when it keeps failing and rerouted when the provider is down.
How each block shows up in the design
- 1. Never wait forever: every provider call from a sender worker has a deadline well inside the 5 second p99 from submit to hand-off, so a hung Twilio connection holds one worker slot for a bounded time and then counts as a transient failure.
- 2. Retry transient failures carefully: a 5xx or a timeout re-publishes the message to a delay queue with exponential backoff and jitter, base 2 seconds, capped at 10 minutes and at most 6 attempts for transactional, so nothing sleeps inside a worker and a recovering provider is not hammered.
- 3. Make retries safe: the producer sends an idempotency key that names the business event, and the API's SET NX in Redis with a 24 hour TTL returns the same notification id to a retried call instead of creating a second notification.
- 4. Decouple producer from consumer: the API only writes a row and a queue message and returns 202, and one queue per channel and priority lets a 33K per second campaign peak drain at provider rate limits while a one-time password still goes out in seconds.
- 5. Drop duplicate events: the queues deliver at least once, so before each provider call the worker sets a sent marker keyed by delivery id, and a redelivered message finds the marker and skips the send.
- 6. Park poison messages: after the last attempt, or once the notification has expired, the message moves to a dead-letter queue with every attempt's error; its depth is alerted on and a replay tool re-enqueues it once the provider recovers.
- 7. Stop calling a failing dependency: a circuit breaker counts errors per provider and, past a threshold, sends new messages to a secondary provider until the primary recovers, so retries stop piling onto an outage.
- ★
Notification System
Now run the timed practice. The blocks above should appear in your answer without prompting; if one does not, that is the one to reread.
The same parts on other clouds
The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.
| AWS | Used here as | Google Cloud | Microsoft Azure | Open source and others |
|---|---|---|---|---|
| Amazon ElastiCache | Idempotency keys, Sent markers, Redis, Seen-set | Memorystore | Azure Managed Redis | Redis, Valkey, Memcached |
| Amazon EC2 Auto Scaling | Producer service, Notification API, SMS sender worker, Feed service, Push worker, API, Workers, Redirect service, Aggregator, SMS sender, Alert + replay tool | Compute Engine managed instance groups | Virtual Machine Scale Sets | Kubernetes Deployment with a HorizontalPodAutoscaler, Nomad |
| Amazon SQS | Channel queues, Dead-letter queue, Delay queue, Intake queue, Queue, sms-transactional | Pub/Sub, Cloud Tasks | Service Bus queues, Queue Storage | RabbitMQ, ActiveMQ |
| Amazon API Gateway | Gateway | API Gateway, Apigee | API Management | Kong, Tyk |
| Amazon SageMaker | Ranking service | Vertex AI | Azure Machine Learning | KServe, Ray Serve, NVIDIA Triton |
| Amazon Aurora | Notification DB | AlloyDB for PostgreSQL, Cloud SQL | Azure Database for PostgreSQL or MySQL | PostgreSQL, MySQL, CockroachDB |
| Amazon DynamoDB | Job status, Counts store | Firestore, Bigtable | Cosmos DB | ScyllaDB, Apache Cassandra |
| Amazon Kinesis Data Streams | clicks topic | Pub/Sub | Event Hubs | Apache Kafka, Redpanda, Apache Pulsar |