Payments slows from 100 ms to 1 s. A checkout service with no timeouts loses all 200 of its threads in about 5 s, and search and cart fail with it. With timeouts, a circuit breaker and a bulkhead, search and cart stay at 100%.
Drag the payments latency, then switch the guards and watch the threads. Then we build, piece by piece, timeouts, retry budgets, circuit breakers, bulkheads, load shedding, rate limits, hedged requests and graceful degradation.
You need what a request and a thread are and what a percentile is. Service Communication and Failure Modes help. We build the rest from zero.
Simulated in your browser, illustrative: 150 searches, 100 cart reads and 50 payments a second; 200 threads; payments runs 12 workers; users give up after 2 s. Each chapter below builds one guard; Chapter 9 lets you switch them one by one.
Chapter 0
Count the threads a slow dependency holds, and watch a healthy service run out of them
A checkout service runs a pool of 200 threads. A thread is a worker that handles one request at a time, start to finish. When the request calls the payments service, the thread waits for the reply and does nothing else.
On a normal day payments answers in 50 ms. Today a disk is failing and each call takes 30 s. Payments is not down. It is slow. That is worse, because every caller keeps waiting. How many threads are busy? Call the calls arriving per second λ and the time each one holds a thread W.
N equals lambda times W.
This is Little's law. Calls start at lambda a second and each holds a thread for W seconds, so lambda times W threads are busy. If N passes the pool size, new requests find no free thread.
With made-up numbers: λ = 100 a second. At W = 0.05 s, N = 5 threads. At W = 30 s, N = 3,000, and the pool has 200. It fills in 200 / 100 = 2 s. After that, searches that never touch payments also wait for a thread.
Each square is a thread. Pink squares wait on payments. Drag the latency and the call rate, then press play to run 10 s.
A fluid model of Little's law: busy threads grow at λ a second until the first calls return after W seconds, and stop at the pool size. Illustrative numbers.
This is the start of a cascading failure. Slowness in one service exhausts its caller's threads, and the caller turns slow for its own callers. Failure Modes catalogues the faults. This lesson builds the guards that stop them from spreading.
Failure. Symptom: search fails during a payments incident, though search never calls payments. Measure: threads in use, split by the dependency each one waits on. Cause: one shared pool and no timeout on the payments call. Fix: a timeout first (Chapter 1), then a bulkhead (Chapter 4).
Chapter 1
Read the limit off the latency percentiles, then count how many threads a hung dependency can still hold
A timeout is the longest a caller waits before it gives up and frees the thread. There are two. The connection timeout limits the TCP handshake, so it fires when nothing answers at that address. The request timeout limits the wait for the reply, so it fires when the server is reachable but slow. Many HTTP clients have no request timeout by default.
A short timeout kills healthy calls that were only a little slow. A long one lets a slow dependency hold threads. AWS describes the usual way to choose. First pick the share of healthy calls you accept to lose, for example 0.1%. Then read that percentile off the dependency's latency: the p99.9, the latency that 99.9% of calls beat.
Now count threads during a slowdown. Call the calls per second λ, the time the dependency would take S and the timeout T.
N equals lambda times the min of S and T.
Little's law again, but each call now holds its thread for the min of S and T. No call holds a thread longer than T, no matter how slow payments gets. So lambda times T is the most threads payments can take.
With made-up numbers: healthy payments has a median of 100 ms and a p99.9 of 469 ms, so T = 500 ms loses 0.06% of healthy calls. When payments hangs at S = 30 s, N = 50 × 0.5 = 25 threads, not 50 × 30 = 1,500.
Bars are payment latencies on a log scale. Calls right of the yellow line time out and turn red. Drag the timeout, then slow payments ten times.
Illustrative lognormal latency: median 100 ms, spread 0.5 (p99 320 ms, p99.9 469 ms). Threads held assume 50 calls a second. The shares are exact for this model.
A common shortcut is "twice the p99", here 640 ms. It works, but it hides the choice. Name the loss you accept, then read the percentile. Never set a timeout from the median. With a p50 of 10 ms and a p99 of 200 ms, a 50 ms timeout cuts about 11% of healthy calls, not 1%.
In a chain, pass each hop the time its caller has left; Service Communication works this through three services.
Failure. Symptom: payments finishes work that nobody reads, and its load doubles during incidents. Measure: the callee's timeout against the caller's. Cause: the gateway gives up at 1 s while checkout waits 5 s for payments, so checkout keeps working for a user who left. Fix: each timeout shorter than its caller's, or a propagated deadline.
Chapter 2
Count the extra load that retries add at each failure rate, and cap it with a budget
A retry sends a failed call again. Against a brief fault it works: at a 1% failure rate, three tries all fail once in a million. Service Communication builds the basics: exponential backoff, jitter, idempotency keys, and why retries multiply across layers.
The cost: a retry is more load, sent when the dependency is already failing. Call the share of calls that fail f and the retries allowed after the first try r. If every call fails with chance f, the first try always goes, a second goes with chance f, a third with chance f squared.
M equals one plus f plus f squared, up to f to the r. That sum equals one minus f to the r plus one, over one minus f.
Add one call for the first try, then f for the second, f squared for the third. When f is small, M stays near 1. When f reaches 1, the client sends every try and M is r plus 1.
With made-up numbers: 1,000 requests a second, f = 0.5, r = 2 (three tries). M = 1 + 0.5 + 0.25 = 1.75, so the dependency gets 1,750 a second. With r = 3 it gets 1,875. If it is fully down, 3,000 or 4,000.
A retry budget caps the extra load for the whole client, not one request. The Google SRE book's version allows a retry only while retries stay under 10% of requests. Then M is at most 1.1, whatever f is. The AWS SDKs use a token bucket: retries spend tokens, successes refill them.
The blue bar is load on payments; the dashed line is its capacity. Load above capacity fails, which causes more retries. Drag the base failure rate and pick a policy.
Illustrative fluid model: 1,000 requests a second, capacity 1,100. Each round, calls fail at the base rate, plus the share of load above capacity. The read-out is the settled point.
At a 20% base rate, three tries lift success from 80% to 88%, but load rises to 1,737 a second. The budget reaches the same 88% with 1,100. Success stops at what payments can serve.
Failure. Symptom: payments recovers, then falls over again within seconds. Measure: calls a second at payments, split into first tries and retries. Cause: every client retries at full rate, so recovery meets a wall of retries. Fix: a retry budget per client, and retries at one layer only.
Chapter 3
Trip a breaker on a window of calls, wait, probe, and choose a window big enough to ignore noise
When payments is down for ten minutes, every call in those minutes waits for a timeout and fails. A circuit breaker, named in Michael Nygard's book Release It!, wraps the call and remembers recent results. It has three states.
Resilience4j's defaults: a window of the last 100 calls, at least 100 calls before it judges, a 50% threshold, 60 s open, and 10 probe calls. A small window reacts fast but trips on noise. How often? Call the window size n, the normal failure rate p and the threshold share θ.
P-trip equals the sum, over k from theta n up to n, of n choose k, times p to the k, times one minus p to the n minus k.
Each call fails with chance p, on its own. Count the chance of exactly k failures in n calls, for every k at or above theta n, and add them. That is the binomial tail.
With made-up numbers: p = 0.2, θ = 0.5. A window of n = 20 trips with chance 0.26%. A window of 100 trips with chance 2 × 10−11. The breaker checks after every call, and 0.26% per call at 50 calls a second is many trips an hour.
The purple window holds the last n results, green or red. The three circles are the states. Drag the normal error rate and the window, then break payments.
Simulated, illustrative: 50 calls a second, threshold 50%, open 5 s, 3 probes. False trips an hour come from a seeded hour of healthy calls in your browser.
At p = 20% and n = 20, the hour holds about 127 false trips. At n = 100 it holds none, and a real outage still opens it in under a second at 50 calls a second. Hystrix used a time window instead: 10 s, at least 20 calls, 50%, then 5 s open.
Failure. Symptom: the breaker opens and closes every few seconds while payments is half broken. Measure: state changes a minute, and the probe results. Cause: few probes, so one lucky probe closes it and a full load arrives. Fix: more probes, a failure-rate test in half-open, or a slow ramp back.
Chapter 4
Wall off the threads one dependency may use, and size the wall with Erlang C
Watertight walls called bulkheads split a ship's hull, so one breach floods one compartment. A software bulkhead gives a dependency its own limit: a thread pool, a connection pool, or a semaphore that counts calls in flight. If payments hangs, it can fill its 40 slots and no more. The other 160 threads keep serving search and cart.
How big should the wall be? Too small and payments calls wait for a slot on a healthy day. Calls arrive at random, so you need more slots than the average. With c slots, calls at λ a second and each holding a slot for 1/μ seconds, the chance a call must wait is Erlang C. Call the average busy slots a = λ/μ.
C equals a to the c over c factorial, times c over c minus a. All of that is divided by the sum over k below c of a to the k over k factorial, plus the same first term.
Weigh every count of busy slots. C is the weight of "all busy" divided by the weight of everything. The mean wait in the queue is then C divided by c times mu minus lambda.
With made-up numbers: λ = 50 a second at 100 ms, so a = 5. Eight slots: C = 17%, mean wait 5.6 ms. Ten: 3.6%. Twelve: 0.6%. In a slowdown capped by a 500 ms timeout, a = 25, and 40 slots give 0.4%.
Top: the 200 threads, with the purple wall around payments' share. Bottom: the chance of waiting for each pool size; the dot is yours. Drag all three.
Erlang C: exact for random (Poisson) arrivals and random (exponential) holding times. Illustrative rates. One fast server cannot stand in for c slots; that formula gives the wrong wait.
Two numbers set the wall. Erlang C on a healthy day gives the floor: here about 10. Little's law with the timeout gives the slowdown ceiling: λ times T, 50 × 0.5 = 25 busy. Add headroom and you get 35 to 40. A wall of 40 serves both and still leaves 160 threads.
Failure. Symptom: the bulkhead rejects payments calls at normal traffic, with payments healthy. Measure: bulkhead rejections against the payments call rate. Cause: a wall of 6 for an offered load of 5, so 59% of calls find it full. Fix: size from Erlang C at peak, not from the average.
Chapter 5
Shed requests at the server and throttle them at the client, so the work you do arrives in time
A server can finish 1,000 requests a second, and 1,500 arrive. With a plain first-in, first-out queue, the queue grows by 500 a second. After 2 s, every request has waited more than the client's 1 s timeout. The server still works flat out, but every reply goes to a client who left. AWS calls the useful part goodput: replies that come back without error and in time. Here it falls to zero.
Load shedding refuses the excess at once, with a cheap 503, so the rest stay fast. There are three common rules. Drop a request that has waited past its deadline. Cap the time in the queue. Or serve the newest first (LIFO), since its client is still waiting. Facebook's "Fail at Scale" article describes an adaptive LIFO and a queue-time limit based on CoDel.
Each column is one second. Green is goodput; dark red is work done for clients who left; light red is refused at once. Pick a rule and drag the load.
Simulated in your browser, illustrative: 10 workers of 10 ms each (1,000 a second), random arrivals, clients give up after 1 s. LIFO also drops requests older than 1 s from the back.
A shed request still costs the server something. Google's SRE book adds client-side throttling: each client counts its requests and the backend's accepts over the last two minutes, and starts refusing locally. Call requests R, accepts A and a multiplier K.
p equals the max of zero and R minus K times A, over R plus one.
While R stays under K times A, send everything. Past that, refuse the excess share yourself. The plus one keeps p defined when R is zero.
With made-up numbers: R = 3,000 a second, A = 1,000. With K = 2, p = 1,000 / 3,001 = 0.33, so 2,000 a second reach the backend. With K = 1.1, p = 0.63 and 1,100 reach it.
Not all requests are equal. Google tags each with a criticality: CRITICAL_PLUS, CRITICAL, SHEDDABLE_PLUS and SHEDDABLE, and sheds the lowest first. AWS advises finishing work already started, such as later pages of a listing, before new work.
Failure. Symptom: median latency looks great during an overload, yet users complain. Measure: latency of successful requests only, and the shed rate. Cause: fast 503s pull the median down. Fix: chart goodput and success latency apart from rejections.
Chapter 6
Let a token bucket pass bursts up to its size, or let a leaky bucket smooth them into a steady stream
Load shedding protects the server from all clients together. A rate limit protects clients from each other: one buggy client sending 10,000 a second should get 429 Too Many Requests, not everyone's capacity.
The token bucket is the common form. Tokens drip into a bucket at r a second, up to a size B. Each request takes one token. An empty bucket means reject. A full bucket lets a burst of B through at once. How much can pass in any window of T seconds?
n of T is at most B plus r times T.
The bucket starts the window with at most B tokens and gains r for each second of T. Every admitted request spends one. So no window ever passes more than B plus r times T.
With made-up numbers: r = 10, B = 50. After 10 s idle, the client can send 50 at once, not 100, because the bucket stops at B. In 1 s it gets at most 60; in 60 s at most 650.
Each dot is a request on a 10 s timeline: green passed, pink waited in the bucket, red rejected. The purple gauge is the bucket. Pick a bucket and send a burst.
Exact for this toy: 80 requests 5 ms apart starting at 1 s, then 3 a second. The leaky bucket here is a queue of B places drained at r a second.
The leaky bucket holds requests in a queue of B places and lets them out at exactly r a second. The burst passes, but late: at r = 10 the 50th waits 4.9 s. Use it when the backend needs a steady rate. A sliding window limit counts requests in the last minute; it allows the whole minute's quota at once.
Failure. Symptom: a client stays under its limit of 100 a second, yet the shared database melts. Measure: the client's total rate across all gateway instances. Cause: 20 instances, each with its own bucket of 100, so the real limit is 2,000. Fix: a shared counter, or divide the limit by the instance count.
Chapter 7
See why fan-out makes rare slow replies common, and cut the tail with a hedge sent after the p95
A search request asks 100 servers for a piece of the answer and must wait for all of them. Each server answers in 10 ms, but one time in 100 it takes a second: a garbage collection, a busy disk, a noisy neighbour. How often is the whole request slow? Call the chance one server is slow q and the servers asked N.
P-slow equals one minus, one minus q, to the N.
Each server is fast with chance one minus q. All N are fast with that chance multiplied N times. Anything else means at least one slow answer, and the request waits for it.
Dean and Barroso's example: q = 0.01, N = 100. P = 1 − 0.99100 = 63%. Even q = 0.0001 with N = 2,000 gives 18%, "almost one in five" in the paper.
The slowness usually comes from the server, not the request. So ask again elsewhere. A hedged request sends a second copy if the first has not answered by the p95 of its latency, and uses whichever answer comes first. Dean and Barroso report this limits the extra load to about 5%.
Bars count whole requests by latency on a log scale; red bars are over 500 ms. The yellow lines are the p50 and p99. Drag the fan-out, then turn on the hedge.
Simulated in your browser, illustrative: each answer takes about 10 ms, or about 1 s with chance 1%, independently. Independence flatters the hedge; a shared cause, like a slow network, would hit both copies.
In the toy, 100-way fan-out puts 63% of requests over 500 ms. The hedge cuts that to about 1%, for about 5% more calls, because both copies must be slow. The paper's real test read 1,000 keys from Bigtable across 100 servers. A hedge after 10 ms cut the p99.9 from 1,800 ms to 74 ms, with 2% more requests.
Failure. Symptom: hedging is on and an overloaded backend gets slower. Measure: hedges sent as a share of requests. Cause: a fixed hedge delay below the new p95, so most requests send two copies. Fix: hedge from a live p95, cap hedges at a few percent, and stop hedging under overload.
Chapter 8
Decide in advance what a failed call returns, and keep the work a system does the same in an incident as on a calm day
Every guard so far ends a call early. Then what does the user see? Graceful degradation means the answer gets worse, not absent. Decide the steps in advance, from best to worst.
| Step | What it returns | Example |
|---|---|---|
| Fresh | the live answer | personal recommendations |
| Stale | the last good answer, from a cache | yesterday's recommendations |
| Default | a simpler answer that needs no dependency | the top sellers list |
| Error | a clear failure, fast | "payment is unavailable, try again in a minute" |
Some features have no fallback: you cannot fake a payment. Those fail fast and clearly, so the page around them still loads.
The second idea is about work, not answers. Many systems do more work when things go wrong. They push every config change at once, check failed hosts more often, and send alert storms. AWS's Colm MacCárthaigh calls the fix constant work: do the same work every time, whether or not anything changed. AWS Hyperplane nodes fetch their whole config file every few seconds, even when it did not change.
The line is work per second on the config system over 3 minutes; the shaded minute is the incident. Pick a design and start the incident.
Illustrative: 1,000 hosts; 2 config changes a minute on a calm day; 50 in the incident minute, plus 300 extra health checks a second. The constant design fetches the full file every 5 s.
Push on change does 33 pushes a second on a calm day and 1,133 in the incident. That is a 34-fold spike at the worst moment. Constant work does 200 a second, every second. It wastes work on calm days and never surprises you. In Route 53's health checks, a checker with 10 checks still sends a full table of 10,000 results; 9,990 are dummies.
Failure. Symptom: the fallback fails the first time anyone needs it. Measure: how often the fallback path runs in normal traffic. Cause: the "cached" fallback calls the same database that is down, and nobody exercised it. Fix: test every fallback on purpose, and keep its data path separate.
Chapter 9
Switch each guard on and off, break payments three ways, and read which features survive
Here is the hero's checkout service with every guard on its own switch. Search, cart and payments share 200 threads. Payments runs 12 workers, so it serves about 105 calls a second when healthy, and fewer as it slows. Users give up after 2 s. The guards use this lesson's numbers: 500 ms timeout, 3 tries, a 10% budget, a 20-call breaker, a 40-slot bulkhead and a 200 ms queue-time cap.
The grid is the 200 threads: pink wait on payments, blue serve other work. The lines are the success rate of each feature over the last 30 s. Set guards, then pick a fault.
Simulated in your browser at real speed, from a fixed seed: random arrivals, lognormal latencies, a breaker that opens at 50% of 20 calls for 5 s and needs 3 good probes. Illustrative numbers.
Things to try:
The worked numbers, from the same engine, 60 s after payments slows to 200 ms: timeouts alone keep payments at 92%. Add three tries and it falls to 0%, with 156 calls a second at a service that serves about 53. Under Traffic ×3, no guards leave 0% of searches served; shedding alone keeps 98%.
Failure. Symptom: every guard is on and payments stays near zero after the incident ends. Measure: payments' queue length and its share of calls whose caller already left. Cause: payments has no deadline check of its own, so it drains a backlog of dead calls first. Fix: shed by deadline in payments too.
Chapter 10
Keep the numbers, the defaults, the order of the guards and the code for the next dependency you call
A slow dependency holds threads at a rate set by Little's law. A timeout caps the hold at λT. Retries help against brief faults and hurt under overload, so they need a budget. A breaker stops calls to a failing service and probes for recovery; its window must be big enough to ignore noise.
A bulkhead walls off each dependency, sized by Erlang C on a good day and λT on a bad one. Shedding and client throttling keep goodput near capacity. Rate limits keep one client from taking everyone's share. Hedges cut the fan-out tail for a few percent more load. A planned fallback and constant work keep incidents from changing the system's shape.
| Term | What it is | This lesson's number |
|---|---|---|
| Busy threads | N = λW | 100 a second at 30 s: 3,000; a pool of 200 fills in 2 s |
| Timeout cap | N = λ min(S, T) | T = 500 ms at the p99.9 of 469 ms: 25 threads in a hang |
| Retry load | M = (1 − fr+1) / (1 − f) | f 0.5, 3 tries: 1.75; budget 10%: 1.1 |
| False trip | binomial tail at θn | p 0.2, n 20: 0.26% a window, about 127 trips an hour |
| Pool wait | Erlang C | a = 5: 10 slots wait 3.6%; a = 25: 40 slots wait 0.4% |
| Client throttle | p = max(0, (R − KA)/(R + 1)) | 3,000 tried, 1,000 accepted, K 2: 2,000 sent |
| Token bucket | n(T) ≤ B + rT | r 10, B 50: 50 at once, 650 a minute |
| Fan-out tail | 1 − (1 − q)N | q 1%, N 100: 63%; hedged: about 1% |
| Library | Guard | Defaults |
|---|---|---|
| Resilience4j | circuit breaker | last 100 calls, at least 100, 50% failures, 60 s open, 10 half-open calls |
| Hystrix (maintenance mode) | circuit breaker, thread pool | 10 s window, at least 20 requests, 50%, 5 s open; 1 s timeout; pool of 10 |
| Envoy | circuit breaking per cluster | 1,024 connections, pending and requests; 3 concurrent retries; retry budget 20% when set |
| AWS SDKs | retries | 3 attempts, full-jitter backoff, a 500-token retry quota |
| Google SRE book | retries, throttling | 3 attempts per request, retries under 10% per client, K = 2 |
python# a breaker, a retry budget and a timeout around one call (sketch) import time, random class Breaker: def __init__(self, n=100, threshold=0.5, open_s=60, probes=10): self.n, self.th, self.open_s, self.probes = n, threshold, open_s, probes self.win, self.state, self.until, self.left = [], "closed", 0, 0 def allow(self): if self.state == "open" and time.monotonic() >= self.until: self.state, self.left, self.ok = "half", self.probes, 0 # timer over: probe if self.state == "half" and self.left > 0: self.left -= 1; return True return self.state == "closed" def record(self, ok): if self.state == "half": if not ok: self.trip() else: self.ok += 1 if self.ok == self.probes: self.state, self.win = "closed", [] return self.win = (self.win + [not ok])[-self.n:] # last n results if len(self.win) == self.n and sum(self.win) >= self.th * self.n: self.trip() def trip(self): self.state, self.until = "open", time.monotonic() + self.open_s def call(fn, breaker, budget, deadline, tries=3, base=0.05): for k in range(tries): left = deadline - time.monotonic() if left <= 0 or not breaker.allow(): break # fail fast try: out = fn(timeout=min(0.5, left)); breaker.record(True); return out except Exception: breaker.record(False) if not budget.take(): break # retries under 10% of requests time.sleep(random.uniform(0, base * 2 ** k)) # full jitter return fallback() # stale, default or a clear error
Now press Present or Teach and explain four things from memory. Explain why a slow dependency is worse than a dead one, with Little's law. Explain why retries without a budget triple the load on a down service. Explain how a breaker's window size trades speed for false trips. Explain why a FIFO server can do full work at zero goodput. Then go back to the hero, set payments to 1 s, and switch from No guards to Full kit.