Circuit breakers, retries and timeouts: when the service you call is sick
Every page of a shop asks a stock service how many are left. One day that service stops answering for two seconds. What happens to the shop depends on how it makes the call: wait, give up, try again, or stop asking for a while.
What you'll take away
- Explain how calls with no timeout pile up on the caller while a service hangs
- Set a timeout from the service's real latency, like p99.9, not a round number
- Know when retries with backoff and jitter help, and when they swamp a sick service
- Follow a breaker through closed, open and half-open, with a fallback users accept
The 1-minute version
Tap a point and the picture below plays that step.
Try all four while Stock hangs: which one makes pages wait longest, which one calls Stock most while it is sick, and which one still refuses after Stock is back?
The service you call takes requests but hangs and answers none. What happens if you call it with no timeout?
The picture: the shop stands on its plaza at the near end of a long street, its lit windows the pages it is still making (amber once they pile up); Stock is the tower at the far end. Every page sends a violet light up the street to ask, and a healthy answer comes back blue. When Stock hangs its outline turns red and the calls sit at its door in a pile; with a timeout each one carries a clock, and when the clock runs out the light goes back amber. A retry waits beside the shop's door, then goes up again. In the breaker's steps a switch box stands on the street, its lamp lit closed (teal), half-open (amber) or open (red); while open, a barrier across the street sends each page back at once (grey). On the plaza's edge, a dot per page served: blue with the count, amber without, grey refused without calling Stock. Model milliseconds; a 40 ms answer is drawn slower so you can see it.
Compare them all: timeouts, retries and a circuit breaker
The shop makes a page every 200 ms and asks Stock for each. At 0.8 s Stock answers one 503, then hangs from 2.15 s to 4.25 s. All four ways at once; each page's bar is as tall as it waited: blue got the count, amber waited and went without, grey never reached Stock: the breaker refused it at once.
Use it when Hardly anywhere. A call across a network with no timeout is a bug waiting for a slow day
Skip it when Every call across a network: a hung call holds a connection, a thread and memory until the other side gets better
From the same model as breaker.ts below, which really runs; every count matches what it printed. Press any tile to see it large above, with when it fits.
Four ways to call a service that may hang
| Way | In the picture (2 s hang) | What it costs | Suits |
|---|---|---|---|
| No timeout | 11 calls open at once; slowest page 2.05 s | threads, connections and memory, held as long as the other side hangs | almost nothing across a network |
| Timeout 300 ms | no page over 300 ms; Stock still gets 11 calls while down | every page in the outage loses 300 ms | every call to another service |
| + 2 retries, backoff + jitter | the 503 saved; 27 calls while down; pages up to 1.1 s | multiplies load on a service that is down; only for work safe to repeat | short faults: one 503, a dropped connection |
| + circuit breaker | 7 calls while down; slowest 0.7 s; 5 pages refused after Stock was back | a fallback to design; refusing until the next trial | a service that can be down for a while, with a fallback users accept |
A timeout on every call
A call that waits for ever holds what it holds for ever, and many clients have no limit unless you set one: Go's http.Client says a Timeout of zero means no timeout (net/http). The Azure Architecture Center warns that a timeout that is too long can tie up threads while the caller waits (Circuit Breaker pattern). Marc Brooker of AWS describes choosing one from the service's own latency: pick an acceptable rate of false timeouts, such as 0.1%, and use that percentile, p99.9 (Timeouts, retries, and backoff with jitter).
Retries: backoff, jitter and a budget
The same article calls retries “selfish”: each one asks a struggling service for more. Layers multiply them; if each of five layers retries on its own, the load on the database at the bottom grows 243 times. Exponential backoff waits longer before each retry, and jitter makes the wait random so clients that failed together don't retry together. AWS SDKs default to 3 attempts. Under their updated retry behavior of 2026 (opt-in for now, through AWS_NEW_RETRIES_2026), each wait is random(0, 1) × min(20 s, base × 2^retry), the base 50 ms for a transient error and 1,000 ms for throttling, and a retry quota of 500 tokens, 14 per transient retry, stops retrying when failures go on (AWS SDKs: retry behavior). In the picture, jitter spreads Stock's 27 calls; it doesn't make them fewer.
A retry needs idempotency
A timeout means you stopped waiting, not that nothing happened. AWS's rule: “APIs with side effects aren't safe to retry unless they provide idempotency.” In retry.go, a charge that answers too late is retried and the card is charged twice; sent with an Idempotency-Key, the server knows the retry and the card is charged once. The Idempotency lesson shows how the key works.
Closed, open, half-open
As the Azure Architecture Center describes it: Closed lets calls through and counts recent failures; past a threshold it opens and starts a timer. Open fails every call at once, and can return a default value. When the timer ends, Half-open lets a limited number of calls through: if they succeed it closes, if one fails it opens again and restarts the timer. Half-open keeps a recovering service from being flooded. Azure also says a retry and a breaker do different jobs, and that a retry should go through the breaker and give up when the breaker says the fault isn't transient.
opossum, really run
opossum, a circuit breaker for Node, defaults to a 10 s timeout, opens when more than 50% of the calls in a 10 s window failed, and stays open 30 s; then the next call is the trial, which closes it or opens it again (opossum docs). Set to 300 ms, 50% of at least 3 calls and 1 s open, it opened at 0.5 s, went half-open at 1.5 s and closed at 1.6 s; Stock got 10 calls of 15, and 5 pages were served the fallback without calling it.
In real code
// A shop page calls a stock service; four ways of making that call, run side by side, each against its own Stock.
// Stock answers in 40 ms, except: the first call from 0.7 s on gets a 503 (a blip), and from 2.15 s to 4.25 s it hangs:
// it takes calls and answers none, then restarts and drops every call it was holding. A page that can't get the stock
// count is still served, without it (a fallback). A page every 200 ms, 30 pages.
import { createServer, type ServerResponse } from "node:http";
import type { AddressInfo } from "node:net";
import { setTimeout as sleep } from "node:timers/promises";
const PAGES = 30, GAP = 200, OK_MS = 40, BLIP_AT = 700, DOWN = { from: 2150, to: 4250 };
const TIMEOUT = 300, ATTEMPTS = 3, BASE = 100, THRESHOLD = 3, OPEN_MS = 1000;
// Full jitter: wait a random time in [0, BASE × 2^k) before retry k + 1. Seeded (mulberry32) so every run is the same;
// real code uses Math.random().
function unit(seed: number): number {
let t = (seed + 0x6d2b79f5) >>> 0;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
}
const backoff = (page: number, k: number) => Math.floor(unit(5 + (page + 1) * 1000 + k) * BASE * 2 ** k);
/** Closed: calls go through, failures in a row are counted. Open: every call is refused at once, for OPEN_MS.
* Half-open: one trial call goes through; it closes the breaker or opens it again. */
class Breaker {
state: "closed" | "open" | "half-open" = "closed";
private fails = 0;
private trialOut = false;
readonly log: string[] = [];
allow(): "go" | "trial" | "refuse" {
if (this.state === "closed") return "go";
if (this.state === "half-open" && !this.trialOut) { this.trialOut = true; return "trial"; }
return "refuse";
}
succeeded(trial: boolean, page: number) {
if (trial) { this.state = "closed"; this.trialOut = false; this.log.push(`closed (page ${page}, trial)`); }
if (this.state === "closed") this.fails = 0;
}
failed(trial: boolean, page: number, n: number) {
if (trial) { this.trialOut = false; this.open(`page ${page}, trial`); }
else if (this.state === "closed" && ++this.fails >= THRESHOLD) this.open(`page ${page}, try ${n + 1}`);
}
private open(why: string) {
this.state = "open";
this.log.push(`open (${why})`);
setTimeout(() => { this.state = "half-open"; this.trialOut = false; this.log.push("half-open"); }, OPEN_MS);
}
}
type Way = "no timeout" | "timeout 300 ms" | "timeout + 2 retries" | "timeout + 2 retries + breaker";
const WAYS: Way[] = ["no timeout", "timeout 300 ms", "timeout + 2 retries", "timeout + 2 retries + breaker"];
async function run(way: Way, start: number): Promise<string> {
// ---- Stock ----
const clock = () => performance.now() - start;
let blipped = false, downCalls = 0, allCalls = 0;
const held: ServerResponse[] = [];
const stock = createServer((req, res) => {
const t = clock();
allCalls++;
if (t >= DOWN.from && t < DOWN.to) { downCalls++; held.push(res); return; } // hangs: no answer
if (!blipped && t >= BLIP_AT) { blipped = true; res.statusCode = 503; res.end(); return; }
setTimeout(() => res.end(JSON.stringify({ stock: 3 })), OK_MS);
});
await new Promise<void>((ok) => stock.listen(0, "127.0.0.1", ok));
const url = `http://127.0.0.1:${(stock.address() as AddressInfo).port}/stock`;
setTimeout(() => { for (const res of held) res.socket?.destroy(); }, Math.max(0, start + DOWN.to - performance.now())); // the restart
// ---- the shop ----
const timeout = way !== "no timeout", retries = way.includes("retries"), breaker = way.endsWith("breaker") ? new Breaker() : null;
let open = 0, maxOpen = 0;
async function call(): Promise<boolean> {
open++; maxOpen = Math.max(maxOpen, open);
try {
const res = await fetch(url, { signal: timeout ? AbortSignal.timeout(TIMEOUT) : undefined });
await res.arrayBuffer();
return res.ok;
} catch {
return false; // timed out, or dropped when Stock restarted
} finally {
open--;
}
}
async function page(i: number): Promise<{ stock: boolean; ms: number; tries: number }> {
const t0 = clock();
for (let n = 0; n < ATTEMPTS; n++) {
const pass = breaker ? breaker.allow() : "go";
if (pass === "refuse") break; // the fallback, at once, without calling Stock
const ok = await call();
if (ok) { breaker?.succeeded(pass === "trial", i); return { stock: true, ms: clock() - t0, tries: n + 1 }; }
breaker?.failed(pass === "trial", i, n);
if (!retries || n + 1 === ATTEMPTS) break;
await sleep(backoff(i, n));
}
return { stock: false, ms: clock() - t0, tries: 0 };
}
const pages = await Promise.all(Array.from({ length: PAGES }, async (_, i) => {
await sleep(Math.max(0, start + i * GAP - performance.now()));
return page(i);
}));
await sleep(Math.max(0, start + DOWN.to + 50 - performance.now()));
stock.close();
const withStock = pages.filter((p) => p.stock).length;
const slowest = Math.round(Math.max(...pages.map((p) => p.ms)));
const blip = pages[4].stock ? `with stock on try ${pages[4].tries}` : "without stock";
const line = `${way}: ${withStock} of ${PAGES} pages with stock · slowest page ${slowest} ms · Stock got ${downCalls} calls while down (${allCalls} in all) · at most ${maxOpen} calls open at once · page 4 (the 503): ${blip}`;
return breaker ? `${line} · breaker: ${breaker.log.join(" → ")}` : line;
}
const start = performance.now() + 100;
for (const line of await Promise.all(WAYS.map((w) => run(w, start)))) console.log(line);
node breaker.ts (Node 23.6+ · on Node 22 add --experimental-strip-types)It printed:no timeout: 18 of 30 pages with stock · slowest page 2053 ms · Stock got 11 calls while down (30 in all) · at most 11 calls open at once · page 4 (the 503): without stock timeout 300 ms: 18 of 30 pages with stock · slowest page 303 ms · Stock got 11 calls while down (30 in all) · at most 2 calls open at once · page 4 (the 503): without stock timeout + 2 retries: 23 of 30 pages with stock · slowest page 1142 ms · Stock got 27 calls while down (51 in all) · at most 6 calls open at once · page 4 (the 503): with stock on try 2 timeout + 2 retries + breaker: 14 of 30 pages with stock · slowest page 709 ms · Stock got 7 calls while down (22 in all) · at most 4 calls open at once · page 4 (the 503): with stock on try 2 · breaker: open (page 11, try 2) → half-open → open (page 20, trial) → half-open → closed (page 27, trial)
A real node:http Stock for each way, all four started together: 30 pages, one every 200 ms; a 503 at 0.8 s; a hang from 2.15 s to 4.25 s, then a restart that drops every call it held. A timeout per try (AbortSignal.timeout), retries with seeded full jitter, and a small breaker class. Node's standard library only; really run, and below is what it printed.
Common questions
What is a circuit breaker?
A wrapper around calls to another service. Closed: calls go through and failures are counted; past a threshold it goes Open: calls are refused at once, without calling, for a set time. Then Half-open: a few trial calls go through; success closes it, failure opens it again. Callers stop waiting on a service already known to be sick.
How is a circuit breaker different from a retry?
A retry hopes the next try works; a breaker stops calling what is likely broken. The Azure Architecture Center suggests both together: retry through the breaker, and stop retrying when it says the fault won't clear soon. In the picture, retries alone send Stock 27 calls while it's down; with a breaker, 7.
Why exponential backoff, and why jitter?
Waiting longer each time gives the other side room to recover; a random wait keeps clients that failed together from retrying together. AWS SDKs' updated retry behavior (2026) uses full jitter: random(0, 1) × min(20 s, base × 2^retry). Jitter spreads retries out; it doesn't make them fewer.
Is every request safe to retry?
No. A timeout means you stopped waiting, not that the other side did nothing. A read-only GET can be retried; a POST that charges a card needs an idempotency key so the server knows it's the same request. In retry.go a retry without a key charges twice, and with one, once.
How long should a timeout be?
From the service's real latency, not a round number. The AWS Builders' Library describes picking the percentile for the false timeouts you can accept, such as p99.9 for 0.1%. Too short cuts calls that were about to succeed; too long holds threads and connections.
What happens in half-open?
After its open time, the breaker lets a few trial calls through (opossum: the next one alone). Success closes it; failure opens it again and restarts the timer. It keeps a service that just recovered from being flooded by every waiting call at once.
What do users see while the breaker is open?
The fallback you designed: a cached value, the page without that part, or a note that something is wrong. In the picture the shop page still opens at once, just without the stock count. Without an acceptable fallback, a breaker only turns a long wait into a quicker error.
What are opossum's defaults?
opossum, a circuit breaker for Node, starts with a 10 s timeout, opens when more than 50% of the calls in the last 10 s failed, and stays open 30 s before going half-open. The example on this page sets 300 ms, 50% of at least 3 calls, and 1 s, so it all happens in a couple of seconds.
Next lesson
Where did the time go? Distributed tracingLevel: Deep
A breaker keeps callers alive while a service is sick; tracing finds which hop is slow and why.