← Study paths

Making retries safe

Every distributed system retries; most do it wrong. This path makes retries harmless.

7 blocks · about 37 min of reading · ends with Notification System

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.

  1. Never wait foreverFundamental
  2. Retry transient failures carefullyFundamental
  3. Make retries safeFundamental
  4. Decouple producer from consumerFundamental
  5. Drop duplicate eventsSenior
  6. Park poison messagesFundamental
  7. Stop calling a failing dependencySenior
  8. Notification System
Decoupling & async workReliability & failure handlingData processing & searchFundamentalSenior
Read each block, then tick “I can explain this”: the path remembers where you are.Start with step 1
Your Notification System so far0 of 7 blocks in
Idempotency keysAmazon ElastiCacheRedis SET NX, 24 h TTLProducer serviceAmazon EC2 Auto Scalingretries after a timeoutNotification APIAmazon EC2 Auto Scalingreturns 202 with thesame idChannel queuesAmazon SQSchannel × priority, atleast onceTwilioprimary SMS providerSent markersAmazon ElastiCacheSET NXsent:{delivery_id}SMS sender workerAmazon EC2 Auto Scalingcall deadline wellunder the 5 s p99Circuit breakererror rate perproviderDead-letter queueAmazon SQSalerted on, replayableDelay queueAmazon SQS2 s base, 10 min cap,6 triesSecondary SMS providertakes traffic while openStep 3: Make retries safe3Step 4: Decouple producer from consumer4Step 5: Drop duplicate events5Step 1: Never wait forever1Step 7: Stop calling a failing dependency7Step 6: Park poison messages6Step 2: Retry transient failures carefully2POST with keySET NX keypublishconsumeSET NX markersendclosedopen5xx or timeoutafter 6 tries

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.

Each block has a diagram. Open one beside its step, or all of them at once.
  1. Never wait forever

    Reliability & failure handlingfundamental~5 min

    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.

    Read this block →

  2. Retry transient failures carefully

    Reliability & failure handlingfundamental~5 min

    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.

    Read this block →

  3. Make retries safe

    Decoupling & async workfundamental~5 min

    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.

    Read this block →

  4. Decouple producer from consumer

    Decoupling & async workfundamental~6 min

    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?

    Return 202 with a job id and a status endpoint the client can poll with backoff. For interactive flows push the result over WebSocket or a notification instead. Either way the job record is the source of truth, written by the worker when it finishes.

    Read this block →

  5. Drop duplicate events

    Data processing & searchsenior~6 min

    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.

    Read this block →

  6. Park poison messages

    Decoupling & async workfundamental~5 min

    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.

    Read this block →

  7. Stop calling a failing dependency

    Reliability & failure handlingsenior~5 min

    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.

    Read this block →

  8. 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
    Idempotency keysAmazon ElastiCacheRedis SET NX, 24 h TTLProducer serviceAmazon EC2 Auto Scalingretries after a timeoutNotification APIAmazon EC2 Auto Scalingreturns 202 with thesame idChannel queuesAmazon SQSchannel × priority, atleast onceTwilioprimary SMS providerSent markersAmazon ElastiCacheSET NXsent:{delivery_id}SMS sender workerAmazon EC2 Auto Scalingcall deadline wellunder the 5 s p99Circuit breakererror rate perproviderDead-letter queueAmazon SQSalerted on, replayableDelay queueAmazon SQS2 s base, 10 min cap,6 triesSecondary SMS providertakes traffic while openStep 3: Make retries safe3Step 4: Decouple producer from consumer4Step 5: Drop duplicate events5Step 1: Never wait forever1Step 7: Stop calling a failing dependency7Step 6: Park poison messages6Step 2: Retry transient failures carefully2POST with keySET NX keypublishconsumeSET NX markersendclosedopen5xx or timeoutafter 6 tries

    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.

    1. Never wait forever
    2. Retry transient failures carefully
    3. Make retries safe
    4. Decouple producer from consumer
    5. Drop duplicate events
    6. Park poison messages
    7. Stop calling a failing dependency

    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.
  9. ★

    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.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon ElastiCacheIdempotency keys, Sent markers, Redis, Seen-setMemorystoreAzure Managed RedisRedis, Valkey, Memcached
Amazon EC2 Auto ScalingProducer service, Notification API, SMS sender worker, Feed service, Push worker, API, Workers, Redirect service, Aggregator, SMS sender, Alert + replay toolCompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad
Amazon SQSChannel queues, Dead-letter queue, Delay queue, Intake queue, Queue, sms-transactionalPub/Sub, Cloud TasksService Bus queues, Queue StorageRabbitMQ, ActiveMQ
Amazon API GatewayGatewayAPI Gateway, ApigeeAPI ManagementKong, Tyk
Amazon SageMakerRanking serviceVertex AIAzure Machine LearningKServe, Ray Serve, NVIDIA Triton
Amazon AuroraNotification DBAlloyDB for PostgreSQL, Cloud SQLAzure Database for PostgreSQL or MySQLPostgreSQL, MySQL, CockroachDB
Amazon DynamoDBJob status, Counts storeFirestore, BigtableCosmos DBScyllaDB, Apache Cassandra
Amazon Kinesis Data Streamsclicks topicPub/SubEvent HubsApache Kafka, Redpanda, Apache Pulsar