Resiliency Patterns

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.

Slow down payments

100 ms

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

Two Seconds to Zero Threads

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.

Say it aloud

N equals lambda times W.

N
N the average number of threads busy with these calls at any moment.
λ
lambda calls to payments per second: 100 here.
W
W the seconds each call holds its thread, from the call to the reply.
In plain words

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 numbers

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.

Fill the pool

Each square is a thread. Pink squares wait on payments. Drag the latency and the call rate, then press play to run 10 s.

30 s
100

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).

  1. Timeouts: pick the limit from the latency tail and cap the threads a call can hold.
  2. Retries: why a retry needs a budget, and what retries do to a struggling service.
  3. Breaker: the three states, and why thresholds need a window.
  4. Bulkheads: one pool per dependency, sized with Erlang C.
  5. Shedding: refuse work you cannot finish before the client gives up.
  6. Rate limits: token and leaky buckets for each client.
  7. Hedging: ask twice and take the first answer to cut the tail.
  8. Degrade: fallbacks and constant work.
  9. Showcase: switch every guard on a live checkout service.
  10. The field guide: numbers, defaults, code and links.
A service has 100 threads. Its dependency now answers in 30 s, and 50 calls arrive each second. About when are all threads busy?

Chapter 1

Pick the Timeout From the Tail

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.

Say it aloud

N equals lambda times the min of S and T.

N
N the threads busy with this call, on average.
λ
lambda calls to payments per second: 50 here.
min
the min of take the smaller of the two. A call ends at the reply or at the timeout, whichever comes first.
S
S how long payments would take to reply. 100 ms healthy, 30 s when it hangs.
T
T the request timeout: 500 ms here.
In plain words

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 numbers

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.

Set the timeout

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.

500 ms

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.

Payments has a p50 of 10 ms and a p99 of 200 ms. You set a 50 ms timeout. What happens?

Chapter 2

Retries Need a Budget

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.

Say it aloud

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.

M
M the load multiplier: calls that reach the dependency for each user request.
f
f the chance one call fails, from 0 to 1.
fr
f to the r the chance the last retry is needed: all r earlier tries failed. r is the retries after the first try.
In plain words

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 numbers

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.

Feed the retries back

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.

20%

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.

Payments is fully down. Clients allow 3 tries, with a 10% retry budget. About how many calls reach payments for each user request?

Chapter 3

Stop Calling What Is Failing

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.

  1. Closed. Calls go through. The breaker records each result in a window of recent calls.
  2. Open. The failure share in the window crossed a threshold. Calls fail at once, with no thread held and no load on payments, until a timer ends.
  3. Half-open. A few probe calls go through. If they succeed, the breaker closes. If one fails, it opens again.

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 θ.

Say it aloud

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.

Ptrip
P-trip the chance one full window of healthy calls holds enough failures to open the breaker.
Σk ≥ θn
the sum over k from theta n add up every failure count k that reaches the threshold: theta times n or more. Theta is 0.5 here.
C(n, k)
n choose k the number of ways to place k failures among n calls.
pk
p to the k the chance that k given calls all fail. p is the normal failure rate; the other factor makes the rest succeed.
In plain words

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 numbers

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.

Trip the breaker

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.

20%
20 calls

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.

Normal error rate 20%, threshold 50%. Why does a window of 20 calls trip far more often than its 0.26% suggests?

Chapter 4

Give Each Dependency Its Own Pool

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 = λ/μ.

Say it aloud

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.

C
C the chance a payments call finds all c slots busy and must wait.
ac/c!
a to the c over c factorial the weight of the state where all slots are busy. a is the offered load, λ divided by μ: the average slots in use. c over c minus a stretches it for the queue that forms.
Σk<c
the sum over k below c the weights of the states with a free slot: 0, 1, up to c minus 1 busy.
In plain words

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 numbers

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%.

Size the payments pool

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.

50
100 ms
40

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.

Payments takes 50 calls a second. With a 500 ms timeout, what is the most slots it can hold during a hang, on average?

Chapter 5

Refuse Work You Cannot Finish in Time

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.

Overload the server

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.

1,500

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.

Say it aloud

p equals the max of zero and R minus K times A, over R plus one.

p
p the chance the client refuses a new request itself, without sending it.
max
the max of take the larger. It keeps p at zero while the backend accepts enough.
R
R requests the application tried, in the recent window.
K
K how much more than the accepts the client may send. The book prefers 2.
A
A requests the backend accepted in the same window.
In plain words

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 numbers

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.

A FIFO server is overloaded. A request waits 5 s for a worker; its client times out after 3 s. What happens to the work?

Chapter 6

Meter Each Client

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?

Say it aloud

