A release fails 5% of its requests. Sent to everyone, it fails about 3,500 requests before the rollback ends. Sent to a 5% canary, about 180: the alarm rings just as fast, and each second reaches 20 times fewer users.
Pick who gets the release and drag its error rate, then watch the alarm and the failed requests. Then we build, piece by piece, tests you can trust, experiments that break the real system, history checkers, small batches, rollouts, canary statistics and the undo button.
You need what a server and a request are and what a probability is. Failure Modes helps. We build the rest from zero.
Illustrative and simulated: 1,000 requests a second, the old version fails 0.1%. Every 10 s a monitor tests the new version's errors against 0.1% (one-sided z score over 4, and at least 5 errors). The rollback then takes 60 s. Bars are averages over 200 seeded runs; the timeline is one run. Chapters 7 and 8 work each number.
Chapter 0
Pass every test in staging, then watch production find the bug in under two minutes
Your tests cover every line, and every one passes. Staging runs the new version on two servers for an afternoon and looks perfect. You deploy to 200 servers that take 1,000 requests a second. Two minutes later the first error appears in the logs.
The bug was always there. It fires only on a rare input, or a rare timing between two servers. Staging sent 10,000 requests; production sends that many in 10 seconds. A rare bug hides from small tests because of arithmetic, not bad luck.
How rare is too rare for staging? Call the chance that one request triggers the bug q, and the number of requests a test sends n. Call the chance the test sees the bug at least once Pseen.
P-seen equals one minus, one minus q, to the power n.
One minus q is the chance one request is safe. Raise it to the power n for the chance that all n are safe. One minus that is the chance at least one request hits the bug.
With made-up numbers: q = 0.00001, n = 10,000. Pseen = 1 − 0.9999910,000 = 0.095. Staging misses the bug 9 times in 10. Production at 1,000 requests a second sends 1/q = 100,000 requests in 100 s. It hits the bug after about 100 s on average.
Each blue row is one staging run; a red mark is where the bug fired. The bottom bar is production at 1,000 requests a second. Make the bug rarer, then send more staging requests.
Simulated: 20 staging runs, one seed; each request triggers the bug with chance q, independently. Real bugs that need two servers to race are rarer still in a two-server staging. Illustrative rates.
No amount of testing makes q zero. So the lesson has three defenses. Tests that are fast and trusted catch the common bugs. Experiments on the real system catch what tests cannot reach. Releases that reach a few users first, and undo fast, limit what slips through.
Failure. Symptom: errors start minutes after a deploy that passed every test. Measure: how many requests staging sent, against production's rate. Cause: the bug is rarer than one in the number of staging requests. Fix: send the release to a small share of real traffic first, and watch it.
Chapter 1
Shape a suite of 10,000 tests, then watch its wall time go from 4 minutes to 41
A unit test checks one function with no network, disk or database. It runs in milliseconds. An integration test checks two parts together, such as a service and its database, in about a second. An end-to-end test (E2E) drives the whole system the way a user does, in tens of seconds.
The test pyramid says: write many unit tests, fewer integration tests and few E2E tests. Software Engineering at Google suggests about 80% unit, 15% integration and 5% end-to-end. The reverse shape, mostly E2E, is the ice cream cone. It catches real bugs, but slowly, and a failure says only "something broke".
Google also sorts tests by size, the resources a test may use. A small test runs in one process. A medium test runs on one machine and may call only localhost. A large test may run anywhere. Bazel's default timeouts are 60 s, 300 s and 900 s. A "unit test" that writes a file is medium, whatever its name.
How long does a suite take? Call the number of tests of each kind Ni, the time one takes ti, and the parallel CI workers w. The wall time is T.
T equals the sum over i of N-i times t-i, all over w.
Multiply each kind's count N-i by its time t-i, and add the three. That is the total test time. Split it across w workers.
With made-up numbers: the pyramid gives 8,000 × 0.01 + 1,500 × 1 + 500 × 20 = 11,580 s. Over 50 workers, T = 232 s, about 4 minutes. The cone (1,000, 3,000, 6,000) gives 123,010 s, so T = 2,460 s: 41 minutes. The 500 E2E tests are 86% of the pyramid's time.
Each layer's width is its number of tests; the yellow bars are the time each layer costs. Pick a shape, then add workers.
Illustrative times per test (0.01 s, 1 s, 20 s) for 10,000 tests; perfect parallel split, no start-up cost. The 80/15/5 mix is from Software Engineering at Google, ch. 11.
Failure. Symptom: CI takes 45 minutes, so people merge before it finishes. Measure: wall time per run, and the share of it spent in E2E tests. Cause: an ice cream cone. Fix: move each check down to the smallest test that can catch it, and keep a few E2E tests for the main user paths.
Chapter 2
Add a few unreliable tests to a suite, then count how often a run fails with no bug at all
A flaky test passes and fails on the same code. It sleeps for a fixed time and loses a race, or it shares state with another test, or it calls a real network. Google reported that about 1.5% of all its test runs gave a flaky result, and that almost 16% of its tests showed some flakiness.
One flaky test is a nuisance. A hundred of them break the signal. Call the number of flaky tests in a suite k, and the chance that one fails on a given run f. Call the chance that a run fails with no real bug Pred.
P-red equals one minus, one minus f, to the power k.
The same at-least-once rule as chapter 0. One minus f is the chance one flaky test passes. To the power k, all k pass. One minus that is the chance the run goes red.
With made-up numbers: f = 0.05, k = 100. Pred = 1 − 0.95100 = 0.994. With 10 people who each run CI 5 times a day, 50 × 0.994 × 3 minutes to rerun = 149 minutes lost each day.
The worse cost is trust. Say 2% of commits carry a real bug. When almost every run is red anyway, a red run means a real bug only 2% of the time. People learn to press rerun, and the real bug gets rerun too.
Each square is one CI run on code with no bug: green passed, red failed. Add flaky tests, then turn on one automatic rerun.
Simulated: 50 runs, one seed; each flaky test fails with chance f, independently. A rerun passes the run unless the same test fails twice (chance f squared). Illustrative rates.
A rerun cuts Pred from 99.4% to 22%, because a flake must now fail twice: 1 − (1 − 0.052)100. But it also hides a real race that fails half the time. Those races are the bugs a distributed system has most.
Failure. Symptom: people rerun red builds without reading them. Measure: the share of red runs that pass on rerun with no code change. Cause: flaky tests. Fix: quarantine each flaky test out of the blocking suite, fix its cause (fixed sleeps, shared state, real network), and prefer small tests.
Chapter 3
Fail a dependency for a small group of users, then stop the experiment the second the hypothesis breaks
Tests check the failures you thought of. Chaos engineering injects a real fault into the running system to find the ones you did not. Netflix wrote it down (Basiri et al., IEEE Software 2016) as four principles. Build a hypothesis around steady state. Vary real-world events. Run experiments in production. Automate them to run all the time.
The steady state is one number that says users are fine. Netflix uses stream starts per second (SPS). The hypothesis says: "if the bookmark service fails, SPS stays the same." The experiment takes a small share of users and splits it into a control group and an experiment group. Only the experiment group sees the fault.
What if the hypothesis is false? Call the share of users in the experiment group s, and the share of their requests that fail if the fallback is missing e. The share of all users the experiment can hurt is its blast radius, B.
B equals s times e.
Only users in the experiment group see the fault, so at most s of all users. Of those, a share e fail. Multiply them. An abort rule then limits how long B lasts.
With made-up numbers: s = 0.01, e = 0.4, so B = 0.004, 0.4% of users. At 20,000 starts a second, 200 a second go to each group. The simulated abort fires 1 s after the fault starts, and about 90 starts fail in all.
Teal is the control group's success rate; pink is the experiment group under the fault, which starts at 20 s. Choose what the fault does, then switch off the abort.
Simulated, one seed: 20,000 starts a second, 99.5% succeed normally. Abort when the experiment's success falls below control's by a two-group z score over 4. The bookmark example and SPS are from Basiri et al. 2016; the rates are illustrative.
Netflix runs Chaos Monkey, which terminates production instances, continuously on weekdays, and Chaos Kong, which simulates losing a whole AWS region, about once a month. A game day is the manual version: the team breaks something on a schedule and also practises its own response.
Failure. Symptom: a chaos test turns into a real outage. Measure: the experiment's share of users, and the seconds from fault to stop. Cause: no small group, no abort rule, or a steady state nobody watched. Fix: start with a tiny s, abort automatically on the steady-state metric, and keep a one-command kill switch.
Chapter 4
Record every call and reply under a network partition, then search for one order that explains them all
A database says it is linearizable: every operation seems to take effect at one instant between its call and its reply. You cannot check that from one answer. A read that returns 1 is fine or wrong depending on what else happened, and when.
Jepsen, Kyle Kingsbury's test tool, checks the whole history. Several clients send reads and writes at once. A "nemesis" cuts the network between nodes. Jepsen records each operation's call time, reply time and result. A checker then searches for one order of the operations that respects real time and in which every read returns the last write.
In 2014 this found that etcd and Consul could return stale reads under a partition. Their "consistent" reads came from any node that still believed it was the leader. Knossos, Jepsen's checker, reported the history as not linearizable.
Why not try every order? Call the number of clients k, and the operations each client makes m. Each client's own operations keep their order. The number of possible orders is O.
O equals k times m, factorial, over m factorial to the power k.
Line up all k times m operations in any order: that is (km)! orders. Each client's m operations must stay in their own order, so divide by m! once for each of the k clients.
With 3 clients and 4 operations each: 12! / (4!)3 = 479,001,600 / 13,824 = 34,650 orders. With 5 clients and 10 each: 4.8 × 1031. Checking linearizability in general is NP-complete (Gibbons and Korach, 1997), so checkers prune: an operation that ended before another began must come first.
Each row is one client; a bar runs from call to reply. Blue bars are writes, teal bars are reads with the value they returned. Pick a history, then change what the read returned.
A toy history of one register that starts at 0, checked by brute-force search with the real-time rule. Knossos uses the same idea with much more pruning. The partition case has the shape of the 2014 etcd and Consul finding, not its data.
Failure. Symptom: a read returns a value that a newer, finished write replaced. Measure: a linearizability checker over a recorded history with partitions. Cause: a node that lost leadership still answers reads. Fix: confirm leadership with a quorum before each read, or use a lease that the clock cannot break.
Chapter 5
Batch 42 changes into one release, then count how often it fails and how long the search takes
A CI/CD pipeline takes each commit through build, tests and deploy with no manual step. Continuous integration merges and tests every change. Continuous delivery keeps every passing change ready to deploy. The point is small, frequent releases instead of large, rare ones.
DORA, Google's DevOps research program, measures delivery with a few numbers. Deployment frequency is how often you deploy. Change lead time is the time from commit to production. Change fail rate is the share of deployments that need immediate intervention. Failed deployment recovery time is how long that takes. DORA reports that speed and stability are not trade-offs: for most teams the numbers move together.
Why do small releases fail less? Say each change is bad with chance p, and a release holds k changes. By chapter 0's rule, the release fails with chance 1 − (1 − p)k. Then someone must find the bad change. Halving the batch each round, a bisect, takes log2 k rounds. Call the time of one build-and-test round tb, and the time to find the bad change Tfind.
T-find equals the ceiling of log base two of k, times t-b.
Test half of the k changes. The half that breaks holds the bad one. Repeat until one change is left. Each round costs t-b.
With made-up numbers: p = 0.02, k = 42. The release fails with chance 1 − 0.9842 = 0.57. Tfind = ⌈5.39⌉ × 20 = 6 × 20 = 120 minutes. With k = 1, a release fails 2% of the time and you know the suspect at once.
Each purple square is a change in the release; red ones are bad. Pink brackets show each bisect round. Grow the batch, then raise the chance that a change is bad.
Illustrative: each change is bad with chance p, independently. The device shows a release that failed, so if the seeded draw has no bad change it marks one. The bisect finds the first bad change; a second needs its own search.
Small batches do not reduce the bad changes people write. At 40 changes a day and p = 2%, about 0.8 bad changes a day reach a deploy either way. What changes is the search: one suspect instead of 42, and a rollback that undoes one change instead of a week of work.
Failure. Symptom: a weekly release breaks, and the cause takes a day to find. Measure: changes per deploy, and hours from failure to the culprit. Cause: big batches. Fix: deploy each change on its own, several times a day, behind the gates of chapters 6 to 8.
Chapter 6
Roll ten pods to a new version at peak load, then find how many you may take down at once
A rolling update replaces pods a few at a time; for a while both versions serve. Blue-green starts a full second copy (green) next to the live one (blue), then moves all traffic at once. Switching back is instant while blue still runs. A canary sends a small share of traffic to a few new pods first, and the rollout continues only if they look healthy.
Kubernetes rolls a Deployment with two limits. maxSurge is how many pods may exist above the desired count. maxUnavailable is how many may be missing. Both default to 25%; surge rounds up and unavailable rounds down. For 10 pods that is 3 extra and 2 missing.
Is 2 missing safe? Call the desired pods N, the requests each pod serves per second μ, and the peak load λ. The largest safe maxUnavailable is u.
u is at most N minus the ceiling of lambda over mu.
Lambda over mu, rounded up, is the pods the peak needs. Every pod above that is spare. You may take down only the spare ones, so u is N minus the pods needed.
With made-up numbers: N = 10, λ = 900, μ = 100. The peak needs 9 pods, so u ≤ 1. The default u = 2 leaves 8 pods: 800 requests a second against 900. For the whole rollout, 100 requests a second, 11% of the peak, have no pod.
Orange boxes are old pods, purple are new, pink are new pods not yet ready. The chart is ready capacity over time against the red load line. Raise maxUnavailable, then try blue-green.
Simulated, 1 s steps: 10 pods of 100 requests a second; a new pod is ready 30 s after it starts. The controller keeps at most N + surge pods and at least N − unavailable ready, as the Kubernetes docs describe. Surge and unavailable cannot both be 0. Illustrative times.
With surge 3 and unavailable 2, the simulated rollout ends in two 30 s waves, ⌈10 / (3 + 2)⌉ = 2. Blue-green needs 2N pods at the switch, 20 instead of 13, but never drops below N. In a rolling or canary update both versions serve, so the schema must work with both. Expand-contract does it in steps: add the new column, write both, backfill, switch reads, then drop the old one.
Failure. Symptom: latency spikes during every deploy, and only at peak. Measure: ready capacity during the rollout, against the peak load. Cause: maxUnavailable takes down pods the peak needs. Fix: set u from the formula, often 0 with a surge of 1 or more, or deploy off peak.
Chapter 7
Watch a canary's errors pile up, then compute the requests it needs to show it is worse
Google's SRE workbook defines canarying as "a partial and time-limited deployment of a change in a service and its evaluation." The canary is compared with a control: the old version, on the same kind of traffic, at the same time. The hard part is noise: at 0.1% errors, 3,000 requests show 3 errors on average, and 6 or more in about 1 run of 12.
So how many requests does a canary need? Call the old version's error rate p0, and the rate you want to catch p1. Call the false-alarm chance you accept α (alpha) and the chance to catch a real change, the power, 1 − β (beta). The requests needed are n.
n equals the square of: z-alpha times the root of p-nought times one minus p-nought, plus z-beta times the root of p-one times one minus p-one, all over p-one minus p-nought.
Each square root is the noise of one request at that rate. The top adds room against a false alarm to room against a miss. Divide by the gap p-one minus p-nought, and square. Half the gap needs four times the requests.
With made-up numbers: p0 = 0.001, p1 = 0.002. The top is 1.645 × 0.0316 + 0.842 × 0.0447 = 0.0896. Divide by 0.001 and square: n = 8,030 requests. At a 5% canary of 1,000 requests a second, that is 50 a second: 161 s. At 1%: 13 minutes.
Grey is what the old version would fail, yellow is the alarm line, red is the canary. The dashed mark is n. Change the release, then shrink the canary.
Simulated: one run per click, 1,000 requests a second in all. The alarm line is n·p0 + 1.645 √(n p0(1 − p0)). Over 400,000 runs at n = 8,027, the test caught 0.2% in 81% of runs. It gave a false alarm on 0.1% in 6.5%: the normal formula is rough with only 8 errors expected.
Bigger changes are cheap to see: at p1 = 1%, n = 227 requests, under 5 s at a 5% canary. Looking again every minute raises the false-alarm chance, so a monitor that checks often must set its line higher, as the hero's z of 4 does.
Failure. Symptom: canaries roll back good releases, or pass bad ones. Measure: false rollbacks and missed regressions over many releases. Cause: a fixed rule such as "over 2× baseline" on too few requests. At 0.1%, 3,000 requests show 7 or more errors 3.4% of the time. Fix: size the canary and its bake time from n.
Chapter 8
Release a feature to 10% with a flag, then compare the damage of three ways to undo it
Deploy puts new code on servers. Release lets users reach it. A feature flag splits the two: the code ships switched off, then a config value turns it on for 1%, 10%, then everyone. If it misbehaves, you turn the flag off in seconds, with no deploy.
A percentage rollout must be stable: a user must not flip between versions on each click. So every server hashes the flag name and user ID into a bucket from 0 to 9,999. The user is in if the bucket is below the percentage times 100. Over a million users, a 10% flag selected 99,677, within one standard deviation (300) of 100,000.
How much does slow undo cost? Call the extra share of requests the bad code fails Δe (delta e), and the request rate r. Call the share of traffic on the bad code s, and the seconds from first harm to the end of the undo t. The failed requests are D.
D equals delta e, times r, times s, times t.
r times s is the traffic on the bad code each second; delta e of it fails. Multiply by the seconds t. A canary shrinks s; automation and flags shrink t.
With made-up numbers: a manual rollback takes 5 minutes to notice, 5 to page, 15 to diagnose, 5 to decide and 5 to roll back, so t = 2,100 s. A full deploy then gives D = 0.05 × 1,000 × 1 × 2,100 = 105,000. An automatic rollback in 300 s gives 15,000. A 10% flag turned off 240 s in gives 1,200.
Each dot is a user; purple users get the new code. Drag the percentage, then pick the undo and read the red damage bars.
Buckets: a 32-bit FNV-1a hash of "flag:user" modulo 10,000. Damage: Δe 5%, 1,000 requests a second, illustrative times.
Each flag is an if-statement with two paths to keep working. Give every release flag an owner and a removal date, and delete it at 100%. A flag cannot undo data either: rows the new code wrote stay written, so schema changes still need expand-contract (chapter 6).
Failure. Symptom: an incident runs 35 minutes while people decide whether to roll back. Measure: seconds from the first bad request to the end of the undo. Cause: undo needs a human and a full deploy. Fix: roll back automatically on the canary's alarm, and put risky features behind a flag that one click turns off.
Chapter 9
Send releases through five stages with a gate after each, then compare a rule of thumb with a real test
Here every piece meets. Each release goes to 1% of traffic for 5 minutes, then 5% for 10, 25% for 15, 50% for 15 and 100% for 30. At the end of each stage a gate decides: go on, or roll back. A continuous alarm can also roll back mid-stage.
Two gates compete. The rule of thumb rolls back if the stage's error rate is over twice the baseline. The test rolls back if the errors sit 3.09 standard deviations above the baseline, a 0.1% false alarm per gate. It also alarms mid-stage at a z of 4. Ship one release to watch it climb, or ship a hundred to count the outcomes.
The purple steps are the share of traffic on the release; red ticks are its failed requests; a yellow line marks each gate. Pick a gate and a release, ship one, then ship a hundred.
Simulated, 10 s steps, 1,000 requests a second, baseline 0.1%. Stage shares and bake times follow a common staged plan; they are illustrative. "Mixed" draws 80 good, 15 subtle and 5 bad releases. The rollback takes 60 s at the stage's share.
Over 1,000 simulated subtle releases, the ratio gate let 7.9% reach everyone. Each cost 322 failed requests more than the old version would have, on average. The statistical gate let none through, at 18 extra each. Both gates rolled back about 3% of good releases.
Chapter 10
Keep the numbers, the safe-change rules and the code for your next release
Tests catch the common bugs if they are fast and trusted: many small tests, few flaky ones. Chaos experiments and history checkers catch what tests cannot reach. What still slips through, small batches, canaries sized by statistics, flags and automatic rollback keep small and short.
| Term | What it is | This lesson's number |
|---|---|---|
| Rare bug | Pseen = 1 − (1 − q)n | 1 in 100,000, 10,000 requests: 9.5% |
| Suite time | T = Σ Niti / w | pyramid 4 min, cone 41 min |
| Flaky suite | Pred = 1 − (1 − f)k | 100 at 5%: 99.4%; with one rerun 22% |
| Blast radius | B = s · e | 1% and 40%: 0.4% of users |
| Orders to check | (km)! / (m!)k | 3 clients, 4 ops: 34,650 |
| Bisect time | ⌈log2 k⌉ · tb | 42 changes: 6 rounds, 2 h |
| Safe unavailable | u ≤ N − ⌈λ/μ⌉ | 10 pods, peak 900: 1, not 2 |
| Canary sample | n from p0, p1, α, power | 0.1% to 0.2%: 8,030 requests |
| Undo damage | D = Δe · r · s · t | 105,000 manual; 1,200 flag at 10% |
| Change | Safe to roll back? | Why |
|---|---|---|
| Add an optional field | Yes | old code ignores fields it does not know |
| Add a table | Yes | old code never reads it |
| Rename a field | No | old code looks for the old name; do it as add, copy, switch, drop |
| Change a field's type | No | old code reads a type it cannot parse |
| Drop a column | No | old code still queries it; drop only after no version reads it |
python# size a canary, then gate one stage of a rollout on it from math import sqrt, ceil from statistics import NormalDist def requests_needed(p0, p1, alpha=0.05, power=0.8): za = NormalDist().inv_cdf(1 - alpha) # 1.645 zb = NormalDist().inv_cdf(power) # 0.842 return ceil(((za * sqrt(p0 * (1 - p0)) + zb * sqrt(p1 * (1 - p1))) / (p1 - p0)) ** 2) def gate(errors, requests, p0, z_crit=3.09): z = (errors - requests * p0) / sqrt(requests * p0 * (1 - p0)) return "roll back" if z > z_crit else "go on" n = requests_needed(0.001, 0.002) # 8027 print(n, "requests:", round(n / (0.05 * 1000)), "s at a 5% canary of 1,000/s") # 161 s print(gate(9, 3000, 0.001), gate(6, 3000, 0.001)) # roll back, go on
Now press Present or Teach and explain four things from memory. Explain why staging misses a 1-in-100,000 bug 9 times in 10. Explain why 100 tests that flake 5% of the time make 99.4% of runs red. Explain why a canary needs 8,030 requests to tell 0.2% from 0.1%. Explain why a 5% canary fails 20 times fewer requests than a full deploy with the same alarm. Then go back to the hero, pick Everyone, and drag the error rate down to 0.2%.