In short
Retry a failed call only when the failure is transient and the operation is safe to repeat, wait longer after each attempt with exponential backoff, and randomize the wait with jitter so many clients do not retry in lockstep. Cap the number of attempts, the total time through a deadline that travels with the request, and the share of traffic that may be retries, so retries cannot multiply an outage. A circuit breaker sits around the call and stops sending requests for a while once failures pass a threshold, then lets a trial call through to see whether the dependency has recovered.
Key points
- Retry transient failures only: timeouts, connection errors, 502, 503, 504 and 429. Never retry a non-idempotent request whose outcome is unknown unless it carries an idempotency key.
- Exponential backoff alone keeps clients synchronized. Add jitter; full jitter, a random wait between zero and the backoff, is the usual default.
- Retries multiply across layers. Retry at one layer, cap attempts, and enforce a retry budget so retries stay a small share of traffic.
- Give each request one deadline and pass the remaining time to every downstream call. Do not start a retry that cannot finish in time.
- Honor Retry-After on 429 and 503 responses, and wait at least that long even when your own backoff is shorter.
- A circuit breaker protects the dependency and your own resources, not your success rate. Pair it with bulkheads, load shedding and metrics on every retry.
Which failures are worth retrying
A retry is a bet that the next attempt will meet a different world: the overloaded server has shed some load, the connection that dropped will not drop again, the leader election has finished. That bet only pays for transient failures. A request that failed because it was malformed, unauthorized or for a resource that does not exist will fail the same way every time, and retrying it only adds load.
| Failure | Retry? | Why |
|---|---|---|
| Connection refused, DNS failure, TLS handshake failure | Yes | The request never reached the server, so it cannot have taken effect |
| Timeout or connection reset after the request was sent | Only if the operation is idempotent | The outcome is unknown: the server may have done the work |
| 503 Service Unavailable | Yes, with backoff, honoring Retry-After | Defined as temporary overload or maintenance |
| 429 Too Many Requests | Yes, after Retry-After | The client is over a rate limit; sending sooner only extends it |
| 502 Bad Gateway, 504 Gateway Timeout | Usually, if idempotent | A proxy could not get a good or timely answer upstream |
| 500 Internal Server Error | Sparingly | Often a bug that will repeat; one retry at most |
| 400, 401, 403, 404, 422 | No | The request itself is wrong; fix it, refresh credentials, or report |
| Database serialization failure or deadlock | Yes, the whole transaction | Another transaction won a conflict; rerunning it usually succeeds |
The database row has a detail that matters. PostgreSQL's documentation recommends retrying serialization_failure (SQLSTATE 40001) unconditionally and says retrying deadlock_detected (40P01) may also be advisable, and it stresses that you must retry the complete transaction, including the logic that decided which SQL to run and with which values. Re-sending only the failed statement is wrong.
Retry only where you can tell these cases apart. A wrapper that retries every exception will retry validation errors, programming errors and the circuit breaker's own "open" error, which defeats it.
Idempotency: what makes a retry safe
RFC 9110 defines an idempotent method as one where multiple identical requests have the same intended effect as a single one, and names PUT, DELETE and the safe methods (GET, HEAD, OPTIONS, TRACE) as idempotent. It explains why the property matters: such a request can be repeated automatically if the connection fails before the client reads the response. And it says a client should not automatically retry a non-idempotent request unless it knows the request is in fact idempotent or can detect that the original was never applied.
Most important writes are POSTs: create an order, book a seat, send a message. The standard way to make them safe to retry is an idempotency key: the client generates a unique key per logical operation, sends it with every attempt, and the server stores the key with the result, so a repeat returns the stored result instead of doing the work twice. The key must be created once, before the first attempt, and reused by every retry; a new key per attempt makes each retry a new operation. Storage, expiry and races between concurrent attempts are covered in idempotency and job queues.
Exponential backoff with full, equal and decorrelated jitter
Retrying immediately turns one failure into a burst. Capped exponential backoff waits min(cap, base * 2^attempt) between attempts: with a base of 100 ms, waits of 100, 200, 400, 800 ms, up to a cap. It slows each client down, but it leaves a problem that Marc Brooker's AWS Architecture Blog post on backoff and jitter shows clearly: clients that failed together back off by the same amounts and retry together, in clusters, with quiet gaps between. Backoff reduced the contention in his simulation only a little.
Jitter is the fix: randomize each wait so the retries spread out. The post compares three ways, and the formulas below are the ones in the simulator AWS published with it. Full jitter picks a uniform random wait between zero and the exponential backoff. Equal jitter keeps half of the backoff and randomizes the other half, so no wait is very short. Decorrelated jitter picks a random wait between the base and three times the previous wait, capped. The code applies each to 1,000 clients that all fail at the same moment and retry five times, and counts the busiest 10 ms window:
// Four backoff strategies, after the formulas in AWS's backoff simulator.
// 1,000 clients fail at t=0 and retry 5 times; count the busiest 10 ms window.
let seed = 7; // mulberry32: a seeded generator, so the output repeats
function rand(): number {
seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
}
const uniform = (lo: number, hi: number) => lo + rand() * (hi - lo);
const BASE = 100; // ms
const CAP = 10_000; // ms
const expo = (attempt: number) => Math.min(CAP, BASE * 2 ** attempt);
type Strategy = (attempt: number, prevSleep: number) => number;
const strategies: Record<string, Strategy> = {
'no jitter': (a) => expo(a),
'full jitter': (a) => uniform(0, expo(a)),
'equal jitter': (a) => expo(a) / 2 + uniform(0, expo(a) / 2),
decorrelated: (_a, prev) => Math.min(CAP, uniform(BASE, prev * 3)),
};
for (const [name, sleepFor] of Object.entries(strategies)) {
const calls: number[] = [];
for (let c = 0; c < 1000; c++) {
let t = 0;
let prev = BASE;
for (let attempt = 0; attempt < 5; attempt++) {
prev = sleepFor(attempt, prev);
t += prev;
calls.push(t);
}
}
const windows = new Map<number, number>();
for (const t of calls) windows.set(Math.floor(t / 10), (windows.get(Math.floor(t / 10)) ?? 0) + 1);
const peak = Math.max(...windows.values());
const last = Math.max(...calls);
console.log(name.padEnd(13) + ' peak calls in 10 ms: ' + String(peak).padStart(4) + ' last retry at ' + Math.round(last) + ' ms');
}Running it with Node.js 22 (node --experimental-strip-types) prints:
no jitter peak calls in 10 ms: 1000 last retry at 3100 ms
full jitter peak calls in 10 ms: 158 last retry at 2820 ms
equal jitter peak calls in 10 ms: 216 last retry at 2950 ms
decorrelated peak calls in 10 ms: 67 last retry at 17676 msWithout jitter, all 1,000 clients hit the server in the same 10 ms window, five times. Full jitter cut the peak by a factor of six without stretching the schedule. Decorrelated jitter spread calls the most, but its wait grows by up to three times per attempt, so by the fifth retry clients were waiting far longer; the cap and the number of attempts decide how much that matters to you.
| Strategy | Wait before the next attempt | Peak calls per 10 ms (run above) | In the AWS post's simulation | Use it when |
|---|---|---|---|---|
| No jitter | min(cap, base * 2^n) | 1000 | The clear loser: more work and more time than any jittered method | Never, with more than one client |
| Full jitter | random(0, min(cap, base * 2^n)) | 158 | Fewest calls, about tied with equal jitter; slightly slower than decorrelated | The default for most clients |
| Equal jitter | b / 2 + random(0, b / 2), b the capped backoff | 216 | Slightly more work than full jitter and much longer to finish | You need a minimum wait between attempts |
| Decorrelated jitter | min(cap, random(base, previous * 3)) | 67 | More calls than full jitter, slightly faster to finish | Long-lived retry loops where you want waits to grow quickly |
Brooker's conclusion is that jittered backoff should be a standard approach for remote clients, and that full and decorrelated jitter are close, with full jitter doing less work and decorrelated finishing slightly sooner. A 2023 update to the post notes that most AWS SDKs now include backoff with jitter, and many other clients do too; check what yours already does before wrapping it in a second retry loop.
Retry budgets and retry storms
Backoff spaces out one client's retries. It does nothing about how many retries the whole system sends. When a dependency slows down, every caller starts retrying at once, traffic rises right when capacity has fallen, and an incident that would have passed becomes an outage that cannot recover by itself. Two mechanisms drive this:
- Retries multiply across layers. Google's SRE book chapter on cascading failures works an example where three layers each make up to four attempts, so one user action can become 64 attempts on the database. The AWS Builders' Library article on timeouts and retries gives a five-layer stack whose database load rises 243 times, and recommends retrying at a single point in the stack.
- Retries are selfish. The same article describes a retry as spending more of a server's time to raise the odds of one request: harmless when failures are rare, harmful when the server is failing because it is overloaded.
A retry budget caps retries as a share of traffic instead of per request. Some published versions:
- Per process: the SRE book suggests a server-wide budget, for example 60 retries per minute in a process, failing without retrying once it is spent.
- Token bucket: the Builders' Library article describes local token buckets in which calls retry while tokens remain, then drop to a fixed retry rate. AWS added this behavior to its SDK in 2016, the article says.
- In a proxy: Envoy's
retry_budgetlimits active retries to a percentage of active requests,budget_percent, which defaults to 20%, with a floor set bymin_retry_concurrency, which defaults to 3.
Servers can help too. The SRE book recommends returning a specific status when overloaded, so that clients and other layers back off and do not retry, and keeping retriable and nonretriable errors separate. Propagate that signal upward instead of converting it into a generic 500 that every layer retries.
Deadlines and timeouts across calls
Every retry loop needs a stopping rule in time, not only in attempts. Without one, a request whose user gave up long ago keeps holding a connection, a thread and a slot in a downstream queue. The gRPC documentation notes that no deadline is set by default, so a client can wait indefinitely, and recommends always setting one.
- Set one deadline at the edge, from what the caller can actually wait: a page load, an API client's own timeout, a job's lease.
- Pass the remaining time down with every call. The SRE book's example: with a 30-second deadline and 7 seconds spent, the next call gets 23 seconds. gRPC propagates deadlines for you in some languages, and sends the remaining time rather than an absolute timestamp, which avoids clock skew between machines.
- Give each attempt its own, shorter timeout, chosen from the dependency's latency. The Builders' Library suggests picking an acceptable rate of false timeouts, such as 0.1%, and using the matching percentile, here p99.9, of the downstream latency.
- Before sleeping for a retry, check that the wait plus a typical attempt still fits inside the deadline. If it does not, fail now and free the resources.
- On the server, check the remaining time between stages and stop work whose caller has already given up; gRPC cancels the call when the deadline passes, but the application must notice and stop.
Retry-After, 429 and 503
Sometimes the server tells you when to come back. RFC 9110 defines the Retry-After header as how long the client ought to wait before a follow-up request, and with a 503 it means how long the service expects to be unavailable. Its value is either an HTTP date or a number of seconds, so Retry-After: 120 means two minutes. The 503 status itself is defined as temporary overload or scheduled maintenance that will likely be alleviated after some delay, and the server may send Retry-After with it. The 429 status is defined in RFC 6585, not RFC 9110: the client has sent too many requests in a given amount of time, and the response may include Retry-After.
- Wait at least as long as
Retry-After, then add jitter, so every client told "60 seconds" does not return in the same second. - Parse both forms. The date form depends on your clock, so treat a date in the past as "now" and clamp very large values to your deadline.
- If the wait does not fit in the remaining deadline, fail at once rather than sleeping and then failing.
- A 429 means you are over a quota or a rate limit. Slow the whole client down, not just this request, or the next request will hit the same limit.
How servers decide when to send 429 and what to put in the headers is the other side of this contract, covered in rate limiter system design. For calls to model providers, where 429s and overload errors are routine and the fallback is often another model, see LLM routing and fallbacks.
Circuit breakers: closed, open and half-open
Retries assume the next attempt might work. When a dependency is down for minutes, that assumption is wrong for every request, and each one still waits for its timeouts and holds its resources. The circuit breaker, which Martin Fowler's article credits Michael Nygard's book Release It! with popularizing, wraps the call and fails fast once it has seen enough failures. It has three states:
- Closed: calls pass through and failures are counted. Fowler's version resets the count on success; Microsoft's Azure Architecture Center describes a time-based counter that resets periodically, so occasional failures do not trip it. When failures pass a threshold, the breaker opens.
- Open: calls fail immediately without touching the dependency, for a reset timeout.
- Half-open: after the timeout, a limited number of trial calls go through. If they succeed, the breaker closes; if one fails, it opens again and restarts the timer. The Azure description notes that this protects a recovering service from a sudden flood of requests.
The Azure pattern also states the rule that ties breakers and retries together: retry through the breaker, but have the retry logic stop when the breaker says the fault is not transient. The simulation below does that. A dependency fails from 300 ms to 1,500 ms, mostly with 503 and sometimes with 429 and a 200 ms Retry-After. A request arrives every 10 ms for two seconds; each makes up to four attempts with full jitter, inside an 800 ms deadline. It runs once without a breaker and once with one that opens after five consecutive failures and stays open for 400 ms:
// Retries with full jitter, a deadline, Retry-After and a circuit breaker, against a
// dependency that fails from t=300 ms to t=1500 ms. A new request arrives every 10 ms.
// Event-driven simulation on a virtual clock with a seeded random generator.
let seed = 1;
const rand = () => (seed = (seed * 48271) % 2147483647) / 2147483647;
type Reply = { status: number; retryAfterMs: number };
function dependency(t: number): Reply {
if (t < 300 || t >= 1500) return { status: 200, retryAfterMs: 0 };
return rand() < 0.7 ? { status: 503, retryAfterMs: 0 } : { status: 429, retryAfterMs: 200 };
}
type State = 'closed' | 'open' | 'half-open';
class Breaker {
state: State = 'closed';
failures = 0;
openedAt = 0;
trialInFlight = false;
threshold = 5; // consecutive failures that trip it
resetMs = 400; // time spent open before one trial call
log: string[] = [];
allow(t: number): boolean {
if (this.state === 'open' && t - this.openedAt >= this.resetMs) this.move(t, 'half-open');
if (this.state === 'closed') return true;
if (this.state === 'half-open' && !this.trialInFlight) return (this.trialInFlight = true);
return false; // open, or a trial is already running
}
record(t: number, ok: boolean) {
this.trialInFlight = false;
if (ok) {
this.failures = 0;
if (this.state !== 'closed') this.move(t, 'closed');
} else if (this.state === 'half-open' || ++this.failures >= this.threshold) {
if (this.state !== 'open') this.move(t, 'open');
this.openedAt = t;
}
}
move(t: number, to: State) {
this.log.push('t=' + t + ' ' + this.state + ' -> ' + to);
this.state = to;
}
}
const RETRYABLE = new Set([429, 502, 503, 504]);
const MAX_ATTEMPTS = 4;
const DEADLINE_MS = 800;
const CALL_MS = 20;
function run(useBreaker: boolean) {
seed = 1;
const b = new Breaker();
type Attempt = { at: number; n: number; deadline: number };
const queue: Attempt[] = [];
for (let t = 0; t < 2000; t += 10) queue.push({ at: t, n: 1, deadline: t + DEADLINE_MS });
const outcomes = new Map<string, number>();
const done = (k: string) => outcomes.set(k, (outcomes.get(k) ?? 0) + 1);
let calls = 0;
while (queue.length > 0) {
queue.sort((x, y) => x.at - y.at);
const a = queue.shift() as Attempt;
if (useBreaker && !b.allow(a.at)) { done('failed fast, breaker open'); continue; }
calls += 1;
const r = dependency(a.at);
const end = a.at + CALL_MS;
if (useBreaker) b.record(end, r.status < 400);
if (r.status < 400) { done(a.n === 1 ? 'ok, first try' : 'ok after retrying'); continue; }
if (!RETRYABLE.has(r.status)) { done('not retryable'); continue; }
if (a.n === MAX_ATTEMPTS) { done('gave up, attempts used'); continue; }
const backoff = Math.round(rand() * Math.min(1000, 50 * 2 ** a.n)); // full jitter
const next = end + Math.max(backoff, r.retryAfterMs); // never sooner than Retry-After
if (next >= a.deadline) { done('gave up, deadline'); continue; }
queue.push({ at: next, n: a.n + 1, deadline: a.deadline });
}
console.log((useBreaker ? '-- retries + breaker' : '-- retries only') + ', calls to the dependency: ' + calls);
for (const [k, v] of outcomes) console.log(' ' + String(v).padStart(3) + ' ' + k);
b.log.forEach((line) => console.log(' ' + line));
}
run(false);
run(true);Running it with Node.js 22, as before, prints both runs:
-- retries only, calls to the dependency: 520
80 ok, first try
71 gave up, attempts used
1 gave up, deadline
48 ok after retrying
-- retries + breaker, calls to the dependency: 78
71 ok, first try
129 failed fast, breaker open
t=350 closed -> open
t=750 open -> half-open
t=770 half-open -> open
t=1170 open -> half-open
t=1190 half-open -> open
t=1590 open -> half-open
t=1610 half-open -> closedRead the numbers honestly. Without a breaker, 200 requests made 520 calls, 2.6 per request, most of them into a dependency that was failing; 128 requests succeeded. With the breaker, the dependency saw 78 calls, 85% fewer, but only 71 requests succeeded, because the breaker was open when the dependency came back at 1,500 ms and stayed open until the trial at 1,590 ms. In this toy model the dependency recovers the instant the fault ends, which flatters plain retries. A real overloaded service gets slower under 2.6 times the traffic and may not recover at all, which is the case breakers exist for. The trade-off is real either way: the reset timeout sets how long you keep failing after recovery, and the half-open policy sets how fast you ramp back.
- Scope breakers to one dependency, or one shard or region of it. A single breaker over a sharded store can block healthy shards because one is failing.
- Decide what an open breaker returns: an error, a stale or default value, or a queued request to replay later. Fowler and the Azure pattern both list options like these.
- Count the right failures. Timeouts and 5xx count; 4xx caused by bad input do not, or one buggy client can trip the breaker for everyone.
- Log every state change and alert when a breaker opens. Fowler calls breaker trips an early warning of deeper trouble, and suggests letting operators trip or reset breakers by hand.
Bulkheads and load shedding
A breaker reacts after failures pile up. Bulkheads limit the damage before that. The Azure Architecture Center names the pattern after the partitions in a ship's hull, and describes the failure it prevents: a client whose requests to one slow service hold its connection pool until requests to every other service fail too. The fix is a separate pool, semaphore or queue per dependency, sized for that dependency, so a slow payment provider cannot take the search page down with it. The same idea applies per tenant or per priority: give important traffic a partition of its own.
Load shedding is the server's side. When a server nears overload, the SRE book recommends rejecting some work early and cheaply, for example returning 503 once in-flight requests pass a limit, instead of accepting everything and timing out on all of it. It also suggests serving the newest requests first under overload, since the oldest are the likeliest to have been abandoned, and degrading gracefully by doing less work per request. Shedding only works if clients cooperate: a client that retries a shed request immediately sends the load straight back, which is why backoff, budgets and Retry-After belong in the same design.
Observability of retries
Retries hide problems. A dependency that fails a third of its calls can look healthy from the outside while it triples its own load and adds seconds of latency. Make retries visible:
- Count attempts per logical request, as a histogram, and the retry ratio: retries divided by first attempts. A rising ratio is the earliest sign of a storm.
- Record why each attempt failed: status code, timeout, connection error. A shift from 503 to timeouts often means the dependency has gone from shedding load to drowning in it.
- Measure latency both per attempt and per request. The user feels the request latency, including every backoff.
- Count budget exhaustion, deadline give-ups and Retry-After waits separately from ordinary failures.
- Emit breaker state changes as events and expose the current state as a gauge per dependency.
- In traces, make each attempt its own span with an attempt number, under the request's parent span, so a slow request shows its retries instead of one long, unexplained call.
Finally, test the failure paths. Inject errors and latency into a dependency in a staging environment and check that retries back off, budgets cap them, deadlines end them and breakers open and close as designed. A retry policy that has never seen a failure is a guess.
If you are building a service that has to stay up when its dependencies do not, see our web app development service: the code lives in your GitHub from day one, AI-assisted work is reviewed by an engineer, and the founders are on the calls.
Sources
Checked when this post was written.
- Marc Brooker, Exponential Backoff and Jitter (AWS Architecture Blog, 2015)
- aws-samples/aws-arch-backoff-simulator (the simulator behind that post, on GitHub)
- Marc Brooker, Timeouts, retries, and backoff with jitter (Amazon Builders' Library, 2019)
- RFC 9110: HTTP Semantics (9.2.2 Idempotent Methods, 10.2.3 Retry-After, 15.6.4 503 Service Unavailable)
- RFC 6585: Additional HTTP Status Codes (4. 429 Too Many Requests)
- Martin Fowler, CircuitBreaker (2014)
- Microsoft Azure Architecture Center: Circuit Breaker pattern
- Microsoft Azure Architecture Center: Bulkhead pattern
- Google SRE book, Chapter 22: Addressing Cascading Failures
- gRPC documentation: Deadlines
- Envoy documentation: config.cluster.v3.CircuitBreakers (RetryBudget)
- PostgreSQL documentation: 13.5. Serialization Failure Handling