Skip to content

Retry with Backoff: Exponential Delays, Jitter and Retry Budgets

How to retry failed calls without turning a short outage into a retry storm, using one retry layer, exponential backoff, full jitter and a retry budget.

20 min readSystem pattern

Recover from transient failures automatically while keeping the extra load from retries small and bounded. Attempts are spaced exponentially, randomised so clients do not synchronise, limited by a deadline, and paid for out of a budget that runs dry when the dependency is unhealthy.

A retry is a bet that the next attempt will succeed where the last one failed. When the failure is a dropped packet or a pod restart, that bet usually pays. When the dependency is overloaded, every retry adds load to the thing that is already falling over, and a ten-second blip can become a thirty-minute outage. This guide follows one invented incident at a ticketing company and rebuilds its retry logic step by step. It retries at exactly one layer. It spaces attempts with exponential backoff and randomises them with jitter. It caps total retry traffic with a budget so the system cannot multiply its own load. These are the parts interviewers probe when you say "and we'd add retries".

The problem

A situation where the obvious design starts to hurt.

Gatehouse sells concert tickets. During a big on-sale, its checkout service takes about 4,000 requests per second, and every checkout calls the seat-hold service to reserve seats. Seat-hold is backed by a Postgres primary with a standby and can sustain roughly 6,000 requests per second.

At 19:00 on a stadium on-sale, the seat-hold primary failed over. Seat-hold refused connections for 12 seconds. Three layers then retried independently. The mobile app retried 3 times, 1 second apart. The API gateway retried 5xx responses twice. The checkout service's seat-hold client retried 3 times with a fixed 1-second sleep. In the worst case, one user tap became (1+3) x (1+2) x (1+3) = 48 calls to seat-hold.

When the new primary came up, it faced the normal on-sale traffic plus every queued retry, and all of them arrived on the same 1-second boundaries because the delays were fixed. Seat-hold's 200-connection pool saturated and latency rose past the 1-second client timeout. Those timeouts counted as failures, so they triggered more retries. The original fault was gone after 12 seconds, but the system stayed down for 34 minutes because the retry traffic alone exceeded capacity. Engineers only recovered it by shedding traffic at the load balancer.

The post-incident review found four separate problems. Retries were multiplied across layers. The delays were fixed, so clients stayed synchronised. Nothing limited how much retry traffic the fleet could generate. And 409 seat-already-taken responses were being retried, even though a retry could never change that answer.

The solution

What the pattern proposes.

Gatehouse rebuilt retries around five rules.

First, retry at one layer only. The seat-hold client inside checkout owns retries. The gateway no longer retries 5xx responses. The mobile app retries only when it gets no response at all, never on an error response from the server.

Second, classify before retrying. Connection refused, connection reset, 502, 503, 504 and 429 are retryable. 400, 404, 409 and 422 are not, because the next attempt will get the same answer.

Third, use exponential backoff with full jitter. Before retry n (counting from 0), sleep a random duration between 0 and min(cap, base x 2^n), with a base of 100 ms and a cap of 2 s. The exponential part slows the clients down as failures continue. The random part spreads them out, so the recovering server sees a smooth arrival rate instead of waves. If the server sends Retry-After, the client waits at least that long.

Fourth, bound attempts by a deadline as well as a count. A checkout has a 2-second budget for seat-hold, each attempt times out at 400 ms, and there are at most 3 attempts. If the next sleep would cross the deadline, the client gives up immediately instead of sleeping uselessly.

Fifth, add a retry budget. Each checkout process keeps a token bucket. Every first attempt deposits 0.1 tokens and every retry withdraws 1, with the bucket capped at 100 tokens. When seat-hold is healthy, almost nothing fails and the bucket stays full. When seat-hold is down, retries drain the bucket within seconds, and after that the process sends at most about 1.1 calls per checkout instead of 3. In the incident replay, the maximum amplification dropped from 48x to roughly 1.1x.

Retries on POST /holds are only safe because each request carries an Idempotency-Key. A retry after a timeout cannot create a second hold.

An everyday analogy

The same idea, outside software.

Think of a busy bakery that runs out of bread at 8:00, with fresh loaves due in ten minutes. If every customer comes back at exactly 8:05, 8:06 and 8:07, the counter is mobbed three times and the staff can't bake. If each customer waits a random few minutes, longer each time they're turned away, arrivals spread out and the counter stays workable.

