Skip to content

    Frontend System Design

    Client Retries, Exponential Backoff and Jitter

    Retry the right failures in the browser: idempotency keys, jittered exponential backoff, Retry-After, user cancel and retry budgets, with a virtual-clock lab.

    By Published 16 min read

    • frontend-system-design
    • retries
    • backoff
    • jitter
    • idempotency
    Share

    Standard lessonintermediateTypeScript labFrontend System Design

    Before this: Request Cancellation, Timeouts and Race Conditions, Timeouts, Retries, Exponential Backoff and Jitter

    What you'll learn: By the end of this lesson you will be able to decide which failed requests a browser client may repeat, compute a jittered exponential delay and honour a Retry-After header, explain why a write needs an idempotency key before it can be retried, keep retries from stacking across layers of a front end, stop retrying when the user cancels, and read a captured trace of a retrying client that runs on a virtual clock.

    A lift button is a small lesson in retries. Press it once and wait: fine. Hammer it ten times and you gain nothing, you only annoy everyone and, if it is a shared panel, make the next person wait. A good rider presses once, waits a little, and only then presses again, and does not press at all if the sign says the lift is out of order.

    A front end retries for the same reason: networks and servers fail in short bursts, and a repeat a moment later often works. But every retry is extra load on something that just failed, and a repeat of the wrong request can do harm twice. The previous lesson, Request Cancellation, Timeouts and Race Conditions, covers how a client stops waiting. This one covers what it does next. The back-end lesson on timeouts, retries, backoff and jitter has the full comparison of jitter rules and retry budgets from the server's side; here the focus is what is specific to a browser client.

    The running example is a grocery product page. It loads a product list with GET, and a "Place order" button sends a POST. All delays and counts are illustrative unless a source is named.

    The core idea

    Keep three statements in mind.

    1. A retry is a bet that the failure was brief, paid for with extra load. So it must be bounded in count, in time and in rate, and it must be spread out so that many clients do not retry at the same moment.
    2. Only repeat what can be repeated. After a timeout or a dropped connection the client does not know whether the server acted. RFC 9110 says a client should not automatically retry a request with a non-idempotent method unless it knows the request is actually idempotent, or can detect that the original was never applied. A write becomes retryable when it carries an idempotency key that the server honours.
    3. The user is part of the loop. A cancel must stop the retries, a wait must be visible, and the total time must stay bounded by a deadline, not by the sum of the attempts.

    Who retries? One layer, on purpose

    A request in a real page passes through several places that may each decide to try again: the user (a "Retry" button, a refresh), a data library, a fetch wrapper, and the browser's own network stack. TanStack Query, for example, retries failed queries by default: its documentation gives a default of 3 retries, with a delay that doubles from 1000 ms and does not exceed 30 seconds. If your own wrapper also retries up to 4 attempts, one user action can become 4 attempts of the library times 4 of the wrapper, 16 requests, before the user has pressed anything again.

    Figure 1. Retries multiply across layers

    Each layer retries on its own, so the counts multiplyUser to Data library (1); Data library to Fetch wrapper (x4); Fetch wrapper to Server (x4)User: presses RetryUserpresses RetryData library: 4 attemptsData library4 attemptsFetch wrapper: 4 attemptsFetch wrapper4 attemptsServer: 16 requestsServer16 requests1x4x4

    How to read this: the library sees a failure after the wrapper has already tried four times, and tries again. The arithmetic is 4 x 4 = 16 for one user action. Illustrative counts, built from the library's default of 3 retries and a wrapper of 4 attempts.

    The Amazon Builders' Library makes the same point for server layers: if each layer retries independently, the load on a database can grow 243 times (its example). The same multiplication happens inside a browser. Decide which layer owns retrying, switch it off in the others (TanStack's retry: false disables retries for a query), and let that one layer apply the policy below.

    Which failures are worth repeating

    Three questions, in order.

    Figure 2. Should this request be retried?

    flowchart TD accTitle: Deciding whether to retry a failed request accDescr: First check whether the failure is permanent, such as a 404, and give up if so. Then check whether the request is safe to repeat because its method is idempotent or it carries an idempotency key. Then check the attempt count. If all pass, wait the computed delay and try again. A["Attempt failed"] --> B{"Permanent error?
    (4xx such as 404, 401)"} B -->|"yes"| X["Give up: show the error"] B -->|"no"| C{"Safe to repeat?
    idempotent method
    or idempotency key"} C -->|"no"| X C -->|"yes"| D{"Attempts left?"} D -->|"no"| X D -->|"yes"| E["Wait: jittered delay,
    or Retry-After if longer"] E --> F["Try again"]

    How to read this: it is the lab's decision function in one picture. Order matters: a permanent error is never retried, whatever the method.

    • Permanent errors are not retried. The Google SRE book says clients should not retry permanent errors or malformed requests, since they will never succeed. A 404 or a 401 will not change in 300 ms.
    • Transient signals are candidates. The lab treats timeouts, dropped connections and statuses 408, 429, 500, 502, 503 and 504 as retryable. That list is the lab's sensible default, not a standard; check what your own servers return for "try again". Note that fetch does not reject on HTTP error statuses, so your code must look at response.ok and the status before it can decide anything.
    • Only repeat what is safe to repeat. RFC 9110 defines an idempotent method as one whose intended effect of several identical requests is the same as one, and lists PUT, DELETE and the safe methods (GET, HEAD, OPTIONS, TRACE) as idempotent. MDN lists POST as neither safe nor idempotent, with the example that successive identical POST requests may create the same order several times.

    Illustration 3: a failure case. The shopper presses "Place order"; the POST times out at the client, and the wrapper, which retries everything, sends it again. The first one was only slow, not lost. The server creates two orders. The wrapper treated a timeout as proof of failure, but a timeout only proves the client stopped waiting.

    The idempotency key

    An idempotency key is a value the client creates for one intended operation and sends unchanged on every attempt, in an Idempotency-Key header. A server that honours it recognises the repeat and returns the first result instead of acting again. The Builders' Library puts the principle this way: APIs with side effects are not safe to retry unless they provide idempotency, which guarantees the side effects happen only once however often you retry.

    The header is described in an IETF Internet-Draft, draft-ietf-httpapi-idempotency-key-header (version 09 when this lesson was written). It is still a draft, not an RFC. Its motivating problem is exactly the one above: a POST times out and "the client does not know if it can safely retry the request". Treat the header name as a common convention that your server must implement; the client sending it changes nothing unless the server deduplicates. The lesson on idempotent and commutative operations covers the server side, and the back-end lesson on idempotency keys and safe retries is planned.

    Two rules for the client: create the key once per intended operation (when the order draft is created, not on each click), and send the same key on every attempt of that operation.

    Waiting: exponential backoff and full jitter

    Exponential backoff lengthens each wait: a base, twice the base, four times, up to a cap. Jitter adds randomness so that many clients that failed together do not all retry together. The Builders' Library describes jitter as adding randomness to the backoff to spread the retries around in time, and the SRE book warns that without random spread a small perturbation, such as a network blip, can make retry ripples schedule at the same time.

    Illustration 1: a minimal example. The lab's rule is full jitter: wait a random time between 0 and the ceiling, where the ceiling doubles per retry and is capped. This is the function, as it appears in the lab:

    export function backoffDelayMs(retryNumber: number, config: BackoffConfig, random: number): number {
      if (!Number.isInteger(retryNumber) || retryNumber < 1) throw new RangeError("retryNumber starts at 1");
      const ceiling = Math.min(config.capMs, config.baseMs * 2 ** (retryNumber - 1));
      return Math.floor(random * ceiling);
    }

    The randomness is an argument, not a call to Math.random(), so a test gets the same delays every run. With a base of 200 ms, the ceilings for retries 1, 2, 3 are 200, 400 and 800 ms, and a random value of 0.5 gives 100 ms for the first retry; the demo below shows 100 then 360 ms for random values 0.5 and 0.9. The back-end lesson compares equal and decorrelated jitter and shows the simulated effect on many clients; this lesson sticks to the one rule.

    Illustration 2: a realistic example. The product list GET meets a server that fails twice with 503, then recovers. The client waits 100 ms, retries, waits 360 ms, retries, and the third attempt succeeds. The trace is in "Build it".

    Figure 3. The life of one request with retries

    stateDiagram-v2 accTitle: States of a request that may be retried accDescr: A request starts an attempt. A success finishes it. A retryable failure moves to a backoff wait and then a new attempt. A permanent failure or too many attempts ends in failure. A user cancel from any state ends in cancelled. [*] --> Attempting Attempting --> Done: success Attempting --> Waiting: retryable failure Waiting --> Attempting: delay passed Attempting --> Failed: permanent error or attempts used up Attempting --> Cancelled: user cancels Waiting --> Cancelled: user cancels

    How to read this: the "Waiting" state is where a client spends most of a retry's time, so it must be cancellable too. A client that only checks the signal during an attempt keeps retrying a request the user has abandoned.

    Retry-After wins when it is longer

    A server can tell the client how long to wait. MDN documents Retry-After with two forms, a date after which to retry or a non-negative number of seconds, and notes it is used with 503 ("how long the service is expected to be unavailable") and 429 ("how long to wait before making a new request"). RFC 6585 defines 429 as "too many requests in a given amount of time" and says a server may add Retry-After; MDN says it "may be included", so it is not guaranteed. MDN also says support for the header on clients and servers is inconsistent, so write a client that works without it.

    The lab uses max(jittered delay, Retry-After), and treats a Retry-After above a configured maximum as "do not retry" instead of sleeping for minutes. In the demo a 429 with Retry-After: 2 beats a small jittered delay of 20 ms: the client waits 2000 ms.

    Time and cancellation: bound the whole thing

    Retries make the worst case long. In the demo's last-but-one scenario, a request that always fails with a 500, a base of 2000 ms and a cap of 5000 ms gives up after four attempts, and the waits (1980, 3960 and 4950 ms) put the last attempt at t=10890 ms. A shopper will not wait eleven seconds, so a retry policy needs a total budget as well as a count: use the deadline from the previous lesson, shared by all attempts, and give each attempt its own shorter timeout.

    Two cancellation rules hold the design together. The caller's abort ends everything and is never retried (the demo's last scenario: Cancel at t=500 ms while waiting rejects at once with the user's reason). And each attempt needs its own controller linked to the caller's signal, so that a per-attempt timeout stops that attempt without cancelling the retry loop.

    Budgets: a limit on retries across requests

    A count per request is not enough when many requests fail together: each is within its limit, and the sum is a flood. The SRE book's overload chapter describes a per-request budget of up to three attempts and a per-client budget, where a request is retried only while the ratio of retries to requests is below 10%. Its stated effect: without the client budget, load can grow to just below 3x; with it, to 1.1x in the general case. The Builders' Library describes a local token bucket with the same intent: retries are allowed while there are tokens, and then happen at a fixed rate once the tokens run out. A client-side version is the lab's stretch exercise: one shared budget for the whole tab, not one per request.

    Trade-offs

    Choice Gain Cost Wrong when
    Retry reads automatically Hides brief failures More load on a struggling server The error is permanent, or the server says overloaded
    Retry writes with a key Safe repeats Server support, key lifecycle The server ignores the header
    Never retry writes No duplicate risk The user must retry by hand The failure is almost always transient and the user cannot tell
    Full jitter Widest spread Some retries come almost at once You need a guaranteed pause
    Honour Retry-After Follows the server's own estimate Longer waits The value is huge: cap it and give up
    Retry in one layer Predictable counts Must disable others A library retries by default
    Shared retry budget Caps the flood Some failures are passed on A single, rare, critical request

    Build it

    The lab is examples/frontend/labs/request-client: a small fetch wrapper whose policy.ts is pure (no timers, no Math.random) and whose client.ts runs attempts with an injected fetch, clock and random function. The ManualClock drives virtual time, so nothing waits. Run it:

    cd examples/frontend/labs/request-client
    node src/demo.ts

    Expected output, captured from a real run (node src/demo.ts in examples/frontend/labs/request-client, copied from examples/frontend/golden/request-client.txt), in full:

    === GET: two 503s, then success (full jitter, base 200 ms)
    t=    0  attempt 1: GET /api/products
    t=    0  retry in 100 ms (HTTP 503)
    t=  100  attempt 2: GET /api/products
    t=  100  retry in 360 ms (HTTP 503)
    t=  460  attempt 3: GET /api/products
    idempotency-key per attempt: -, -, -
    result: resolved 200 "ok"
    
    === GET: server asks us to wait (Retry-After: 2 s beats a small jittered delay)
    t=    0  attempt 1: GET /api/products
    t=    0  retry in 2000 ms (HTTP 429, Retry-After 2000 ms)
    t= 2000  attempt 2: GET /api/products
    idempotency-key per attempt: -, -
    result: resolved 200 "ok"
    
    === POST without an idempotency key: a 503 is NOT retried
    t=    0  attempt 1: POST /api/orders
    t=    0  give up: not-idempotent
    idempotency-key per attempt: -
    result: rejected HttpError: HTTP 503 after 1 attempt(s)
    
    === POST with an idempotency key: the same key is sent on every attempt
    t=    0  attempt 1: POST /api/orders
    t=    0  retry in 100 ms (HTTP 503)
    t=  100  attempt 2: POST /api/orders
    idempotency-key per attempt: order-7f3a, order-7f3a
    result: resolved 201 "created"
    
    === GET: the server hangs, each attempt times out after 1000 ms, then it recovers
    t=    0  attempt 1: GET /api/slow
    t= 1000  retry in 100 ms (timeout)
    t= 1100  attempt 2: GET /api/slow
    t= 2100  retry in 200 ms (timeout)
    t= 2300  attempt 3: GET /api/slow
    idempotency-key per attempt: -, -, -
    result: resolved 200 "ok"
    
    === GET: 404 is not retryable
    t=    0  attempt 1: GET /api/missing
    t=    0  give up: status-not-retryable
    idempotency-key per attempt: -
    result: rejected HttpError: HTTP 404 after 1 attempt(s)
    
    === GET: always 500: gives up after 4 attempts, delays capped by 5000 ms
    t=    0  attempt 1: GET /api/broken
    t=    0  retry in 1980 ms (HTTP 500)
    t= 1980  attempt 2: GET /api/broken
    t= 1980  retry in 3960 ms (HTTP 500)
    t= 5940  attempt 3: GET /api/broken
    t= 5940  retry in 4950 ms (HTTP 500)
    t=10890  attempt 4: GET /api/broken
    t=10890  give up: attempts-exhausted
    idempotency-key per attempt: -, -, -, -
    result: rejected HttpError: HTTP 500 after 4 attempt(s)
    
    === GET: the user presses Cancel at t=500 ms while we wait to retry
    t=    0  attempt 1: GET /api/products
    t=    0  retry in 990 ms (HTTP 503)
    idempotency-key per attempt: -
    result: rejected AbortError: The user cancelled

    Read it in order. The demo has eight scenarios.

    1. Scenario 1: two 503s, then success. Delays 100 and 360 ms from random values 0.5 and 0.9 against ceilings 200 and 400. The idempotency key column shows - for every attempt: a GET needs none.
    2. Scenario 2: Retry-After. The server's 2 s beats the 20 ms the jitter would give.
    3. Scenarios 3 and 4: POST without and with a key. Without one, a 503 is not retried: give up: not-idempotent. With the key, the same POST retries and order-7f3a is sent on both attempts.
    4. Scenario 5: timeouts. A hanging server makes each attempt time out after 1000 ms, then a retry follows (100 ms, then 200 ms of waiting).
    5. Scenario 6: a 404 is not retryable.
    6. Scenario 7: always 500. Gives up after 4 attempts at t=10890; the delays are the ceilings 2000, 4000 and then the 5000 cap, times 0.99.
    7. Scenario 8: cancel during the wait. The caller's reason comes straight back, and no further attempt starts.

    Verified. The 38 tests (policy, client with a scripted fake fetch, and the real clock under fake timers) passed with Node 26.12.1 and Vitest 5.1.0, and the type check passed. The golden file was re-checked with node examples/frontend/tools/capture-golden.mjs --check.

    Break it. In src/policy.ts, replace the condition !isIdempotentMethod(input.method) && !input.hasIdempotencyKey with false. A POST that fails is now retried without a key. Five tests fail (this was run for this lesson: 5 failed, 33 passed), including "does not retry a POST after a network error (the server may have processed it)". Revert it.

    Stretch. Add a retry budget shared by all requests (for example at most 10% of recent requests may be retries); add a circuit breaker in front of request and test that it stops calling fetch while open.

    The other side of this topic

    The server's job is the mirror image: send Retry-After when it can, refuse work early when overloaded instead of letting every layer retry, and deduplicate writes by key. See Timeouts, Retries, Exponential Backoff and Jitter and Load Shedding and Retry Storms for that view.

    In practice: the product page during a brief outage

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    A grocery marketplace's product page calls a catalogue API. For a few minutes the API returns 503 for a share of requests. The page shows a blank error on the first failure. Support asks for "just retry it". An engineer adds retries to the fetch wrapper.

    Starting architecture

    Figure 4. Starting point: retries on, in two places, for every method

    Starting architecture: the library and the wrapper both retry, and the wrapper retries POSTProduct page to Data library (GET list); Data library to Fetch wrapper; Product page to Fetch wrapper (POST order); Fetch wrapper to Catalogue and order API (retries)Product page: list and Place orderProduct pagelist and PlaceorderData library: default retriesData librarydefault retriesFetch wrapper: retries every methodFetch wrapperretries everymethodCatalogue and order API: 503 for a whileCatalogue andorder API503 for a whileGET listPOST orderretries

    How to read this: the two warning boxes both retry, so list requests multiply, and the wrapper repeats the order POST with no key.

    Options considered

    Option What it fixes What it costs Risk
    Keep both layers, lower counts Less load Still stacked Hard to reason about
    Retry in the wrapper only, reads only Predictable load Writes stay manual The user must retry orders
    Wrapper retries reads; writes only with a key Safe repeats everywhere Server must deduplicate Key lifecycle bugs
    Add a shared retry budget Caps the flood More code to test Some failures passed on

    The decision

    Field Decision record
    Context Two layers retry; the wrapper retries a POST without a key; delays are fixed.
    Decision Turn the library's retries off. Retry in the wrapper only: reads with full-jitter backoff and Retry-After, writes only when they carry a key created with the order draft. Apply a total deadline per user action and stop on cancel.
    Consequences, good Bounded, spread-out load; no duplicate orders from retries.
    Consequences, bad One layer to own and test; the server must honour the key.
    Revisit when The server publishes a retry budget or error code for "overloaded, do not retry".

    Rollout and verification

    1. Reproduce first with the lab-style scripted fake fetch: two 503s then success, and a POST that times out.
    2. Ship reads first, then watch requests per page view and the share of requests that are retries.
    3. Ship the key with the server's deduplication enabled, and confirm in logs that a repeat returns the first result.
    4. Test the edges: Cancel during a wait, a Retry-After of many minutes, a server that answers 429 without the header.

    The 2 a.m. failure

    At night a partner's integration test hammers the API and gets 429 responses with Retry-After: 60. The page's list still shows an error for a full minute and then loads, which looks like an outage.

    The cause is correct behaviour with poor feedback: the client honours the 60-second wait, but the UI shows nothing during it. First three checks: (1) look for give up or retry in events with Retry-After in the client's logs; (2) confirm the wait comes from the header, not from backoff; (3) check what the UI shows while waiting. Mitigation: show "busy, trying again in a moment" with a manual retry, and give up for waits above the configured maximum. Follow-up: emit the retry events to monitoring so waits and give-ups are visible.

    Architect's notes

    • Choose one retry owner per request path. Library or wrapper, not both.
    • Classify by method and key, not by habit. POST is retryable only with a key the server honours.
    • Keep the policy pure. Pass randomness and time in, as the lab does, and the whole policy is testable without waiting.
    • Pair every retry loop with a deadline and a cancel. The count is not a time bound.
    • Make waiting visible. A silent wait looks like a hang.
    • Log retries. Without a count you cannot tell a healthy client from one hammering a dying service.

    Common mistakes

    • Retrying every failure, including permanent ones such as 404 or 401.
    • Retrying a POST after a timeout without a key.
    • Generating the idempotency key per attempt or per click instead of per operation.
    • Fixed delays (every client waits exactly one second), which keep clients in step.
    • Stacked retries in a library and a wrapper.
    • Ignoring Retry-After, or obeying a huge value without a cap.
    • Not stopping on cancel while waiting between attempts.
    • Treating the draft Idempotency-Key header as an RFC that every server supports.

    Key takeaways

    • A retry is extra load: bound its count, its time and its rate.
    • After a timeout the client does not know whether the server acted: retry only idempotent requests or writes with a key.
    • Use exponential backoff with jitter; the randomness is what spreads clients out.
    • Retry-After can lengthen the wait; cap it, and give up when it is too long.
    • Retry in one layer; layers multiply.
    • The caller's cancel ends the loop, including the waiting.
    • Test the policy on a virtual clock with injected randomness.

    Practice exercises

    Exercise 1: Starter (30 min). Compute by hand the ceilings for retries 1 to 5 with a base of 300 ms and a cap of 5000 ms, and the delay for random value 0.5 each time. Check with backoffDelayMs.

    Exercise 2: Intermediate (2 hours). Run the demo, then add a scenario where a PUT times out twice and succeeds the third time. Predict the trace before you run it.

    Exercise 3: Intermediate (2 hours). Write a test that a Retry-After given as an HTTP date in the past results in a retry with only the jittered delay.

    Exercise 4: Advanced (half day). Add a shared retry budget to the client (the stretch exercise) and write a test that shows the share of retries stays under the configured ratio when the server always fails.

    In this course:

    Elsewhere on the site:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments