Exponential backoff and jitter: why retries need randomness, and a budget to go with it
A 1,000-client simulation shows why exponential backoff fails without jitter, which jitter to use, and how a retry budget stops retries deepening an outage.
· 11 min read
- Reliability
- Retries
- TypeScript
A dependency blips for three seconds. Every client that was talking to it fails, waits, and tries again. If they all wait the same amount of time, they all come back at the same moment, and the service that was just recovering is knocked over by its own clients. The outage is now self-sustaining.
The usual advice is “use exponential backoff with jitter”. Many people apply the exponential part and skip the jitter. A small simulation shows it is the other way round. After that, this article covers the two things backoff cannot do: decide whether a retry is safe, and stop a fleet of clients retrying itself into the ground. The code is TypeScript, run on Node 22.
The simulation
The model is deliberately simple. 1,000 clients each need to make one call, and all of them fail within the same 100 ms, which is what a deploy, a cache expiry or a network partition looks like from the server’s side. The server rejects everything for three seconds, then serves up to 100 requests per 100 ms window and answers the rest with a 503. Each client retries until it succeeds, with a base delay of 100 ms and a cap of 10 seconds. The network takes no time, so the only thing that varies between runs is the delay rule.
Five rules, where n is the number of failures so far and random() is uniform on [0, 1):
const base = 100, cap = 10_000;
const fixed = () => 1000;
const exponential = (n: number) => Math.min(cap, base * 2 ** n);
const equalJitter = (n: number) => { const v = exponential(n); return v / 2 + random() * (v / 2); };
const fullJitter = (n: number) => random() * exponential(n);
// decorrelated keeps the previous sleep as state; it starts at `base`
const decorrelated = (prev: number) => Math.min(cap, base + random() * (prev * 3 - base));
The last three are the formulas from Marc Brooker’s 2015 AWS Architecture Blog post, Exponential Backoff And Jitter, taken from the simulator he published with it. Here is what happens to our 1,000 clients:
| Delay rule | Total calls | Peak arrivals per 100 ms after recovery | Median client done | 99th percentile | Last client |
|---|---|---|---|---|---|
| Fixed 1 s | 8,500 | 1,000 | 8.0 s | 12.1 s | 12.1 s |
| Exponential, no jitter | 10,500 | 1,000 | 42.7 s | 82.8 s | 82.8 s |
| Equal jitter | 6,998 | 76 | 4.8 s | 5.8 s | 6.0 s |
| Full jitter | 7,527 | 49 | 4.3 s | 11.1 s | 12.6 s |
| Decorrelated jitter | 7,275 | 109 | 3.7 s | 7.0 s | 7.9 s |
Exponential backoff without jitter is the worst result in the table, and it is worth seeing why. The clients’ delays are identical, so they stay in lockstep. At 3.1 s all 1,000 arrive in the same window. 100 are served; 900 sleep for exactly 3.2 s and arrive together at 6.3 s. 100 more are served. After the 12.7 s wave every remaining client’s delay is at the 10 s cap, so from then on a wave of all the remaining clients arrives every 10 s and the server clears 100 of them each time:
3.1 s 1000 ################################################################################
6.3 s 900 ########################################################################
12.7 s 800 ################################################################
22.7 s 700 ########################################################
32.7 s 600 ################################################
42.7 s 500 ########################################
52.7 s 400 ################################
62.7 s 300 ########################
72.7 s 200 ################
82.7 s 100 ########
The server spends almost all of that time idle. Doubling the delay reduced how often the wave hit, but the wave was the problem, and doubling cannot touch it. A fixed one-second delay, which nobody would recommend, finishes nearly seven times sooner because at least its waves are frequent.
Add any jitter and the waves disappear. Peak arrivals drop from 1,000 to between about 50 and 110 per window, around the server’s capacity, and the server rejects almost nothing after it recovers: nothing at all for equal and full jitter, nine requests for decorrelated. So with jitter the finish times in the table are not queueing at the server; they are the clients’ own sleep draws, and the differences between the three rules mostly come from how many attempts each client burnt during the outage. Full jitter has the lowest peak because its delays spread over the whole window, and the longest tail because some clients drew short sleeps early, used up attempts, and reached the 10 s window before the server came back. The cap is the lever for that tail: at 2 s instead of 10 s, full jitter’s last client finishes at 5.0 s; at 5 s, 7.9 s; at 20 s, 15.0 s. Brooker’s own simulation ranked the jitter rules a little differently and he called the choice between them unclear. The jitter is what matters; which jitter, and what cap, are tuning questions.
Full jitter is the default to reach for: it is stateless, it has the lowest peak, and one line implements it. If you need a guaranteed minimum spacing between attempts, equal jitter gives you that at the cost of a higher peak.
A retry helper that gets the details right
The delay rule is about ten per cent of a good retry function. The rest is deciding what to retry, how long to keep trying, and how to test it. This is the helper; RetryBudget is defined further down:
import { setTimeout as sleep } from "node:timers/promises";
export class RetryableError extends Error {
readonly retryAfterMs?: number;
constructor(message: string, retryAfterMs?: number, options?: ErrorOptions) {
super(message, options);
this.name = "RetryableError";
this.retryAfterMs = retryAfterMs;
}
}
export function fullJitter(attempt: number, baseMs: number, capMs: number, random = Math.random): number {
return random() * Math.min(capMs, baseMs * 2 ** attempt);
}
export interface RetryOptions {
attempts?: number; // total attempts, including the first
baseMs?: number;
capMs?: number;
signal?: AbortSignal; // deadline or cancellation for the whole call
budget?: RetryBudget;
isRetryable?: (err: unknown) => boolean;
random?: () => number; // injected so tests are deterministic
wait?: (ms: number, signal?: AbortSignal) => Promise<unknown>;
}
export async function retry<T>(fn: (signal?: AbortSignal) => Promise<T>, options: RetryOptions = {}): Promise<T> {
const {
attempts = 3, baseMs = 100, capMs = 10_000, signal, budget,
isRetryable = (err) => err instanceof RetryableError,
random = Math.random,
wait = (ms, s) => sleep(ms, undefined, { signal: s }),
} = options;
for (let attempt = 0; ; attempt++) {
signal?.throwIfAborted();
try {
const result = await fn(signal);
budget?.recordSuccess();
return result;
} catch (err) {
const last = attempt + 1 >= attempts;
if (last || !isRetryable(err) || (budget && !budget.tryRetry())) throw err;
const hint = (err as RetryableError).retryAfterMs;
const delay = hint ?? fullJitter(attempt, baseMs, capMs, random);
await wait(delay, signal); // rejects with AbortError if the deadline passes first
}
}
}
Four decisions are built into it.
Only errors marked retryable are retried. The default predicate is “is a RetryableError”, and the function that makes the call decides what counts. Nothing is retried by accident: a bug that throws a TypeError fails once, not three times with a delay. The HTTP wrapper below shows the classification.
The deadline covers the whole call, not each attempt. The caller passes one AbortSignal, typically AbortSignal.timeout(5000). It is checked before each attempt and handed to the sleep, so a deadline that passes mid-sleep rejects immediately; on Node 22 the sleep rejects with an AbortError whose cause is the signal’s reason. For a per-attempt timeout as well, give the attempt AbortSignal.any([signal, AbortSignal.timeout(perAttemptMs)]).
The server’s hint wins. When the error carries a retryAfterMs, that is the delay, with no jitter added. A server that says “come back in two seconds” has better information than our formula.
Randomness and time are injected. random and wait default to the real thing. A test replaces them and asserts on the exact delays without any time passing:
const delays: number[] = [];
let calls = 0;
const result = await retry(async () => {
if (++calls < 3) throw new RetryableError("flaky");
return "ok";
}, { attempts: 5, random: () => 0.5, wait: async (ms) => { delays.push(ms); } });
// result === "ok", calls === 3, delays deep-equals [50, 100]
The sleep itself should run on the monotonic clock, and setTimeout does. Our monotonic clock article covers what goes wrong when a delay is computed from Date.now() instead.
What is safe to retry
Backoff answers “when”. It does not answer “whether”, and that question has two parts.
The first is whether the operation is idempotent. A GET is. A POST that creates a payment is not, unless the server deduplicates on a key you send with it. A timeout is the dangerous case: the request may have been processed and the response lost, so a retry performs it twice. Retry a non-idempotent request only with an idempotency key the server honours. Our idempotent webhooks article is the server side of that contract.
The second is whether the failure is the kind another attempt could fix. For HTTP:
export function parseRetryAfter(value: string | null, now = Date.now()): number | undefined {
if (value === null) return undefined;
if (/^\d+$/.test(value)) return Number(value) * 1000;
const at = Date.parse(value);
return Number.isNaN(at) ? undefined : Math.max(0, at - now);
}
export async function fetchJson(url: string, signal?: AbortSignal): Promise<unknown> {
let res: Response;
try {
res = await fetch(url, { signal });
} catch (err) {
if (signal?.aborted) throw err; // cancelled or out of time: not a retry case
throw new RetryableError("request failed before a response", undefined, { cause: err });
}
if (res.status === 429 || res.status === 503) {
throw new RetryableError(`HTTP ${res.status}`, parseRetryAfter(res.headers.get("retry-after")));
}
if (res.status >= 500) throw new RetryableError(`HTTP ${res.status}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
Working from the top: a connection refused or reset before any response is the commonest symptom of an outage, and fetch reports it as a TypeError, so the wrapper converts it into a retryable error with the original as its cause. An abort is left alone, because retrying a cancelled request is wrong. 429 and 503 are the error responses that carry Retry-After in practice; RFC 9110 defines the header as either a number of seconds or an HTTP date, says a 503 may include it, and also defines it for 413 and redirects. The date form depends on the server’s clock, so parseRetryAfter clamps a past date to zero rather than producing a negative delay. Other 5xx responses are retryable without a hint. A 4xx other than 429 is not: the request was wrong, and sending it again will not make it right. All of this assumes an idempotent request; for one that is not, a reset or a timeout is a judgement call, because the request may have arrived; a refused connection never did.
Against a local server that answered 503 with Retry-After: 1, then a bare 503, then 200, the helper made three calls and returned after about 1.1 seconds: one second from the hint, then a jittered delay of up to 200 ms. Against a port with nothing listening it made three attempts and threw a RetryableError whose cause was fetch failed.
Retries that make the outage worse
The fleet-level problem is different: during an outage a service receives its normal traffic plus every client’s retries, and that extra load is what stops it recovering. Two limits keep that in check.
The first is a small attempt count. Three attempts in total is the common default: it is the per-request budget Google’s SRE book describes, and the default in the AWS SDK for Go v2. gRPC’s retry design caps maxAttempts at five on the client side however high the service config sets it. If the last attempt fails, the failure goes back to the caller.
The second is a limit on how many retries the client makes overall. The SRE book’s rule is that each client tracks the ratio of its requests that are retries and stops retrying once that ratio reaches 10 per cent; the book says that turns a worst case of just under 3x load into about 1.1x. The AWS SDK for Go v2 does it with a token bucket: 500 tokens per client, 14 per retry (5 for throttling), refunded when the retry succeeds, one earned per first-attempt success, and a retry that cannot afford its tokens fails instead. gRPC keeps a similar bucket per server and switches retries off while it is at or below half full. Successes earn a little credit, retries spend it, and a long-running failure drains the account.
A minimal version for the helper above:
export class RetryBudget {
private tokens: number;
private readonly capacity: number;
private readonly refill: number;
constructor(capacity = 10, refill = 0.1) {
this.capacity = capacity;
this.refill = refill;
this.tokens = capacity;
}
recordSuccess(): void {
this.tokens = Math.min(this.capacity, this.tokens + this.refill);
}
tryRetry(): boolean {
if (this.tokens < 1) return false;
this.tokens -= 1;
return true;
}
}
One instance per dependency, shared by every call to it. In steady state a retry costs one token and a success earns a tenth, so retries settle at about 10 per cent of successes. When the dependency is down there are no successes, the bucket empties after ten retries, and every call after that fails fast until it starts answering again.
Backoff and the budget do different jobs. Brooker’s August 2022 post What is Backoff For? makes the point that backoff helps with short spikes, but under sustained overload from many independent clients it barely changes the amplification, because delaying a retry does not remove it. Only a policy that drops retries does that.
The last amplifier is layering. If a browser makes three attempts, the API it calls makes three attempts against its database, and the database driver makes three of its own, one user action can become 27 queries. Retry at one layer, normally the one closest to the failure, and let the others fail fast.
Backoff elsewhere
The same rules apply beyond HTTP clients. A job queue that schedules a failed job for now() plus an interval that doubles per attempt, like the one in our Postgres job queue article, is exponential backoff without jitter: if 1,000 jobs fail together because a downstream API is down, they retry together. Multiply the interval by random() before adding it. Any time many independent things are told to wait the same amount, they stop being independent.
Retry logic that holds up under a real outage is part of every backend we build: see our backend development service.