The budget is the bakery's rule that only a limited number of people per hour get a "come back later" ticket. Everyone else is told to try tomorrow. That keeps the shop from filling up with return visits while it is trying to recover.

Structure

The pieces and how they relate.

Gatehouse checkout after the fix: only the seat-hold client retries, with jittered backoff, a deadline and a per-process retry budget.Mobile app calls API gateway (POST /checkout). API gateway calls Checkout service. Checkout service calls Seat-hold client (holdSeats()). Seat-hold client calls Retry budget (withdraw before retry). Seat-hold client calls Seat-hold service (POST /holds + Idempotency-Key). Seat-hold service calls Seat DB. Seat-hold service sends to Seat-hold client (503 + Retry-After). Seat-hold client sends asynchronously to Metrics (retry counters).Mobile appretries only when noresponseAPI gateway5xx retries disabledCheckout service4,000 req/s aton-sale peakDeadline2 s total, 400 msper attemptSingle retrylayeredges pass failuresthroughRetry budgettoken bucket: +0.1per call, -1 pe…Seat-hold clientclassify, back off,jitterSeat-hold service~6,000 req/scapacitySeat DBPostgres primary +standbyDelay beforeretry nrand(0, min(2 s, 100ms x 2^n))Metricsretries, budgetdenials, give-upsPOST /checkoutholdSeats()withdraw before retryPOST /holds + Idempotency-Key503 + Retry-Afterretry counters
Gatehouse checkout after the fix: only the seat-hold client retries, with jittered backoff, a deadline and a per-process retry budget.

Participants

Seat-hold client (the retry layer)
The only component that retries. It wraps each call to seat-hold, classifies the result, computes a jittered delay, checks the deadline and the budget, and either sleeps and tries again or gives up with the original error attached.
Retry policy
Configuration for the loop: 3 maximum attempts, 100 ms base, 2 s cap, 400 ms per-attempt timeout, and the set of retryable statuses (429, 502, 503, 504, plus connection-level errors). It lives in config so you can tune it without a deploy.
Retry budget
A per-process token bucket. Each first attempt deposits 0.1 tokens and each retry costs 1. The cap is 100 tokens. When the bucket is empty, the client returns the failure instead of retrying, which limits retry traffic to about 10% of normal traffic during an outage.
Seat-hold service
The dependency. It returns 503 with Retry-After when it is shedding load and 409 when a seat is already taken. It deduplicates POST /holds by Idempotency-Key, which is what makes retrying a write safe.
Edge layers (app and gateway)
They pass failures through instead of retrying them. The app retries only when it gets no response at all, and it reuses the same idempotency key, so the server-side dedup absorbs the duplicate.
Metrics
Counts attempts per call, retries, budget denials and deadline give-ups. Alerts fire when the retry rate passes 5% of calls, which shows up before the dependency is fully down.

Pseudocode

The solution to the scenario, language-neutral.

policy = { maxAttempts: 3, base: 100ms, cap: 2s }
budget = TokenBucket(depositPerCall: 0.1, costPerRetry: 1, max: 100)

function holdSeats(request, deadline):
    budget.deposit()                        // every first attempt pays in
    attempt = 0
    loop:
        result = seatHold.post(request, key = request.idempotencyKey,
                               timeout = min(400ms, deadline - now()))
        if result.ok:
            return result.value
        if not isRetryable(result):         // 400, 404, 409, 422
            raise result.error
        if attempt + 1 >= policy.maxAttempts:
            raise GiveUp("attempts exhausted", cause = result.error)

        ceiling = min(policy.cap, policy.base * 2^attempt)
        delay = random(0, ceiling)          // full jitter
        delay = max(delay, result.retryAfter or 0)

        if now() + delay >= deadline:
            raise GiveUp("deadline", cause = result.error)
        if not budget.withdraw():
            raise GiveUp("retry budget empty", cause = result.error)

        metrics.increment("seat_hold.retry")
        sleep(delay)
        attempt = attempt + 1

function isRetryable(result):
    return result.isConnectionError
        or result.status in {429, 502, 503, 504}

The code

The same solution in TypeScript, Python and PHP.

// Retry loop for the seat-hold client: one layer, full jitter, deadline, budget.

type Outcome<T> =
  | { ok: true; value: T }
  | { ok: false; error: Error; retryable: boolean; retryAfterMs?: number };

interface RetryPolicy {
  maxAttempts: number;
  baseMs: number;
  capMs: number;
}

