A short circuit in the bathroom trips its breaker. Only that circuit goes dark, and the fridge in the kitchen stays cold, because each room has its own circuit and its own breaker. Once it's repaired, you flip the breaker up once to try. If it trips again, it isn't fixed yet. The separate circuits are bulkheads, the breaker is a circuit breaker.
Both are resilience patterns: techniques that keep one broken part from bringing down the whole system. A good system isn't one that never fails, but one that fails gracefully.
One sick dependency, everything gets sick
This lesson's example model (and its Lab), 20 seconds in the middle of the ticket war:
ordersends 10 payments a second topayment(normally 120 ms) and 20 seat checks a second toticket(50 ms).- For outgoing calls,
orderhas 20 connections (a connection pool). A call that gets no connection fails at once. paymenthangs from second 2 to second 12: requests are accepted but never answered.ordergives up after a 2-second timeout.
Every payment to the hung payment holds one connection for 2 seconds. 10 a second × 2 seconds = 20 connections, which means the whole pool is held by payment. Seat checks get no connection, though ticket is healthy:
| Protection (2-second timeout) | Payments succeeded (of 200) | Waited 2 seconds, then failed | Refused at once | Seat checks failed (of 400) |
|---|---|---|---|---|
| timeout only | 100 | 100 | 0 | 168 |
| + bulkhead | 100 | 50 | 50 | 0 |
| + circuit breaker | 57 | 23 | 120 | 8 |
| breaker + bulkhead | 57 | 13 | 130 | 0 |
Look at the first row: 168 of 400 seat checks fail, about 42%, though ticket is healthy. All of it is because of payment. That's a cascading failure: one sick dependency uses up a shared resource, and the healthy parts fall with it. The other rows of the table are the patterns in this lesson.
Timeout: a limit on waiting
Every network call must have a timeout. Node's fetch only gives up after waiting about 5 minutes for headers (the Microservices Architecture lesson in the DevOps track). The length of the timeout shapes the damage too: in this model, a 1-second timeout means payment holds at most 10 connections, so seat checks survive; a 5-second timeout keeps the pool exhausted longer. A starting point: a little above the dependency's p99 response time (99% of requests finish under it).
Timeouts must also shrink as you go inward. If the load balancer gives up after 3 seconds, order mustn't wait 5 seconds for payment: the work is wasted because the user already got an error. The remaining time carried down to each call is called deadline propagation.
Retry with exponential backoff and jitter
Momentary failures (a lost packet, a pod restarting) deserve another try, but how you retry matters. Exponential backoff: the pause before each retry doubles, for example 1, 2, 4, 8 seconds, with a maximum (cap) of 8 seconds. Jitter: the pause is randomised. The full jitter formula:
// retry with exponential backoff + full jitter, at most 5 retries
async function withRetry(fn, { max = 5, base = 1000, cap = 8000 } = {}) {
for (let retry = 0; ; retry++) {
try {
return await fn();
} catch (err) {
if (retry === max) throw err;
const limit = Math.min(cap, base * 2 ** retry); // 1,000, 2,000, 4,000, 8,000, 8,000 ms
await new Promise((r) => setTimeout(r, Math.random() * limit)); // random between 0 and the limit
}
}
}
base * 2 ** retryis the exponential part;Math.min(cap, ...)stops it from growing without end.Math.random() * limitis the jitter: each client picks its own pause between 0 and that limit.
Why does jitter matter? The Lab's model: 2,000 clients fail in the same second while payment is down, then payment recovers and can take 600 requests per half second. Without jitter, they all retry at exactly second 1: 2,000 at once, 1,400 fail again, then retry together again at seconds 3, 7 and 15. That's a retry storm: waves of simultaneous retries that keep hitting a service that just recovered. 4,400 requests in total, and only done at second 15. With full jitter, the retries spread out: a peak of 1,145 per half second, 2,957 requests in total, done at second 7.7.
Retry only requests that are safe to repeat (GET, or ones carrying an Idempotency-Key, the Idempotency & Retry Safety lesson), and don't retry in two places at once (the Service Mesh lesson).
Circuit breaker: closed, open, half-open
A timeout limits how long you wait, but order still waits 2 seconds for every payment to a payment that's clearly dead. A circuit breaker stops calling a dependency that keeps failing. It has three states:
| Current state | Event | Next state |
|---|---|---|
| closed (normal) | a call succeeds | closed, failure counter back to 0 |
| closed | 3rd failure in a row (threshold 3) | open |
| open | a new request comes | refused at once, payment isn't called |
| open | 5 seconds pass | half-open |
| half-open | one trial request (the probe) succeeds | closed, counter 0 |
| half-open | the probe fails | open again, wait another 5 seconds |
In the Lab's model (2-second timeout), payment dies at second 2. The first failure is only noticed at second 4.0, because it has to wait out the timeout, and the third at second 4.2: the breaker goes open. At second 9.2 it goes half-open, sends a probe, payment is still dead, the probe times out at second 11.2: open again. At second 16.2 it's half-open, the probe succeeds at 16.4: closed. All that time payment only receives 80 requests, not 200, and users refused at once don't wait 2 seconds for the same result. The price: payment had actually recovered at second 12, but the breaker only finds out at 16.4.
The breaker wraps the call:
// order: call payment through a circuit breaker, 2-second timeout, fallback on failure
async function payOrder(order) {
if (!breaker.canTry()) return paymentFallback(order); // open: refused at once
try {
const res = await fetch("http://payment:8080/charges", {
method: "POST",
headers: { "Content-Type": "application/json", "Idempotency-Key": `ord-${order.id}` },
body: JSON.stringify({ orderId: order.id, amount: order.total }),
signal: AbortSignal.timeout(2000),
});
breaker.success();
return res;
} catch (err) {
breaker.failure();
return paymentFallback(order);
}
}
breaker.canTry()answers "yes" when closed, "yes, but only one" when half-open, and "no" when open.success()andfailure()report the result, and the state moves according to the table. Ready-made libraries: opossum (Node.js), Resilience4j (Java), Polly (.NET).
Bulkhead: a partition per dependency
A bulkhead is named after the partitions in a ship's hull: one compartment floods, the ship stays afloat. In software it means resources are split per dependency. The pool of 20 connections is divided: 10 for payment, 10 for ticket. When payment hangs, only payment's 10 connections run out; the 11th payment onwards is refused at once, and ticket keeps its 10 connections. The result in the table: seat checks failed 0. The partition can be a connection pool, a thread pool, a semaphore, or separate pods.
Fallback: still give something useful
When a call fails or the breaker refuses it, a fallback gives a backup answer instead of a raw error:
- Payment failed: "Payments are having trouble. We're holding seat A-12 for 10 minutes, try paying again shortly."
- Seat check failed: show the seat map from the cache, marked "data from 1 minute ago".
- Other concert recommendations failed: hide that section, the rest of the page works.
Users would rather see 80% of the features working than an error 500 page. This is called graceful degradation.
⚠️ Safeguards that make things worse
- Network calls without a timeout. One hung dependency holds connections and sets off a cascading failure.
- Retries without jitter. Every client retries in the same second and floods the service that just recovered.
- Retries without a circuit breaker. A dead service receives many times the requests exactly when it can least cope.
- A breaker that's too sensitive (open after 1 failure) keeps marking a healthy service as dead; one that stays open too long refuses traffic long after the dependency has recovered.
- An open breaker with no fallback. Users still get a raw error, just faster.
TL;DR: Resilience patterns stop one sick dependency from bringing everything down (cascading failure: in the Lab, a hung payment makes 168 of 400 seat checks to the healthy ticket fail too, because the connection pool runs out). A timeout limits waiting, a little above p99, and shrinks as you go inward. Retries use exponential backoff and jitter, random(0, min(cap, base × 2^retry)), so clients don't retry together and set off a retry storm; only for requests that are safe to repeat. A circuit breaker has three states: closed (normal, counting failures), open (after failures reach the threshold; requests are refused at once), and half-open (after the open timeout passes, one probe is sent to test; success goes back to closed, failure back to open). A bulkhead isolates resources (thread pool, connection pool) per dependency, so one troubled service can't use up another service's resources. A fallback gives a backup answer so the user still gets something useful.
⚡ One sick dependency, everything gets sick
Guess first: payment hangs, ticket is healthy, and order only has a 2-second timeout. Of 400 seat checks to ticket, how many fail?
168, about 42%. Every payment to payment holds one connection for 2 seconds, so the whole pool of 20 connections runs out.
Meaning: That's a cascading failure: one sick dependency uses up a shared resource, and the healthy parts fall with it. Every network call must have a timeout.
⚡ Retry with backoff and jitter
Write:
const limit = Math.min(cap, base * 2 ** retry); // 1,000, 2,000, 4,000, 8,000, 8,000 ms
await new Promise((r) => setTimeout(r, Math.random() * limit)); // random between 0 and the limit
Meaning: The pause before each retry doubles up to the cap, then gets randomised. Without jitter, every client retries in the same second and floods the service that just recovered (a retry storm).
⚡ Circuit breaker: closed, open, half-open
Meaning: Closed is normal. After 3 failures in a row, the breaker goes open: requests are refused at once without calling payment. After 5 seconds it goes half-open and sends one probe. The probe succeeds, back to closed. It fails, open again.
⚡ Bulkhead and fallback
Meaning: A bulkhead splits the pool: 10 connections for payment, 10 for ticket. When payment hangs, seat checks that fail drop to 0. A fallback gives a backup answer, such as holding seat A-12 for 10 minutes, instead of a raw error.