Designing Exponential Backoff with Full Jitter
Prevent thundering-herd retry storms using capped exponential backoff, Full Jitter randomization, Retry-After precedence, and per-call retry budgets.
On this page
Why Naive Retries Amplify Partial Outages
A slow downstream dependency is rarely fixed by hitting it three times harder. Yet that is exactly what fixed-interval retries—and even deterministic exponential backoff (1000ms, 2000ms, 4000ms)—do during an outage. Suppose a database failover stalls 4,000 API workers at t = 0. Without randomization, every worker finishes failing within milliseconds of one another, sleeps 1,000 ms in unison, and strikes the freshly promoted replica simultaneously at t = 1s, t = 3s, and t = 7s.
Worse still is retry amplification across microservice layers. If gateway A retries 3 times, service B retries 3 times, and storage client C retries 3 times, a single transient hiccup multiplies leaf load by 4 * 4 * 4 = 64x while keeping every upstream connection pool saturated until the entire fleet trips circuit breakers. Resilient backoff combines Full Jitter desynchronization, strict retryability predicates, Retry-After honoring, and bounded total deadlines.
Latency budgets also enforce a strict ceiling on how many retries make sense on synchronous user requests. If your API gateway enforces a 10-second upstream timeout while a client configures maxAttempts: 6 with baseDelayMs: 500 and maxDelayMs: 16000, the browser or gateway disconnects long before attempt 4 even starts, causing wasted background work on dead sockets. Keeping maxAttempts small (typically 2 to 4 attempts on user-facing paths, reserving higher counts for background queue workers) preserves caller tail latency while giving transient blips time to clear.
You can simulate attempt timings, cumulative wait budgets, and Full vs Equal vs Decorrelated Jitter spreads interactively in the Interactive HTTP Retry Backoff Calculator.
Full Jitter vs Equal vs Decorrelated Jitter
As popularized by Marc Brooker’s AWS Architecture analysis, three jitter strategies dominate distributed systems:
- Full Jitter:
sleep = random(0, min(capMs, baseMs * 2 ** attempt)). Spreading clients smoothly across the entire[0, ceiling]interval yields the lowest total contention and fewest wasted retries under heavy contention, though an individual call occasionally retries immediately near0 ms. - Equal Jitter:
temp = min(capMs, baseMs * 2 ** attempt); sleep = temp / 2 + random(0, temp / 2). Guarantees at least half of the backoff window elapses before every retry, useful when immediate zero-millisecond retries risk tripping strict rate-limit windows. - Decorrelated Jitter:
sleep = min(capMs, random(baseMs, prevSleep * 3)). Ties each sleep to the previous observed sleep rather than strictly2 ** attempt, smoothing clusters when attempt counters reset differently across workers.
For most HTTP API clients calling rate-limited or autoscaling upstreams, Full Jitter gives the cleanest balance between fast tail recovery and minimal server load—provided you also honor server Retry-After headers when present. Notice also why you should pair Full Jitter with a per-host circuit breaker or shared retry token bucket: jitter smooths out synchronized spikes over short windows, whereas a circuit breaker stops sending doomed traffic altogether when an upstream stays completely unhealthy for tens of seconds, preventing worker queues from piling up indefinitely across an entire cluster.
When implementing retries in browser frontends versus backend services, calibrate your caps differently. Browser callers should stick to short ceilings (maxDelayMs around 4,000 ms across at most 2 retries) and display clear offline recovery feedback, whereas background webhook workers or queue consumers can safely tolerate multi-minute backoffs backed by persistent job queues.
Production Fetch Wrapper with Deadline and Retry-After
Notice how the TypeScript client below guards against four real-world failure modes: non-idempotent HTTP methods, AbortSignal cancellation during sleep, Retry-After exceeding remaining deadline budget, and HTTP status filtering.
export interface RetryPolicy {
maxAttempts: number;
baseDelayMs: number;
maxDelayMs: number;
totalTimeoutMs: number;
allowNonIdempotent?: boolean;
}
const RETRYABLE_STATUSES = new Set([408, 425, 429, 500, 502, 503, 504]);
const IDEMPOTENT_METHODS = new Set(["GET", "HEAD", "OPTIONS", "PUT", "DELETE"]);
export function computeFullJitterDelay(
attemptIndex: number,
baseDelayMs: number,
maxDelayMs: number,
rand: () => number = Math.random,
): number {
const exp = baseDelayMs * Math.pow(2, attemptIndex);
const capped = Math.min(maxDelayMs, exp);
return Math.floor(rand() * capped);
}
export function parseRetryAfterMs(headerVal: string | null, nowMs: number = Date.now()): number | null {
if (!headerVal) return null;
const trimmed = headerVal.trim();
if (/^\d+$/.test(trimmed)) {
return Number(trimmed) * 1000;
}
const parsedDate = Date.parse(trimmed);
if (!Number.isNaN(parsedDate)) {
return Math.max(0, parsedDate - nowMs);
}
return null;
}
function sleepWithSignal(ms: number, signal?: AbortSignal): Promise<void> {
if (ms <= 0) return Promise.resolve();
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(signal.reason ?? new Error("Aborted"));
return;
}
const timer = setTimeout(() => {
signal?.removeEventListener("abort", onAbort);
resolve();
}, ms);
const onAbort = () => {
clearTimeout(timer);
reject(signal?.reason ?? new Error("Aborted"));
};
signal?.addEventListener("abort", onAbort, { once: true });
});
}
export async function fetchWithBackoff(
url: string,
init: RequestInit = {},
policy: RetryPolicy = {
maxAttempts: 4,
baseDelayMs: 250,
maxDelayMs: 8000,
totalTimeoutMs: 15000,
},
): Promise<Response> {
const method = (init.method ?? "GET").toUpperCase();
const hasIdempotencyKey = new Headers(init.headers).has("Idempotency-Key");
const canRetryMethod =
Boolean(policy.allowNonIdempotent) ||
IDEMPOTENT_METHODS.has(method) ||
hasIdempotencyKey;
const deadlineAt = Date.now() + policy.totalTimeoutMs;
for (let attempt = 0; attempt < policy.maxAttempts; attempt++) {
const remainingMs = deadlineAt - Date.now();
if (remainingMs <= 0) {
throw new Error(`Retry deadline exceeded (${policy.totalTimeoutMs}ms)`);
}
const attemptController = new AbortController();
const timeoutId = setTimeout(() => attemptController.abort(new Error("Attempt timeout")), remainingMs);
const onParentAbort = () => attemptController.abort(init.signal?.reason);
init.signal?.addEventListener("abort", onParentAbort, { once: true });
try {
const response = await fetch(url, { ...init, signal: attemptController.signal });
clearTimeout(timeoutId);
init.signal?.removeEventListener("abort", onParentAbort);
if (response.ok || !canRetryMethod || !RETRYABLE_STATUSES.has(response.status)) {
return response;
}
if (attempt === policy.maxAttempts - 1) {
return response;
}
// Release unread response body socket before sleeping
await response.body?.cancel().catch(() => undefined);
const serverDelay = parseRetryAfterMs(response.headers.get("Retry-After"));
const jitterDelay = computeFullJitterDelay(attempt, policy.baseDelayMs, policy.maxDelayMs);
const waitMs = serverDelay !== null ? Math.min(serverDelay, policy.maxDelayMs) : jitterDelay;
if (Date.now() + waitMs >= deadlineAt) {
return response;
}
await sleepWithSignal(waitMs, init.signal ?? undefined);
} catch (err) {
clearTimeout(timeoutId);
init.signal?.removeEventListener("abort", onParentAbort);
if (init.signal?.aborted || !canRetryMethod || attempt === policy.maxAttempts - 1) {
throw err;
}
const waitMs = computeFullJitterDelay(attempt, policy.baseDelayMs, policy.maxDelayMs);
if (Date.now() + waitMs >= deadlineAt) {
throw err;
}
await sleepWithSignal(waitMs, init.signal ?? undefined);
}
}
throw new Error("Exhausted retry attempts");
}
Pay close attention to await response.body?.cancel() right before sleeping on a retryable 503 or 429. In Node.js undici and browser Fetch implementations, discarding a Response without reading or canceling its body stream holds the underlying TCP socket open until garbage collection, rapidly exhausting connection pools during outages.
Retry Budgets, Token Buckets, and Edge Pitfalls
Even perfectly jittered retries break down if you neglect fleet-wide capacity boundaries:
- Retrying
400,401,403,404, or422: Client validation and auth errors will never succeed on retry; retrying them only triples wasted database/auth load. Always classify client errors vs transient transport failures (ECONNRESET,ETIMEDOUT,UND_ERR_SOCKET) before scheduling backoff. - Unbounded
Retry-Afterdates: A buggy upstream returningRetry-After: 3600causes serverless workers to hang until killed by platform timeouts. Always clampserverDelayagainst bothmaxDelayMsanddeadlineAt - Date.now(). - No fleet-level retry budget: If 100% of requests start failing because an upstream crashed, even
3retries per request quadruples QPS on a wounded service. Maintain a sliding retry token bucket (allowing retries only up to 10–20% of normal request volume) and fail fast once the retry budget drains. - Skipping
Idempotency-KeyonPOST: Never auto-retryPOST /chargesorPOST /orderswithout attaching a deterministic UUIDIdempotency-Keyheader verified by the server. - Retrying inside multi-hop service meshes blindly: Enforce retries at only a single layer—typically the outermost edge client or dedicated egress gateway—and pass remaining request deadline headers (
X-Request-Deadline-Ms) downstream so inner services never sleep past the original caller’s timeout.
Simulating Backoff Schedules and Verifying Edge Behavior
Before shipping retry logic into SDKs or service clients, preview attempt-by-attempt intervals and total worst-case elapsed time inside the Interactive HTTP Retry Backoff Calculator, then cover deterministic retry behavior with injected clocks and RNG stubs in unit tests:
import assert from "node:assert/strict";
import { computeFullJitterDelay, parseRetryAfterMs } from "./retry";
// Verify Full Jitter stays bounded within [0, maxDelayMs)
for (let attempt = 0; attempt < 10; attempt++) {
const minVal = computeFullJitterDelay(attempt, 200, 5000, () => 0);
const maxVal = computeFullJitterDelay(attempt, 200, 5000, () => 0.9999);
assert.equal(minVal, 0);
assert.ok(maxVal <= 5000);
}
// Verify both integer seconds and HTTP-date Retry-After parsing
assert.equal(parseRetryAfterMs("12"), 12000);
const fixedNow = Date.parse("2026-11-24T12:00:00Z");
assert.equal(parseRetryAfterMs("Tue, 24 Nov 2026 12:00:07 GMT", fixedNow), 7000);
Run tests verifying 400 never triggers a second fetch, AbortSignal aborts cleanly during an active sleep timer, unread 503 bodies are canceled prior to waiting, and requests past totalTimeoutMs exit promptly instead of sleeping past caller SLOs. Also run chaos tests against a mock server injecting 503 bursts alongside Retry-After headers to verify your fleet retry ratio never crosses your configured budget ceiling, and confirm Idempotency-Key headers stay constant across every retry attempt of the same logical mutation so downstream payment or ledger engines deduplicate safely.
FAQ
- Why does pure exponential backoff without jitter cause retry storms?
- When 5,000 clients fail simultaneously during a two-second downstream outage, deterministic 1s, 2s, 4s waits wake all 5,000 callers in synchronized waves, hammering the recovering service harder than the original traffic spike.
- What is the difference between Full Jitter and Equal Jitter?
- Full Jitter picks a random delay uniformly from [0, min(cap, base * 2^attempt)], maximizing spread and cutting total server work. Equal Jitter sets half deterministically and randomizes only the upper half [temp/2, temp], guaranteeing a minimum wait floor at slightly higher contention.
- When is retrying an HTTP POST request dangerous?
- Never retry non-idempotent mutations such as payments, inventory decrements, or email sends automatically unless the server enforces an Idempotency-Key header, because a client timeout may occur after the server already committed the action.
Interactive Tools for This Topic
Report a problem with this articleOpens a pre-filled issue on GitHub.