class RetryGivenUp extends Error {
  constructor(reason: string, readonly cause: Error) {
    super(`${reason}: ${cause.message}`);
  }
}

// Per-process token bucket: first attempts deposit, retries withdraw.
class RetryBudget {
  private tokens: number;
  constructor(private readonly ratio = 0.1, private readonly maxTokens = 100) {
    this.tokens = maxTokens;
  }
  recordRequest(): void {
    this.tokens = Math.min(this.maxTokens, this.tokens + this.ratio);
  }
  tryWithdraw(): boolean {
    if (this.tokens < 1) return false;
    this.tokens -= 1;
    return true;
  }
}

const RETRYABLE_STATUSES = new Set([429, 502, 503, 504]);
const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));

function fullJitter(attempt: number, p: RetryPolicy): number {
  const ceiling = Math.min(p.capMs, p.baseMs * 2 ** attempt);
  return Math.random() * ceiling;
}

async function callWithRetry<T>(
  op: (attempt: number) => Promise<Outcome<T>>,
  policy: RetryPolicy,
  budget: RetryBudget,
  deadlineMs: number,
): Promise<T> {
  budget.recordRequest();
  let attempt = 0;
  while (true) {
    const outcome = await op(attempt);
    if (outcome.ok) return outcome.value;
    if (!outcome.retryable) throw outcome.error;
    if (attempt + 1 >= policy.maxAttempts) {
      throw new RetryGivenUp("attempts exhausted", outcome.error);
    }
    const delay = Math.max(fullJitter(attempt, policy), outcome.retryAfterMs ?? 0);
    if (Date.now() + delay >= deadlineMs) {
      throw new RetryGivenUp("deadline would pass", outcome.error);
    }
    if (!budget.tryWithdraw()) {
      throw new RetryGivenUp("retry budget empty", outcome.error);
    }
    await sleep(delay);
    attempt += 1;
  }
}

// Demo: seat-hold returns 503, then 429 with Retry-After 300 ms, then succeeds.
// A real op would send POST /holds with an Idempotency-Key and a 400 ms timeout.
const responses: Array<{ status: number; retryAfterMs?: number }> = [
  { status: 503 },
  { status: 429, retryAfterMs: 300 },
  { status: 200 },
];

async function fakeHold(attempt: number): Promise<Outcome<string>> {
  const r = responses[attempt];
  if (r.status === 200) return { ok: true, value: "hold-81f2" };
  return {
    ok: false,
    error: new Error(`seat-hold returned ${r.status}`),
    retryable: RETRYABLE_STATUSES.has(r.status),
    retryAfterMs: r.retryAfterMs,
  };
}

async function main(): Promise<void> {
  const policy: RetryPolicy = { maxAttempts: 3, baseMs: 100, capMs: 2000 };
  const budget = new RetryBudget(0.1, 100);
  const holdId = await callWithRetry(fakeHold, policy, budget, Date.now() + 2000);
  console.log(`seat hold created: ${holdId}`);
}

main().catch((err) => {
  console.error(err.message);
  process.exit(1);
});

When to use it

Situations where it pays off.

  • The failure is likely transient: connection resets during a deploy, a database failover, a pod being rescheduled, or a 503 from a server shedding load.

    Such failures clear within seconds. A spaced-out retry hides them from the user, so they do not show up as a failed checkout.

  • The operation is idempotent, or you can make it idempotent with a key the server deduplicates on.

    After a timeout you cannot know whether the first attempt was applied. Retrying is only safe if applying it twice has the same effect as applying it once.

  • You have a caller-side deadline and the retry still fits inside it.

    A retry that lands after the user has given up, or after the upstream timeout has fired, does work nobody will read. The deadline is what turns retries from hopeful into bounded.

  • Many clients share one dependency and failures are correlated, as in a fleet of checkout pods all calling seat-hold.

    This is where jitter and budgets matter most. Synchronised retries from hundreds of pods make up the retry storm, and a per-process budget limits what each pod adds to it.

How to implement it