n of T is at most B plus r times T.

n(T)
n of T the requests the bucket admits in any stretch of T seconds.
B
B the bucket size: the tokens it can hold, so the biggest burst. 50 here.
r
r the refill rate: tokens added per second. 10 here.
T
T the length of the window you look at, in seconds.
In plain words

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 numbers

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.

Meter a burst

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.

10
50

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.

A token bucket has r = 10 a second and B = 50. The client was idle for 10 s. How many requests pass at once?

Chapter 7

Ask Twice, Use the First Answer

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.

Say it aloud

P-slow equals one minus, one minus q, to the N.

Pslow
P-slow the chance the whole request is slow: at least one of the N answers is slow.
q
q the chance one server's answer is slow: 0.01 here.
N
to the N N is the servers asked in parallel. One minus q to the N is the chance all N are fast.
In plain words

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.

With numbers

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%.

Fan out and hedge

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.

100

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.

Each of 100 servers is slow 1% of the time, independently. What share of fan-out requests is slow?

Chapter 8

Degrade on Purpose, Work at a Constant Rate

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.

StepWhat it returnsExample
Freshthe live answerpersonal recommendations
Stalethe last good answer, from a cacheyesterday's recommendations
Defaulta simpler answer that needs no dependencythe top sellers list
Errora 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.

Live through an incident

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.

During an outage, engineers make 50 config changes in a minute. Why does a constant-work config system not spike?

Chapter 9

Run the Checkout Service

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.

Break payments, keep checkout

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:

  1. All guards off, press Payments slow. Payments can serve about 35 a second of the 50 that arrive. Its queue grows, threads pile up on it, and about 20 s later search and cart fail too (Chapter 0).
  2. Turn on Timeouts. Search and cart recover. Payments still fails: its queue is full of calls whose callers already left (Chapters 1 and 5).
  3. Add Three tries. Payments load rises far past what it can serve (Chapter 2). Switch to Budget.
  4. Add Breaker and Bulkhead. Payments now fails fast most of the time, and its queue drains (Chapters 3 and 4).
  5. Press Traffic ×3 with everything off, then with only Shedding on (Chapter 5).

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.

Timeouts are on and payments slows. Search and cart recover, but payments stays at 0%. Why?

Chapter 10

The Field Guide

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.

Terms and numbers

TermWhat it isThis lesson's number
Busy threadsN = λW100 a second at 30 s: 3,000; a pool of 200 fills in 2 s
Timeout capN = λ min(S, T)T = 500 ms at the p99.9 of 469 ms: 25 threads in a hang
Retry loadM = (1 − fr+1) / (1 − f)f 0.5, 3 tries: 1.75; budget 10%: 1.1
False tripbinomial tail at θnp 0.2, n 20: 0.26% a window, about 127 trips an hour
Pool waitErlang Ca = 5: 10 slots wait 3.6%; a = 25: 40 slots wait 0.4%
Client throttlep = max(0, (R − KA)/(R + 1))3,000 tried, 1,000 accepted, K 2: 2,000 sent
Token bucketn(T) ≤ B + rTr 10, B 50: 50 at once, 650 a minute
Fan-out tail1 − (1 − q)Nq 1%, N 100: 63%; hedged: about 1%

Documented defaults

LibraryGuardDefaults
Resilience4jcircuit breakerlast 100 calls, at least 100, 50% failures, 60 s open, 10 half-open calls
Hystrix (maintenance mode)circuit breaker, thread pool10 s window, at least 20 requests, 50%, 5 s open; 1 s timeout; pool of 10
Envoycircuit breaking per cluster1,024 connections, pending and requests; 3 concurrent retries; retry budget 20% when set
AWS SDKsretries3 attempts, full-jitter backoff, a 500-token retry quota
Google SRE bookretries, throttling3 attempts per request, retries under 10% per client, K = 2

The order on one outbound call

  1. Rate limit the client: over its bucket, answer 429.
  2. Shed if overloaded or past the deadline: answer 503, lowest criticality first.
  3. Take a bulkhead slot: none free, fail fast or fall back.
  4. Ask the breaker: open, fail fast or fall back.
  5. Call with a timeout no longer than the time the caller has left.
  6. On failure, retry only if the call is idempotent and the budget allows, with backoff and jitter.
  7. Release the slot, record the result for the breaker, and pick the fallback step.

Corrections to common figures

The core as code

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

Keep going

The takeaway. Every call needs a timeout read off the tail. Retry only within a budget. Wrap each dependency in a breaker and a bulkhead. Shed what you cannot finish in time, and decide the fallback before the incident.

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.

Resiliency Patterns
SRE: cascading failures · AWS: load shedding · The Tail at Scale · Back to Gleams