Steps to introduce it in existing code.

  1. Pick one retry layer, usually the client closest to the dependency. Turn off retries on 5xx at the gateway and in the SDKs above it, and write down that decision so nobody quietly turns them back on.

  2. Classify errors explicitly. Retry connection-level failures and 429, 502, 503 and 504. Never retry 400, 401, 403, 404, 409 or 422. Treat a client-side timeout as retryable only if the request carries an idempotency key.

  3. Compute the delay as random(0, min(cap, base x 2^attempt)), starting with base 100 ms and cap 2 s. If the response has Retry-After, wait at least that long.

  4. Pass a deadline down from the inbound request, and set each attempt's timeout to the smaller of the per-attempt limit and the remaining time. Stop as soon as the next sleep would cross the deadline.

  5. Add a per-process retry budget: deposit 0.1 tokens per first attempt, withdraw 1 per retry, cap at 100. Size the ratio to the extra load the dependency can absorb during recovery.

  6. Emit metrics for attempts, retries, budget denials and deadline give-ups. Alert on the retry ratio, and replay an outage in a load test to confirm that amplification stays near 1.1x.

Pros and cons

What you gain and what you pay.

Pros

  • Transient faults such as failovers, deploys and dropped connections are invisible to users, without anyone writing manual recovery code.
  • Full jitter spreads retries evenly across the backoff window, so a recovering service sees a smooth rate instead of synchronised spikes.
  • A retry budget puts a hard ceiling on load amplification. During the Gatehouse replay the ceiling was about 1.1x, compared with 48x before.
  • Deadlines keep the worst-case latency predictable: a checkout fails within 2 s instead of hanging through stacked sleeps.

Cons

  • Successful-but-retried requests are slower. A call that succeeds on attempt 3 can take up to about 1.5 s instead of 400 ms.
  • Writes need idempotency keys and server-side dedup storage. That is real work and an extra table or cache to run.
  • Per-process budgets are local. With 300 pods, each one has its own 100-token burst, so the first seconds of an outage can still add up to 30,000 retries fleet-wide.
  • Retries hide flakiness. Without metrics on retry rate, a dependency can degrade for weeks while dashboards still show 100% success.

Trade-offs

Decisions you'll have to make, each with its price.

  • Cap of 2 s versus 10 s on the backoff ceiling

    You gainA 2 s cap keeps the retry inside a 2 s checkout deadline, so the user gets a fast answer either way.

    You payAgainst a dependency that is down for 30 s or more, 2 s spacing gives up sooner. That is fine for interactive calls, but background jobs should use a higher cap and more attempts.

  • 3 attempts versus 5

    You gainThree attempts cover the common single-blip case and keep worst-case latency at about 1.5 s with 400 ms per-attempt timeouts.

    You payTwo consecutive transient failures, such as a failover followed by a cold connection pool, fail the checkout where a fourth attempt might have worked.

  • Per-process budget versus a shared budget in Redis

    You gainA per-process budget has no network hop and no dependency, and it keeps working while Redis is down.

    You payEach pod gets its own burst. 300 pods x 100 tokens allow 30,000 retries fleet-wide before the budgets drain. A shared budget limits that burst globally but adds a call to every retry decision.

  • Honouring Retry-After over your own jittered delay

    You gainThe server knows its own recovery time. A seat-hold node that sends Retry-After: 5 during failover gets real breathing room.

    You payA buggy server can send Retry-After: 3600. Clamp it to your deadline and give up instead of sleeping, and alert when that clamp is hit.

How it fails

What goes wrong in production and how to prevent it.

  • Retries at several layers multiply into a storm: 48x amplification in the original Gatehouse incident.

    What to doMake one layer own retries. Disable 5xx retries in the gateway config and in client SDKs, and add a test that asserts the gateway's retry count is 0. Propagate a header such as X-Retry-Attempt so a downstream service can detect nested retries and log them.

  • Fixed or unjittered delays keep clients synchronised, so the recovering service is hit in waves on each backoff boundary.

    What to doUse full jitter on every delay, including the first. Check it in a load test by plotting seat-hold arrivals per 100 ms during a simulated failover. The plot should be flat, without spikes at 100, 200 and 400 ms.

  • Timeouts trigger retries that lengthen queues, which cause more timeouts. The system stays down after the original fault clears.

    What to doThe retry budget breaks this loop: once the bucket drains, retry traffic is limited to about 10% of normal. Pair it with a circuit breaker that opens at a 50% failure rate over 10 s, and with server-side load shedding that returns 503 early instead of queueing.

  • Non-retryable errors are retried, such as 409 seat taken or 422 validation failures. This wastes capacity and delays the real error.

    What to doUse an explicit allowlist of retryable conditions instead of a denylist. Unit-test the classifier against each status code seat-hold documents, and default unknown statuses to not retryable.

  • A timed-out write is retried without an idempotency key, which creates duplicate holds and oversells seats.

    What to doGenerate the Idempotency-Key once per checkout and reuse it on every attempt. Have seat-hold store keys for 24 hours with the original response, and return that stored response on a duplicate.

In a system design interview

When to bring it up and how to explain it.

Bring this up whenever your design has a synchronous call to another service or database, and especially when the interviewer asks what happens during a deploy, a failover or a partial outage. Say it right after you mention timeouts, because the two only work together.

What you could say

I'd retry only in the client closest to the dependency, so for checkout that's the seat-hold client. The gateway and the app pass errors through. Otherwise retries multiply: three layers with three retries each is 64 calls per click.

I'd retry only transient failures, meaning connection errors and 429, 502, 503 and 504, never a 409 or a 422. Writes carry an idempotency key so a retry after a timeout can't double-book.

The delay is exponential with full jitter: a random value between 0 and min(2 seconds, 100 ms times 2 to the attempt). The jitter matters because without it every pod retries on the same boundary and the recovering service gets hit in waves. If the server sends Retry-After, I wait at least that long.

Each checkout has a 2 second deadline and 400 ms per attempt, so I stop when the next sleep would pass it.

Finally, there's a retry budget: a token bucket per process where each call earns 0.1 tokens and each retry costs one. During a real outage it drains in seconds and retries drop to about 10% extra load, so the dependency can actually recover.

Likely follow-ups

How does this interact with a circuit breaker?

The breaker sits outside the retry loop. When it is open, the call fails immediately without spending any budget or sleeping. The budget limits extra load during partial failure, and the breaker cuts load to zero during total failure. With half-open probes, it lets a few requests through so the system can detect recovery.

What would you do differently for a background job instead of a user request?

The deadline becomes minutes or hours, so I'd raise the cap to something like 5 minutes and allow more attempts. Usually I'd hand the retry to the queue's redelivery with a visibility-timeout backoff instead of sleeping in-process. After N attempts the message goes to a dead-letter queue so a single bad message can't loop forever.

How would you verify that retries help rather than hurt?

Watch three metrics: retries as a share of calls, budget denials, and attempts per successful call. Then run a game day that kills the seat-hold primary under on-sale load. Success means arrivals at seat-hold stay at or below about 1.1x normal and error rates return to baseline within seconds of the failover finishing.

Why a token bucket for the budget instead of a simple retries-per-second limit?

A ratio scales with traffic: 10% of 400 requests per second off-peak and 10% of 4,000 during an on-sale. A fixed limit is either too tight at peak or too loose off-peak. The bucket also allows short bursts when retries are rare, which is exactly when they are most likely to succeed.

Relations with other guides

Patterns it's often confused or combined with.

Common questions

Short answers to the usual doubts.

Full jitter, equal jitter or decorrelated jitter: which should I use?

Full jitter picks a delay uniformly in [0, ceiling]. It spreads clients the most, and it is the simplest to reason about. Equal jitter keeps half the ceiling fixed and randomises the other half. That guarantees a minimum wait but leaves clients more clustered. Decorrelated jitter bases each delay on the previous one, which also works but is harder to bound. Start with full jitter. Switch only if you need a guaranteed minimum wait, and in that case Retry-After from the server is usually the better tool.

Why not let every layer retry a little, just to be safe?

Retries multiply across layers. Three layers that each make up to 3 extra attempts produce up to 4 x 4 x 4 = 64 calls per user action. Those calls arrive exactly when the dependency is weakest. Retry at the layer that understands the error and holds the idempotency key, which is usually the client nearest the dependency. Every other layer should pass the failure through.

Is it ever safe to retry a non-idempotent POST?

It is safe if the request never reached the server, for example connection refused or a TLS handshake failure. After a timeout or a reset mid-response you cannot tell whether the server applied it. Either add an idempotency key that the server deduplicates on, or do not retry. In that case, surface the error and let a reconciliation job or the user decide.

How do I pick the budget ratio?

Ask how much extra load the dependency can take while it recovers. Seat-hold runs at about 4,000 of its 6,000 requests per second during on-sales, so it has roughly 50% headroom. A 10% budget fits well inside that. A dependency running near capacity might need 5%. Also cap the bucket so the initial burst across all pods stays survivable: 300 pods x 100 tokens is already 30,000 retries.

Now, practise it

Put it to work straight away.

Tests, exercises and problems that use what you've just read.

Next guide3 of 6 · ResilienceTimeouts and Deadline PropagationRead the next one