CComputer Science, Built

Act IX · Systems at Scale

Part 50 of 61

Keeping It Running

Degreestarts at this level52 min of film17 chaptersprerequisites: Part 31, Part 38, Part 43, Part 48

Why does a system that survives the loss of half its capacity stay down after the capacity comes back?

The part opens with three post-mortems from the companies' own reports, Amazon S3 in 2017, Cloudflare in 2019 and CrowdStrike in 2024: each a routine change pushed too far, too fast. Reliability is then made arithmetic. Nines are downtime budgets, parts in series multiply their availabilities and parts in parallel multiply their failures, and a shared cause is a switch in series that caps the nines replicas can buy. An objective of 99.9% turns into an error budget that a synthetic month spends incident by incident, and burn-rate alerts are derived and scored. The turn comes with a server that loses half its capacity for ten seconds: without retries it answers again 11 seconds later, and with three immediate retries the load sent climbs to four times what users send and nothing is answered in time again. Retry budgets, load shedding and circuit breakers are measured against that trigger. The second half is about finding out: histograms and DDSketch, traces and their critical path, coordinated omission, a flame graph of Pebble running the Job, capacity plans, incidents and chaos experiments on the Job service and a Raft cluster. It ends at the frontier with gray failure and the triggers that tip a system into a metastable state.

What you need. Probabilities of independent events, and logarithms; no experience of being on call is assumed.

Mathematics, ideas and history
availability arithmetic, SLOs and error budgets, metastable failures, backoff and jitter, circuit breakers, quantile sketches, tracing, coordinated omission, flame graphs, incident response, chaos engineering
What we build or compute
the Job service under injected failure

What you will be able to do

Degree

  • Convert an availability into nines and into minutes of downtime a year, a month and a week.
  • Compute the availability of a request path built from parts in series and replicas in parallel.
  • Explain why the average of ten servers' 99th percentiles is not the fleet's 99th percentile.

Graduate

  • Derive the burn-rate threshold b = f x 720 h / w and choose the windows of a multiwindow alert.
  • Prove DDSketch's relative-error guarantee from its bucket boundaries.
  • Explain the loop that keeps a retrying server overloaded after its trigger ends, and why backoff with jitter does not break it but a retry budget does.

Research

  • Define gray failure by differential observability and say how a client can judge health from real requests.
  • Map which triggers, by depth and length, leave a retrying system collapsed, and state what a model of metastability would have to predict.

Industry

  • Detect coordinated omission in a load test and measure latency from intended send times instead.
  • Read a flame graph and check a sampling profile against the binomial error of its counts.
  • Design a chaos experiment with a steady state, a hypothesis, a control and a bounded blast radius.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Degree 18 min · Graduate 51 min · Research 52 min · Industry 39 min.

  1. 0Three post-mortemsDegree2 min
  2. 1Availability arithmeticDegree4 min
  3. 2SLOs and error budgetsDegree4 min
  4. 3How systems fail: gray, cascading, metastableGraduate4 min
  5. 4Timeouts, retries, backoff and jitterGraduate4 min
  6. 5Breakers, bulkheads and load sheddingGraduate4 min
  7. 6RedundancyDegree3 min
  8. 7Metrics, and why averages lieDegree3 min
  9. 8Logs and tracesIndustry3 min
  10. 9Coordinated omissionIndustry4 min
  11. 10Profiling and flame graphsIndustry2 min
  12. 11Performance method and capacityIndustry2 min
  13. 12Incidents and post-mortemsIndustry3 min
  14. 13Chaos engineeringIndustry3 min
  15. 14The Job service under faultsIndustry4 min
  16. 15Frontier: gray failure and metastabilityResearch1 min
  17. Recap, problems, and where this comes backAll tracks3 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.

Three post-mortemsDegree2 min

Three post-mortems. In February 2017 an engineer at Amazon ran a command to take a few servers out of the billing system of its storage service, S3. One input was mistyped. The command removed far more servers, including two subsystems that every request in the region depended on, and restarting them took hours. Amazon changed the tool to remove capacity slowly, and never below a safe floor. In July 2019 Cloudflare deployed a new firewall rule whose regular expression backtracked catastrophically, the failure Part 12 warned about. Pushed to every machine at once, it drove every processor serving web traffic to one hundred percent. And in July 2024 a content update for CrowdStrike's security sensor made its Windows kernel driver read memory out of bounds. About eight and a half million machines crashed, and would not boot until someone repaired each one by hand. None of these was exotic. Each was a routine change, pushed too far, too fast, with nothing to stop it.

A system is only as good as its worst hour, so reliability is counted in minutes. A year has five hundred and twenty-five thousand, nine hundred and sixty of them. Ninety-nine percent availability allows about three and a half days of downtime a year. Three nines allows under nine hours. Four nines, under an hour, about four minutes a month. Five nines, about five minutes a year, less than the time it takes to notice a problem. Each nine costs about ten times as much as the last, and this part is about how to buy them: the arithmetic of availability, budgets for failure, defences against overload, and the instruments that tell you what actually happened.

1Availability arithmeticDegree4 min

Availability is the fraction of time a service does its job. Engineers count it in nines: the number of nines is minus the logarithm, base ten, of the unavailability, and the unavailability times a period is the downtime that period allows. Two nines allows three and a half days a year; three nines, about forty-three minutes a month; four nines, four minutes a month, or one minute a week. Think of it as a budget rather than a promise. At four nines, a bad deploy that takes ten minutes to roll back spends more than two months of it at once.

Part 3's switch circuits show how the parts combine. Let a closed switch mean a part that is up, and a lit lamp mean the service works. In series, current needs every switch, so one part down takes the service down. If failures are independent, the probability that all are up is the product of their availabilities. Ten parts at ninety-nine percent give ninety percent; fifty give sixty. In parallel, the service is down only if every part is down, so multiply the unavailabilities instead. Two parts at ninety-nine percent give four nines; three give six. So a rule of thumb: in series the downtimes add, and in parallel the nines add.

Real systems are both at once. A request passes through name servers, then a load balancer, then an application server, then the database: four stages in series. Replicate each stage, and it becomes a parallel bank worth six nines or more. Now the series law adds three parts in a million: five and a half nines, under two minutes a year. Build the same path from one of each and it reaches only ninety-eight point seven percent, almost five days a year, dominated by its weakest part, the single application server. Replication buys the nines, but every one of these figures assumes the parts fail independently.

Where does a part's availability come from? A part runs for a while, fails, is repaired, and runs again. Here is one simulated server's year: up for random stretches averaging a month, seven hundred and twenty hours, then down for repairs averaging two hours. Over a long run the fraction of time up is the mean time between failures over that plus the mean time to repair: ninety-nine point seven two percent, which two hundred simulated years confirm. The formula has two levers, and they are worth exactly the same: failing half as often and repairing twice as fast both halve the downtime. Repair is usually the cheaper one: failing over in ten minutes is worth twelve times fewer failures.

Three replicas at ninety-nine point nine percent each promise nine nines, if they fail independently. But suppose a share of each replica's downtime has a common cause: a bad deploy, one power feed, one configuration file. That cause is a switch in series with the whole bank, and when it opens, every replica is down together. If just one percent of the downtime is shared, the three give five nines, not nine. At ten percent, four; at thirty percent, three and a half. The common part caps the whole at its own availability. The three post-mortems that opened this part were all of this kind: one change, applied everywhere at once.

2SLOs and error budgetsDegree4 min

Objectives, and the budget for failing to meet them. Reliability needs three words. An indicator, the SLI, is something measured: of the valid requests, the fraction that were good, say answered correctly within three hundred milliseconds. An objective, the SLO, is the target for that indicator over a window: here ninety-nine point nine percent over thirty days. It is an engineering choice, and it should be what users actually notice. An agreement, the SLA, is a contract with consequences, refunds when it is broken, and so it is set looser than the objective. In our synthetic month the indicator came in at ninety-nine point nine four five percent. It met the objective, and the gap between the objective and perfection is not waste. It is room to change things.

The objective turns into a resource. The error budget is the unreliability the objective allows: one bad request in a thousand, or the equivalent of forty-three minutes of total outage a month. Here is our synthetic month, spending it. Background errors trickle steadily. On day eight, a twenty-five minute outage at a quarter of requests takes fourteen and a half percent in one bite. On day fourteen a six-hour degradation takes ten percent. From day twenty a slow leak, only two errors in a thousand, quietly takes almost nineteen percent over three days. The month ends with fifty-five percent spent. The budget is the contract between the people who ship features and the people who carry the pager: while budget remains, ship; when it is gone, freeze risky launches and spend the effort on reliability.

When should the budget wake someone up? Measure the burn rate: the error rate divided by the rate the objective allows. A burn rate of one spends the budget in exactly thirty days; a burn rate of b spends it in thirty days over b. Two lasts fifteen days; six, five days; fourteen point four, just over two days. Now turn it around. To page when a share f of the month's budget has gone within a window w, the threshold is f times seven hundred and twenty hours, over w. The Site Reliability Workbook's choices: two percent in an hour gives fourteen point four, and pages; five percent in six hours gives six, and pages; ten percent in three days gives one, and opens a ticket for working hours.

We scored five alerting rules from the Workbook on this month, counting an incident as worth a page if it costs at least two percent of the budget. Paging whenever the error rate exceeds the objective over ten minutes catches everything at once, and pages twenty times, including for blips that cost half a percent. A thirty-six-hour window is quiet for blips, but slow to notice and slower to stop: it keeps paging for a day and a half after the outage. A single fast burn threshold misses the degradation and the leak entirely. Two burn rates, with a ticket for the slowest, catch all three significant incidents, but the six-hour window keeps the page firing for six hours. The cure is a second, short window that must agree: the alert ends half an hour after the outage does. That last rule is the Workbook's recommendation.

3How systems fail: gray, cascading, metastableGraduate4 min

How systems fail, and why some failures outlast their causes. Failures come in kinds, and each kind contains the ones before it. The kindest is fail-stop: a machine halts, and everyone else can tell that it has. Fault-tolerant protocols love it. A plain crash halts without announcing it. Omission loses some messages and not others. A timing failure answers, but too late: a slow disk, a long pause. And an arbitrary failure may do anything at all, even send wrong answers. The failures that hurt most in practice are gray: partial, intermittent, and seen differently by the health check, which reports all is well, and by the users, who are timing out. Chapter fifteen returns to them.

Failures spread. Five servers share a load that keeps each one seventy-two percent busy. One fails, and the balancer moves its share to the other four: each is now at ninety percent. The load each survivor carries is the original times n over n minus k. A second one fails, perhaps because ninety percent made it slow enough to fail its health check, and the remaining three are asked for a hundred and twenty percent. They cannot give it. Queues grow, they too look dead, and the cascade takes the rest. The remedies come later in this part: headroom, so that losing machines does not overload the rest, and servers that refuse excess work instead of falling over under it.

Now the strangest failure of all. In this simulation a server answers a hundred requests a second, and users send eighty: comfortable. Clients give up on a request after one second. At thirty seconds comes a trigger: for ten seconds, capacity halves, as when a replica is lost or a long pause stalls the server. Without retries, a queue builds, requests time out, and eleven seconds after the trigger ends the server has caught up. Now let each client retry a timed-out request up to three times, immediately. The same ten seconds tip it over. The load sent climbs to about 320 requests a second, four times what the users want, and the number answered in time falls to zero, and stays there, eighty seconds after the trigger has gone. Nothing is broken any more. The system is simply stuck.

Nathan Bronson and colleagues named this a metastable failure, in 2021. A system is stable at low load. At high load it becomes vulnerable: still working, but a trigger can push it into a bad state, and the bad state sustains itself. Here is the loop. The queue is long, so requests wait past their timeout. Their clients retry, so there is more load than capacity, so the queue stays long. Meanwhile the server is fully busy, with work for clients who have already given up. Removing the trigger does nothing, because the loop no longer needs it; only cutting the load breaks it. Huang and colleagues, in 2022, found this pattern in the incident reports of many large services. The next chapter is about retrying without feeding the loop.

4Timeouts, retries, backoff and jitterGraduate4 min

A request that never returns is worse than one that fails. A timeout turns an endless wait into a known failure; set it from the dependency's measured latency, a little above its ninety-nine point nine percentile, and pass the deadline down, so that inner layers stop working for callers who have given up. Failures can be retried. But look what happens when every layer does it. The database is down, and each of three layers tries four times. One tap becomes sixty-four attempts on a database that is already struggling. So retry at one layer only, and only requests that are safe to repeat, with Part 43's idempotency keys.

Retry immediately, and clients that failed together fail together again. Here twenty clients each need one write to the same record; a write fails if another overlaps it. With no backoff they collide every time, for ever. Exponential backoff, waiting one, two, four, eight units, makes far fewer attempts, but the clients stay in lockstep, wait the same time, and collide again. Add jitter, a random wait between zero and the exponential bound, and the herd spreads out. The white dots are successes: all twenty finish, after a hundred and seventy-five attempts. Randomness breaks the symmetry, as it did for Ethernet in 1976.

Marc Brooker compared ways to back off in 2015; we repeat his experiment with a hundred clients. With no backoff, almost a million calls, and the clients never all finish. Plain exponential backoff cuts the calls to under three thousand, but still never finishes. Full jitter waits a random time up to the exponential bound. Equal jitter keeps half the bound and randomizes the rest. Decorrelated jitter grows from the previous wait instead. All three finish, with about a thousand to eighteen hundred calls. Between them the differences are small, and change with the load. The lesson is the one Brooker drew: backoff without jitter is the mistake; any jitter is far better.

Back to chapter three's metastable server. Give them exponential backoff with full jitter. It does not help. Backoff spreads the retries out in time, but every timed-out request still makes up to four attempts, and the sent load stays near three hundred a second. The loop holds. What breaks it is limiting the number of retries. With a retry budget, each client may add retries worth at most a tenth of its first attempts, kept as a token bucket like Part 48's rate limiter. The sent load can rise only ten percent above demand, the queue drains, and the server answers again nineteen seconds after the trigger. Google's SRE book recommends the same ten percent.

One kind of retry makes things faster. A request goes to server A, which happens to be in a long pause. If no answer has come by a short deadline, send a copy to server B, take whichever answer comes first, and cancel the other. Jeffrey Dean and Luiz Barroso called these hedged requests, in The Tail at Scale: the tail of Part 39. In our simulation, replies are usually quick, but one request in fifty hits a two-hundred-millisecond pause. Without hedging the ninety-ninth percentile is two hundred milliseconds. Hedging at fifty milliseconds cuts it to fifty-three, for two percent more requests; at twenty, to twenty-five, for under four percent. Hedge earlier, and the extra load grows faster than the tail shrinks.

5Breakers, bulkheads and load sheddingGraduate4 min

Michael Nygard's book Release It!, in 2007, borrowed a device from electricians. A circuit breaker sits in the client, in front of a dependency. Closed, it lets calls through and counts the failures. When most recent calls fail, it trips open: every call fails at once, with no timeout to wait for and no load added to a struggling dependency. After a cool-down it goes half-open and lets a few probe calls through. If they succeed, it closes again; if they fail, it opens again.

Here is chapter three's server again, its clients retrying three times. Without a breaker, the retries hold it in the bad state for good. Now give every client a breaker. Two seconds into the trigger most calls are failing, the breakers open, and the load sent falls almost to nothing. The server drains its queue, the probes succeed, the breakers close, and the server is answering at full rate as the trigger ends. In all, nine thousand one hundred and ten answers in time, against two thousand five hundred and sixty-seven.

The server can defend itself too. Before serving a request, it checks how long the request has waited, and drops it if that is over half a second, since its client is about to give up. A rejection costs a fiftieth of an answer. Through the trigger it sheds what it cannot serve in time, answers the rest at its reduced capacity, and afterwards recovers at once. This is CoDel's idea from Part 37, moved from routers to services: judge a queue by how long its requests have waited, not by its length. Ben Maurer described Facebook's servers doing this in 2015, switching to last in, first out when the queue is long, so that the newest requests are served first.

Put the six side by side. Users sent eighty requests a second for two minutes. Immediate retries, with or without backoff, answered just over a quarter of them; the retry budget recovered after nineteen seconds, and no retries at all after eleven. Shedding and the breakers never got stuck. What works is reducing the load, at the server or at the client, and real systems combine all three.

A ship's hull is divided by bulkheads, so that one leak floods one compartment, not the ship. A service calls A forty times a second and B twenty, from one pool of thirty threads; a call that finds no free thread is rejected. At twenty seconds B turns slow, two seconds a call instead of fifty milliseconds, and its calls fill the pool. So calls to the healthy A fail too: in the worst second, only twenty-eight percent succeed. Split the pool into two bulkheads of fifteen, and A does not notice. B, with half the threads, does worse. The damage stays where it started.

Serving something less is better than refusing. A product page has parts that matter unequally. When the recommender is slow, the page neither waits nor fails: it shows a cached list of popular items, and the price and the buy button still work. Overload can also be pushed back to its source: Part 43's backpressure bounds every queue, so a full queue slows the producer instead of growing. And when something must be refused, refuse the least important first. Google's SRE book describes tagging each request with a criticality, from critical plus down to sheddable, and shedding from the bottom.

6RedundancyDegree3 min

Redundancy: how many spares, and where to put them. Redundancy starts with counting. A service needs the capacity of ten machines, and each machine is up ninety-nine percent of the time, independently. With exactly ten, the service is whole only when all ten are up: ninety percent of the time, about one nine. Add one spare, N plus one, and it survives any single failure: two point three nines. But machines are also taken out on purpose, for deploys and maintenance, and a failure during that window finds no spare. So the usual rule is N plus two, three point seven nines here. Jim Gray's 1985 study of Tandem's fault-tolerant computers found that operations and software, not hardware, caused most of their outages. Plan for the machine you take out yourself.

There are two ways to keep a spare. Active-passive: a primary serves, and a standby follows its log, ready to take over. When the primary dies, something must notice and promote the standby, and that time is downtime, chapter one's repair time. Worse, the standby has never served real traffic, so failover is the least tested path in the system. Active-active: every copy serves all the time, so failover is only routing, exercised every day. The price is headroom. To lose one of n sites, each must run below n minus one over n of its capacity: a half for two sites, two thirds for three. It is chapter three's cascade arithmetic, run in reverse.

The largest unit of redundancy is a whole region, a separate set of buildings, power and network, because, as chapter one showed, replicas that share a cause fail together. Three regions share the traffic, each sixty percent busy. Region two starts to misbehave: errors are rising, and nobody yet knows why. The first move is not to debug but to evacuate: steer its traffic to the other two, which rise to ninety percent. Debug afterwards, with no users waiting. Evacuation needs three things ready in advance: headroom in the other regions; the data, already there through Part 39's replication, since whatever had not been copied is lost or stranded; and practice, because an evacuation that has never been rehearsed is a hope, not a plan.

7Metrics, and why averages lieDegree3 min

Prometheus, begun at SoundCloud in 2012, stores three kinds of metric. A counter only goes up: requests, errors, bytes. You chart its rate, which survives a missed reading and a restart that resets it. A gauge goes up and down: queue length, memory in use. A histogram counts observations into buckets: under ten milliseconds, under twenty-five, under fifty. Buckets add, across servers and across time, and that turns out to matter.

Here are two hundred thousand simulated latencies, on logarithmic axes. Most take about twenty milliseconds; one in twenty misses a cache; one in two hundred falls into a heavy tail. The mean is thirty milliseconds, a latency almost no request has. The median, twenty and a half, is what a typical request sees. The ninety-ninth percentile is a hundred and seventy-seven, the ninety-nine point ninth eight hundred and thirty-four, and the slowest took a hundred and four seconds. And the tail is not rare for users: a page making a hundred requests meets one beyond the ninety-ninth percentile sixty-three times in a hundred, as Dean and Barroso pointed out.

Now ten servers, one of them four times slower than the rest. Each reports its ninety-ninth percentile: about a hundred and seventy-five milliseconds for nine, seven hundred and nineteen for the slow one. A dashboard that averages them shows two hundred and thirty. But the true ninety-ninth percentile of the fleet's requests is two hundred and seventy. Percentiles do not average. Distributions do combine: add the servers' histograms bucket by bucket, then read the quantile: two hundred and sixty-eight, within the sketch's one percent.

In 2019 Charles Masson, Jee Rim and Homin Lee, at Datadog, published a sketch with a guarantee, DDSketch. Choose a relative accuracy, alpha. Bucket boundaries are powers of gamma, one plus alpha over one minus alpha, so the buckets grow geometrically. To answer a quantile, find the bucket holding that rank and return two gamma to the i over gamma plus one. For any value in that bucket, the answer divided by the value lies between one minus alpha and one plus alpha. So the error is relative: one percent of a twenty-millisecond median, and one percent of a two-second tail. At one percent, these latencies fill three hundred and thirty-two buckets, and sketches merge by adding counts.

8Logs and tracesIndustry3 min

Logs and traces: following one request through many services. In 2010 Benjamin Sigelman and colleagues described Dapper, Google's tracing system. One user request crosses many services, and each unit of work becomes a span: a name, a start and an end, and three identifiers. The trace identifier is shared by every span of the request. The span identifier is the span's own. The parent identifier names the span that caused it, so the spans form a tree. The identifiers travel with the request in a header, which the W3C's Trace Context standard calls traceparent. Each service reads it, starts a child span, and passes the header on. Spans are reported separately and joined later by trace identifier. OpenTelemetry, formed in 2019, is today's common toolkit for all of this.

Here is one trace from our simulator, drawn as a waterfall: time runs to the right, and each span is indented under its parent. The front end starts, and checks authentication first. Then it calls the catalog and the recommender at the same time, and each calls its own dependencies in turn: a cache and then a database; features, and then a model. When both have answered, it renders the page. The whole request took thirty-two point six milliseconds. If it has to be faster, where should the effort go?

The answer is the critical path: the chain of work the end was waiting for. Walk back from the end: the front end waited for render, render for the recommender, the recommender for its model, the model for the features, and so back to authentication. It is the longest path through the DAG of the trace's work, as in Part 19. Along it the model accounts for twelve point six milliseconds, render for six, the features for five point eight. The catalog and its database are not on it. The database takes twelve and a half milliseconds, yet making it faster would save nothing. The catalog has seven point three milliseconds of slack: shave more than that off the model, and the catalog becomes critical instead.

Tracing every request costs too much, so traces are sampled. Head sampling decides at the first span, with a coin that keeps one trace in a hundred, and the decision travels in the context, so every service keeps the same traces. Of fifty thousand simulated requests it kept five hundred and thirty-three, but only four of the eight hundred and seventy-six that failed, and fifty-four of the four thousand three hundred slow ones. Tail sampling decides when the trace has finished: keep every error, every trace over a hundred milliseconds, and one in a hundred of the rest. That kept all of them, in five thousand five hundred and eighty-four traces. The price: every span is buffered until its trace ends, at one collector chosen by hashing the trace identifier, Part 39 again.

9Coordinated omissionIndustry4 min

Coordinated omission: how a load test can hide the very tail it was built to measure.

Here is a load test. A generator is meant to send a hundred requests a second to a server that answers in one millisecond, except that every forty seconds the server freezes for four, as in a long garbage-collection pause. The generator is a closed loop: it sends a request, waits for the answer, then sends the next. When the server freezes, one request waits four seconds, and that is one sample. But in those four seconds the generator should have sent four hundred requests. Waiting, it sent none of them, so none were measured. The generator has coordinated with the server, against the measurement. Over two hundred seconds, twenty thousand requests were due, and eighteen thousand and five were recorded. The nineteen hundred and ninety-five skipped are exactly the ones that would have waited.

Compare what the generator reported with the truth, measured from when each request should have been sent. The closed loop says the median is one millisecond, and so are the ninetieth, the ninety-ninth and even the ninety-nine point ninth percentiles. Only the maximum, four seconds, hints at trouble, and a maximum is easy to dismiss as a fluke. But the server was frozen a tenth of the time, so about a tenth of the requests due had to wait. The true ninetieth percentile is four hundred milliseconds; the ninety-ninth, three point six seconds. Even the mean is a hundred times larger: two hundred and twenty-three milliseconds, against two. A team reading the first column would ship a service whose users wait seconds.

Look at one freeze through the requests' eyes. The closed loop has a single point: one request that waited four seconds. A request due a second into the freeze waits about three; one due near the end waits a moment, and then the backlog drains at a millisecond each. The true waits form a ramp from four seconds down to one millisecond, and the red area is what the test never saw. Gil Tene, of Azul Systems, named this coordinated omission. The cure is to send at fixed times, whether or not the last reply has arrived, an open loop, as his load generator wrk2 does; or else to charge every sample from its intended start time, a correction his HdrHistogram library can apply.

The deeper lesson is about the shape of the load. In 2006 Bianca Schroeder, Adam Wierman and Mor Harchol-Balter called their paper on it a cautionary tale. In a closed system, a fixed number of users each think for a second, send one request, and wait for it. Response time stays bounded, because when the server slows, the users wait instead of sending, as our generator did. In an open system, requests arrive whatever happens, and Part 31's queue gives the response time at the same throughput. At ninety-two percent busy, the closed system answers in eighty-two milliseconds and the open one in a hundred and thirty-two. At full load the closed mean is half a second, while the open queue grows without limit. A web service faces many independent users, which is close to open. Test it with a closed loop, and you measure a gentler world than the one it lives in.

10Profiling and flame graphsIndustry2 min

Profiling: finding where the time goes, and drawing it as a flame graph. A sampling profiler does not trace every step. Now and then it interrupts the program and asks where it is. Pebble runs version zero of the Job over twenty thousand bytes of a novel: six point three million instructions. Every nine hundred and ninety-seventh, a prime, so that it cannot fall into step with a loop, the profiler reads the program counter. It maps the address to its routine, and the routine to its callers: main, then word, then scan. Counting the stacks gives a folded profile of six thousand three hundred and eleven samples, more than four in five of them in scan and next, the loop that walks the table.

In 2011 Brendan Gregg found a way to see a profile at a glance: the flame graph. Each box is a frame, as wide as the share of samples with that frame on the stack. Callers sit below their callees, so the top edge is where the processor actually was. Left to right is alphabetical, not time, so identical stacks merge. Read ours from the bottom. Word takes ninety-four and a half percent of all samples. Above it, scan and next take eighty-two, and cmp, comparing letters, most of the rest. The Job walks its table, entry by entry, for every word. The profile does not say make this loop faster. It says do not loop: Part 17's hash table finds a word in one probe.

A profiler that samples the processor sees only time spent running. Real requests also wait: for a disk, a lock, a reply from the network. Timer samples land only where the thread was running, so a request stuck behind a lock can look idle. Off-CPU analysis catches the rest. Each time the scheduler switches a thread out, record its stack, and when it runs again, charge the time away to that stack. On-CPU plus off-CPU is wall-clock time. eBPF, from Part 31, makes this cheap: a small verified program on the scheduler's tracepoint sums the waits inside the kernel, and only the totals reach user space.

11Performance method and capacityIndustry2 min

Performance as a method: where to look first, how much capacity to buy, and how to notice when things get slower.

Faced with a slow system, the worst method is to look wherever you happen to know the tools. Brendan Gregg's USE method is a checklist instead. For every resource, the processors, memory, disks and network, check utilisation, the share of time it was busy; saturation, the work queued that it cannot take yet; and errors. Going down the list finds what the eye misses. Here the disk is only sixty percent busy, yet requests queue for it in bursts. Saturation, not utilisation, was the clue. For services, Tom Wilkie's RED method asks for the rate of requests, the errors, and the duration, as a distribution, as chapter seven insisted. Google's site reliability book calls its version the four golden signals: latency, traffic, errors and saturation.

Capacity planning asks how many servers next year's load will need, and queueing theory answers. Each book takes the Job's service eighty milliseconds, and we want the mean wait under twenty milliseconds, with at most one request in five waiting at all. At twelve books a second, about one server's worth of work, Erlang's formula from Part 45 asks for three servers, only thirty-two percent busy. At a thousand a second it asks for ninety, eighty-nine percent busy. Bigger pools run hotter for the same wait, because the spare capacity they need grows only like the square root of the load: two spare servers at the top of the table, ten at the bottom. Then add chapter six's spares for failures, and check the plan with an open-loop load test, or chapter nine's illusion will flatter it.

12Incidents and post-mortemsIndustry3 min

Incidents: what people do while a system is broken, and what they learn afterwards.

Here is an incident, as it typically unfolds. A change ships, and two minutes later errors begin. Google's site reliability book reports that about seventy percent of its outages came from changes to a live system. Chapter two's fast-burn alert pages the on-call engineer, who acknowledges, sees users affected, and declares an incident: now one named person is in charge, and customers are told. The first goal is not to understand the bug but to stop the harm, usually by undoing the change. Here the rollback ends it at minute thirty-four. Two intervals are tracked across incidents: the time to detect, and the time to mitigate. The root cause can wait for the next day, when nobody is in a hurry.

Afterwards comes the post-mortem: a written account of what happened and what will change. Google's template has a summary; the impact, in users, minutes and error budget; a timeline; contributing factors; what went well and what went wrong; and a section many teams find the most useful: where we got lucky. It is written without blame. Punish the person who typed the command, and the next person hides their mistake, and the organisation stops learning. John Allspaw, writing about Etsy's practice in 2012, asked not who made the mistake but why the action made sense at the time, with what they knew then. And every action item gets an owner and a date.

Why do incidents happen in systems built by careful people? James Reason, a psychologist who studied human error, offered a picture: the Swiss-cheese model. Every defence is a slice with holes in it, and the holes move. Harm gets through only when they line up. Take the S3 outage from the start of this part. The trigger was a mistyped input, but the tool also let too much capacity be removed, too quickly. The removed subsystems had not been fully restarted in the larger regions for years, so recovery was slow. And Amazon's status page could not at first show the problem, because it depended on S3. Four holes, lined up. Blaming the typist closes one.

In 1998 Richard Cook, a physician who studied safety in medicine, wrote a short paper called How Complex Systems Fail. Complex systems run in degraded mode, with something always broken somewhere. So catastrophe needs several failures at once: the Swiss cheese again. A single root cause is therefore a story told with hindsight, and hindsight makes every error look obvious. The people running a system are not its weak link but the adaptable part that creates its safety, mostly unseen. And every change, even a fix, introduces new forms of failure.

13Chaos engineeringIndustry3 min

Chaos engineering: breaking a system on purpose, before the world does it for you.

When Netflix moved its streaming service onto Amazon's cloud, its engineers accepted that any machine could vanish at any moment, and decided to make sure their services believed it too. They wrote Chaos Monkey, a program that picks instances at random and terminates them, in production. It runs during working hours, when the engineers who must respond are at their desks. A service that cannot lose one machine is found out on a Tuesday afternoon, not at three in the morning. In 2011 Netflix described a whole Simian Army. Latency Monkey added delays, and Chaos Gorilla took out an entire availability zone, so that traffic had to move to the others. Later, Chaos Kong drilled the evacuation of a whole region.

In 2016 Ali Basiri and his colleagues at Netflix set out the discipline as a scientific method. First, define the steady state: a measurable output that users feel, not an internal gauge. Netflix used the number of streams started per second. Second, state a hypothesis: that the steady state will be the same in an experiment group as in a control group. Third, inject the events the real world produces: machines crashing, networks partitioning, replies slowing, bad deployments, sudden load. Fourth, look for a difference between the two groups. If there is none, confidence grows. If there is one, you have found a weakness before your users did. And do it in production, because only production has production's traffic, and do it continuously, because the system changes every day.

Experimenting in production is responsible only if the damage is bounded, so the practitioners' published principles add a fifth rule: minimise the blast radius. Route a small slice of users, say one percent, to the experiment, and another one percent to a control group with no fault. Everyone else is untouched. Now crash one of the Job service's three replicas, under the naive client of chapter fourteen. The experiment group loses a third of its requests at once. An abort rule, written before the start, stops the experiment as soon as the group misses the objective for a minute. The dashed line is what it spared them. The experiment cost under a hundredth of a percent of the month's error budget. Unconfined, on all traffic for chapter fourteen's hour of faults, the same weakness costs thirteen percent. The hypothesis was refuted, cheaply.

14The Job service under faultsIndustry4 min

The Job's service, broken on purpose. The Job's counting service runs as three replicas, and clients spread requests over them. A chaos experiment starts with a hypothesis about the steady state, stated in the terms the users care about: ninety-nine point nine percent of requests answered correctly within three hundred milliseconds. Then, during one simulated hour, we break things. At minute ten the first counter crashes, and connections to it are refused at once. At minute twenty-five the second is cut off by a partition, so requests to it simply vanish. And at minute forty the third turns ten times slower, the gray failure that health checks often miss. We run the hour three times, with three clients: a naive one; one with a timeout and a single retry on another replica; and one that also ejects a replica after five failures in a row, and hedges a slow request after a hundred milliseconds.

Here is the share of requests that met the objective, minute by minute. The naive client loses a third of its requests whenever a replica is crashed or cut off, since one request in three goes to it, and about 24 percent while one is slow. Over the hour it keeps 90.5 percent. A timeout and one retry elsewhere recover almost everything: 99.91 percent, just above the objective. The misses are requests that wait out the timeout and then meet a slow reply. Ejection and hedging close the gap: the sick replica leaves the rotation within seconds, and the few slow replies are raced by a copy. Not one request in the hour missed. The price is in the next chart.

Count the hour against the month's error budget, a tenth of a percent of a month of requests. The naive client burned 13 percent of the whole month's budget in one hour of faults. Retrying used 0.13 percent, at the price of 11 percent more requests, because every timed-out or refused request was sent twice. Ejection cut the retries, since the broken replica stopped receiving traffic, so the best client was also the cheaper of the two: 1.2 percent extra. This is what an error budget is for: it turns reliability from a feeling into a number you can spend, and lets you price each defence.

The ledger gets row nineteen, and for once the row is not about being faster. With one of the service's forty-two workers ten times slow, the thirty books take about 0.71 seconds without hedging, since one of them usually lands on the slow worker, and 0.30 seconds with a hedge after two hundred and forty milliseconds. That is a shade faster than the healthy service without hedges, because a hedge also trims the ordinary tail, for about two extra requests in thirty. Reliability engineering rarely makes the good case faster. It keeps the bad case close to the good one, which is what users actually notice.

15Frontier: gray failure and metastabilityResearch1 min

Can we predict the failures that persist? The easy failures are the ones where something stops. The hard ones are gray: a replica whose health check answers OK, because the check is cheap and fast, while the users' real requests time out on a slow disk, a lossy link or a stuck thread. Peng Huang and colleagues named this in 2017, and called its cause differential observability: the failure detector and the application see different worlds. The remedy is to judge health the way users do, from the outcomes of real requests, as the Job's best client did when it ejected the slow replica.

Recap, problems, and where this comes backAll tracks3 min

What we built in this part. Availability that multiplies in series and is rescued in parallel, until a common cause breaks the independence it relies on. An error budget, and alerts derived from it that page quickly for real trouble and stay quiet for blips. Retries that can hold a system in collapse long after the trigger, and the backoff, jitter and budgets that prevent it. Breakers, bulkheads, shedding, ejection and hedges. Metrics, sketches, traces and profiles that do not lie, and load generators that do. And the Job's own service, broken on purpose, kept within its objective. One idea runs through it: reliability is not hoped for, it is measured and paid for.

Where this comes back. Part 51 renders frames against a sixteen-millisecond budget, an objective of its own. Part 54 proves protocols and configurations correct before they ship. Part 55 asks whether the software we deploy can be trusted at all. Part 59 returns to the theory of distributed algorithms and what they cannot do. And Part 60 builds hardware for one job, where every watt is budgeted.

In practice. Define objectives in the terms your users feel, and an error budget the whole team agrees to spend. Alert on how fast the budget is burning, over a long and a short window, rather than on every symptom. Retry with timeouts, jitter and a budget, and never at every layer at once. Measure latency with histograms or sketches, from the time a request should have been sent. And learn from failure: blameless post-mortems, and chaos experiments that start with a small blast radius.

Six problems, with full solutions in the part's notes. Pause on any of them. The fifth is a build problem: add a circuit breaker and a retry budget to a client, and measure what they do through a drop in capacity. The last, marked with a star, is a research problem: derive, rather than simulate, the triggers from which a retrying server cannot recover.

Next time, Part 51, which opens Act Ten, Horizons and Trust: light and pixels. A picture is millions of samples of light. Projecting triangles onto a screen is linear algebra plus one division; getting the samples right is Nyquist again; and the physics of light is one integral equation, which our own path tracer solves one bounced ray at a time.

The books and papers this part follows are on screen and in the notes. Thank you for watching.

Where it goes next. Part 51 renders frames against a sixteen-millisecond budget, an objective of its own. Part 54 proves protocols and configurations correct before they ship, and Part 55 asks whether deployed software can be trusted at all. Part 59 returns to the theory of distributed algorithms and what they cannot do.

Key results

The part's results in one place, for revision.

Series and parallel\(\displaystyle A_{\text{series}}=\prod_i A_i,\qquad\allowbreak A_{\text{parallel}}=1-\prod_i(1-A_i)\)
Up time\(\displaystyle A=\frac{\text{MTBF}}{\text{MTBF}+\text{MTTR}}\)
A shared cause\(\displaystyle A=(1-cq)\bigl(1-q'^{\,3}\bigr),\qquad\allowbreak q'=\frac{(1-c)\,q}{1-cq}\)
Burn rate\(\displaystyle b=\frac{\text{error rate}}{1-\text{SLO}},\qquad\allowbreak \text{page }\allowbreak \text{at } b=f\cdot\frac{720\ \text{h}}{w}\)
DDSketch\(\displaystyle \gamma=\frac{1+\alpha}{1-\alpha},\quad\allowbreak \hat x=\frac{2\gamma^{i}}{\gamma+1},\quad\allowbreak |\hat x-x|\le\alpha x\)
A profile's error\(\displaystyle \operatorname{se}(\hat p)=\sqrt{\hat p(1-\hat p)/n}\)

Try it

Lab 50 · Availability, a retry storm, and a sketch that keeps its promise

Compare the series, parallel and k-of-n availability formulas with a Monte Carlo of independent failures, run the series' overloaded server with and without retries after a ten-second loss of half its capacity, and check DDSketch's relative-error guarantee at five quantiles against a sample of 1,000.

Figure produced by Lab 50: Availability, a retry storm, and a sketch that keeps its promise
Produced by the lab below, seed 0, in 0.4 s.
python -m videos.cs.labs 50 needs numpy, scipy, matplotlib · download lab50.py · source on GitHub
10 parts in series, parts up 99%           formula 90.43821% (1.0 nines)   simulated 90.50200%
2 parts in parallel, parts up 99%          formula 99.99000% (4.0 nines)   simulated 99.99250%
10 needed of 11 (N + 1), parts up 99%      formula 99.48203% (2.3 nines)   simulated 99.47125%
10 needed of 12 (N + 2), parts up 99%      formula 99.97944% (3.7 nines)   simulated 99.97925%
a majority of 5, parts up 99%              formula 99.99901% (5.0 nines)   simulated 99.99950%
up 720 h, repair 2 h, 200 simulated years  99.727% up   MTBF/(MTBF+MTTR) = 99.723%
overload, no retries                       answered in time 6,504; peak load sent 98/s; recovers 11 s after the trigger
overload, three immediate retries          answered in time 2,567; peak load sent 350/s; recovers never
overload, a 10% retry budget               answered in time 5,956; peak load sent 106/s; recovers 19 s after the trigger
DDSketch, alpha 1%, 280 buckets            relative error at p50, p90, p99, p99.9, p99.99: 0.91%, 0.41%, 0.97%, 0.53%, 0.51%
a sample of 1,000 values                   relative error: 0.5%, 2.2%, 3.0%, 25.8%, 78.2%

Independent parts obey the formulas to the last digit a simulation can see; the same ten-second trigger is survived without retries and never with them; and a sketch that bounds relative error keeps the tail that a sample loses.
The code (96 lines; it asserts its own result)
"""Lab 50: check availability arithmetic by simulation, tip a server into a retry storm, and test a quantile sketch's guarantee."""

from videos.coursekit import labs  # noqa: I001  (must stay first: it lets explainer.cs import without manim)

import numpy as np

from explainer.cs.ops import observe, overload, reliability

TITLE = "Availability, a retry storm, and a sketch that keeps its promise"
GOAL = ("Compare the series, parallel and k-of-n availability formulas with a Monte Carlo of independent failures, "
        "run the series' overloaded server with and without retries after a ten-second loss of half its capacity, "
        "and check DDSketch's relative-error guarantee at five quantiles against a sample of 1,000.")
TASKS = [
    "Change the trigger from (30, 40, 0.5) to (30, 35, 0.7) and to (30, 32, 0.5). Which of them does the retrying server survive, and what decides it?",
    "Replace the policy 'budget' by 'shed' and by 'breaker'. Which answers the most requests in time over the run, and which is never stuck?",
    "Build the sketch with alpha = 0.05 instead of 0.01. How many buckets does it need now, and does the measured relative error still stay under alpha at every quantile?",
]

A = 0.99
QS = (0.5, 0.9, 0.99, 0.999, 0.9999)


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()

    # 1. availability: formulas against independent coin flips
    trials = 400_000
    up = rng.random((trials, 13)) < A                              # thirteen parts, each up 99% of the time
    cases = [
        ("10 parts in series", ("series", [A] * 10), up[:, :10].all(axis=1)),
        ("2 parts in parallel", ("parallel", [A] * 2), up[:, :2].any(axis=1)),
        ("10 needed of 11 (N + 1)", ("kofn", 10, [A] * 11), up[:, :11].sum(axis=1) >= 10),
        ("10 needed of 12 (N + 2)", ("kofn", 10, [A] * 12), up[:, :12].sum(axis=1) >= 10),
        ("a majority of 5", ("kofn", 3, [A] * 5), up[:, :5].sum(axis=1) >= 3),
    ]
    for name, tree, sim in cases:
        formula, measured = reliability.evaluate(tree), float(sim.mean())
        sd = np.sqrt(max(formula * (1 - formula), 1e-9) / trials)
        assert abs(measured - formula) < 5 * sd + 2e-5, name
        lab.row(f"{name}, parts up 99%", f"formula {formula:.5%} ({reliability.nines(formula):.1f} nines)   "
                                         f"simulated {measured:.5%}")
    ren = reliability.renewal(seed=seed)
    assert abs(ren["measured"] - ren["formula"]) < 5e-4, "time up is MTBF / (MTBF + MTTR)"
    lab.row("up 720 h, repair 2 h, 200 simulated years", f"{ren['measured']:.3%} up   MTBF/(MTBF+MTTR) = {ren['formula']:.3%}")

    # 2. a metastable failure: the same trigger, three client policies
    runs = {p: overload.overload(p, seconds=100, seed=seed) for p in ("none", "retries", "budget")}
    late = {p: float(np.mean(r["goodput"][70:])) for p, r in runs.items()}
    assert runs["none"]["recovered_s"] is not None and late["none"] > 70, "without retries the server recovers"
    assert runs["retries"]["recovered_s"] is None and late["retries"] < 5, "with retries the overload outlasts its cause"
    assert max(runs["retries"]["offered"]) > 3 * runs["retries"]["base"], "retries multiply the load"
    assert runs["budget"]["recovered_s"] is not None and late["budget"] > 70, "a retry budget lets it recover"
    for p, label in (("none", "no retries"), ("retries", "three immediate retries"), ("budget", "a 10% retry budget")):
        r = runs[p]
        rec = "never" if r["recovered_s"] is None else f"{r['recovered_s']:.0f} s after the trigger"
        lab.row(f"overload, {label}", f"answered in time {sum(r['goodput']):,.0f}; peak load sent {max(r['offered']):.0f}/s; "
                                      f"recovers {rec}")

    # 3. DDSketch: every quantile within a relative error alpha, where a sample of 1,000 loses the tail
    x = observe.latencies(40_000, seed)
    sketch = observe.DDSketch(0.01)
    for v in x:
        sketch.add(float(v))
    sample = np.sort(rng.choice(x, 1000, replace=False))
    true = [float(np.quantile(x, q, method="lower")) for q in QS]
    err_dd = [abs(sketch.quantile(q) - t) / t for q, t in zip(QS, true)]
    err_s = [abs(float(np.quantile(sample, q)) - t) / t for q, t in zip(QS, true)]
    assert max(err_dd) <= 0.01 + 1e-9, "DDSketch's guarantee: relative error at most alpha, at every quantile"
    assert max(err_s) > 0.05, "a sample of 1,000 cannot see the far tail"
    lab.row(f"DDSketch, alpha 1%, {sketch.buckets} buckets", "relative error at p50, p90, p99, p99.9, p99.99: "
            + ", ".join(f"{e:.2%}" for e in err_dd))
    lab.row("a sample of 1,000 values", "relative error: " + ", ".join(f"{e:.1%}" for e in err_s))
    lab.note = ("Independent parts obey the formulas to the last digit a simulation can see; the same ten-second "
                "trigger is survived without retries and never with them; and a sketch that bounds relative error "
                "keeps the tail that a sample loses.")

    fig, ax = labs.figure(2, size=(11, 4.3))
    t = np.arange(100)
    ax[0].axvspan(30, 40, color=labs.RED, alpha=0.15, label="capacity halved")
    for p, color, label in (("none", labs.BLUE, "no retries"), ("budget", labs.GREEN, "10% retry budget"),
                            ("retries", labs.GOLD, "three immediate retries")):
        ax[0].plot(t, runs[p]["goodput"], color=color, label=label)
    ax[0].plot(t, runs["retries"]["offered"], color=labs.GOLD, ls=":", lw=1.2, label="load sent, with retries")
    ax[0].set(title="Requests answered in time, each second", xlabel="seconds", ylabel="requests a second")
    ax[0].legend(loc="center right", fontsize=8)
    pos = np.arange(len(QS))
    ax[1].bar(pos - 0.2, [max(e, 1e-5) for e in err_dd], 0.4, color=labs.BLUE, label="DDSketch (alpha = 1%)")
    ax[1].bar(pos + 0.2, [max(e, 1e-5) for e in err_s], 0.4, color=labs.ORANGE, label="sample of 1,000")
    ax[1].axhline(0.01, color=labs.RED, ls="--", lw=1.2, label="the guarantee, 1%")
    ax[1].set_yscale("log")
    ax[1].set_xticks(pos, ["p50", "p90", "p99", "p99.9", "p99.99"])
    ax[1].set(title="Relative error of each latency quantile", ylabel="relative error")
    ax[1].legend(loc="upper left")
    lab.fig = fig
    return lab

Now change it

  1. Change the trigger from (30, 40, 0.5) to (30, 35, 0.7) and to (30, 32, 0.5). Which of them does the retrying server survive, and what decides it?
  2. Replace the policy 'budget' by 'shed' and by 'breaker'. Which answers the most requests in time over the run, and which is never stuck?
  3. Build the sketch with alpha = 0.05 instead of 0.01. How many buckets does it need now, and does the measured relative error still stay under alpha at every quantile?

Problems, with solutions

Try each problem before opening its solution.

  1. Availability. A request needs five services of 99.95% each, and each has two replicas. What is its availability, and what if 10% of each service's downtime is common-mode?

    Solution

    Each replica is down q = 0.0005 of the time. With independent replicas a service is down only when both are, q² = 2.5 × 10⁻⁷, so it is up 1 − q², and five services in series give (1 − q²)⁵ ≈ 1 − 5q² = 1 − 1.25 × 10⁻⁶: 99.99988%, 5.9 nines, about 0.66 minutes (39 s) a year. (Without the replicas, 0.9995⁵ = 99.750%, 2.6 nines, 21.9 hours a year.) Now let a share c = 0.1 of each replica's downtime be a common event that takes both replicas down, as in chapter 1: the common part is down cq = 5 × 10⁻⁵ of the time, and to keep each replica's own downtime at q the independent part is down q′ = (1 − c)q/(1 − cq) = 4.5002 × 10⁻⁴. A service is up when the common cause is absent and not both independent parts are down: (1 − cq)(1 − q′²) = 1 − 5.020 × 10⁻⁵, 4.3 nines. Five in series: (1 − 5.020 × 10⁻⁵)⁵ = 99.9749%, 3.6 nines, 132 minutes (2.2 hours) a year, two hundred times the independent figure. To first order the unavailability is 5(cq + q′²) ≈ 5cq: the common-mode share acts as a part in series, each service is capped at 1 − cq, and the replicas' squared term no longer matters.

  2. Burn-rate threshold. Derive the burn-rate threshold that pages when 5% of a 30-day budget is spent in 6 hours, and the time to detect a burn rate of 10.

    Solution

    With N requests in the month, the budget is (1 − SLO)N errors. A burn rate b means an error rate b(1 − SLO), so a window of w hours, holding N w/720 requests, spends b(1 − SLO)N w/720, a share b w/720 of the budget. Setting that equal to f gives b = f × 720 h/w = 0.05 × 720/6 = 6: at a 99.9% objective, an error rate of 0.6% over six hours. A burn of 10 starting from a clean window raises the 6-hour average burn as 10t/6 after t hours, which reaches 6 at t = 6 × 6/10 = 3.6 hours (3.58 with chapter 2's background burn of 0.1). In general the long window detects a burn b ≥ b* after w b*/b, when the budget spent is b(w b*/b)/720 = f, the same 5% whatever b is: a faster burn is caught sooner but not more cheaply. The multiwindow rule's 30-minute window reaches 6 after 18 minutes, so the 6-hour window governs. The 1-hour threshold of 14.4 never fires on a burn of 10, which would exhaust the budget in 72 hours. Check against chapter 2: the degradation burned at 12 and was paged after 179 minutes, against 6 × 6/12 = 3 hours (2.97 with the background).

  3. Retry amplification. Show that with L layers each retrying r times, a failing backend sees (r + 1)ᴸ attempts, and that a 10% retry budget bounds it by 1.1ᴸ.

    Solution

    Number the layers 1 to L from the user, with layer L calling the backend, and let aₖ be the attempts layer k makes per user action. While the backend fails, every attempt fails all the way up, so each request a layer receives becomes r + 1 attempts downstream: a₁ = r + 1 and aₖ = (r + 1)aₖ₋₁, and by induction the backend sees a_L = (r + 1)ᴸ (64 for chapter 4's three layers of four tries; 4¹⁰ ≈ 10⁶ for ten). A retry budget lets a client add retries worth at most a share β = 0.1 of its first attempts, as a token bucket earning β tokens per first attempt and holding at most B. A layer's first attempts are the requests it received, nₖ₋₁ (retries from above arrive as new requests), so over any period nₖ ≤ (1 + β)nₖ₋₁ + B, and by induction the backend sees at most 1.1ᴸn₀ + B(1.1ᴸ − 1)/0.1 attempts for n₀ user actions: 1.1ᴸ per action in the long run (1.331 for three layers, 2.59 for ten), plus a burst bounded by the buckets. The bound is multiplicative per layer, which is why retrying at one layer only, as chapter 4 advises, does better still: 1.1.

  4. DDSketch. Prove DDSketch's guarantee: every value in bucket i is within relative error α of 2γⁱ/(γ + 1).

    Solution

    With γ = (1 + α)/(1 − α), a value x goes to bucket i = ⌈log_γ x⌉, so γⁱ⁻¹ < x ≤ γⁱ. Then x̂/x = 2γⁱ/((γ + 1)x) lies in [2γⁱ/((γ + 1)γⁱ), 2γⁱ/((γ + 1)γⁱ⁻¹)) = [2/(γ + 1), 2γ/(γ + 1)). Since γ + 1 = 2/(1 − α), 2/(γ + 1) = 1 − α and 2γ/(γ + 1) = γ(1 − α) = 1 + α, so 1 − α ≤ x̂/x < 1 + α, that is, |x̂ − x| ≤ αx. The estimate is the harmonic mean of the bucket's ends, the one point equally far from both in relative terms. For quantiles: bucket counts are exact, so the bucket in which the cumulative count first passes the rank holds the true q-quantile, and the answer is within α of it. Merging sketches with the same α adds counts bucket by bucket, so the merged sketch is exactly the sketch of the union and keeps the guarantee, which is why chapter 7's merged p99 (268 ms) is right where the average of p99s (230 ms) is not. Values from m to M need at most about log_γ(M/m) ≈ ln(M/m)/(2α) buckets: about 509 for 4 ms to 104 s at α = 1%, of which our latencies fill 332.

  5. Build. Add a circuit breaker and a retry budget to a client, and measure goodput through a capacity drop.

    Solution

    Solution notes. Start from overload in explainer/cs/ops/overload.py, which already has a "breaker" and a "budget" policy, each tested with policy == .... Let a policy name a set of mechanisms (for example "breaker+budget", tested by membership), so that a timed-out request is retried only if the breaker is closed and the client holds a token (0.1 earned per first attempt, at most 10). The simulator's breaker is one state shared by all clients, open for 5 s when over half of the last second's attempts failed, with 5% of calls passing as probes; a fuller answer gives each of several clients its own three-state machine (closed: count failures over a sliding window with a minimum number of calls; open: fail fast for a cool-down; half-open: admit a few probes, close if they succeed, reopen if not). Measure goodput per second and in total, offered load, and recovered_s, the time after the trigger until goodput is back to 90% of demand, on chapter three's trigger and over the grid of trigger_sizes. A quick version of the combined policy answers 9,098 requests in time on chapter three's trigger (breakers alone 9,110, the budget alone 7,530): here the breaker does the work. On a deeper, longer drop, to 30% for 20 s, the budget alone did not recover within the run (2,496 answered), because the server still serves, first come first served, a backlog of requests whose clients have given up and drains it only at the headroom the budget leaves, while the combined client answered 8,133 and recovered one second after the drop ended. Tests to add: the combined policy recovers on every cell of the grid; while a breaker is open the offered load stays near the probe rate; retries never exceed 10% of first attempts plus the bucket.

  6. ★ Research. The exact set of triggers a retrying server cannot recover from.

    Discussion. Open. For a server of capacity μ, users sending λ < μ, a client timeout τ and r retries, two steady states can coexist: the good one, with a short queue and no timeouts, and a bad one in which every request waits past τ, so each user request becomes r + 1 attempts and the offered load is λ(r + 1), self-sustaining when λ(r + 1) > μ (chapter 3: 80 × 4 = 320 > 100). The trigger set is the set of perturbations, here a capacity fraction f for a duration D, that carry the state out of the good state's basin of attraction. What makes it hard is the state: a FCFS queue with deadlines is described by the ages of everything waiting, an infinite-dimensional, delayed and stochastic system, and the outcome near the boundary depends on more than the backlog. Our grid shows this: a drop to 70% for 10 s and a drop to 60% for 5 s both leave a deficit of about 100 requests, yet the first collapses and the second recovers, most likely because the first spends longer with waits past the timeout, generating retries. Near the boundary the outcome is random, so the exact set is really a probability of collapse as a function of (f, D). A good partial answer would take a fluid or diffusion model with an explicit treatment of timeouts and abandoned work, prove the bistability condition, and give inner and outer bounds on the collapse region (states from which recovery is certain, and states from which it is impossible) that are close to each other and agree with trigger_sizes over a range of λ, μ, τ and r; a closed form for the boundary in the deterministic limit would already be new.

Notes and sources

Glossary

  • availability, nines, downtime budget — the fraction of time a service works; −log₁₀ of the unavailability; the downtime a period allows.
  • series and parallel composition, k of n — up only if every part is up; down only if every part is down; up while at least k parts are.
  • MTBF, MTTR, renewal process — mean time between failures and to repair; alternating up and down times.
  • common-mode (correlated) failure — one cause that takes replicas down together; a part in series with them.
  • SLI, SLO, SLA — a measured ratio of good events; a target for it over a window; a contract with consequences.
  • error budget, error-budget policy — the unreliability the objective allows; what a team does when it is spent.
  • burn rate, multiwindow multi-burn-rate alert — the error rate over the rate the objective allows; a page when a long and a short window both burn fast.
  • fail-stop, crash, omission, timing and arbitrary (Byzantine) failure — fault models, each containing the last.
  • gray failure, differential observability — partial failure seen differently by the failure detector and by users.
  • cascading failure, metastable failure, trigger, sustaining effect — survivors overloaded in turn; a bad state that outlasts its trigger because the failure itself feeds it.
  • timeout, deadline propagation, idempotency — a bounded wait; passing the caller's deadline downstream; safe to repeat.
  • exponential backoff, full, equal and decorrelated jitter, retry budget — growing waits; randomised waits; a cap on retries as a share of first attempts.
  • hedged request, tail latency — a second copy sent after a short delay, the first answer winning; the slow percentiles.
  • circuit breaker (closed, open, half-open), bulkhead, load shedding, criticality — failing fast for a dependency in trouble; separate pools; refusing work early; which requests to refuse first.
  • graceful degradation, backpressure — serving less instead of failing; a full queue slowing its producer.
  • N + k, active–passive, active–active, failover, regional evacuation — spare capacity; a standby against copies that all serve; taking over; moving a region's traffic away.
  • recovery point, recovery time — how much recent data a failover can lose; how long it takes.
  • counter, gauge, histogram, cardinality — a value that only grows; one that goes up and down; counts in buckets; the number of distinct label combinations.
  • quantile sketch, DDSketch, log-linear (HDR) histogram, relative error — small mergeable summaries of a distribution; an error proportional to the value.
  • structured log, trace, span, trace context, critical path — a log of named fields; the spans of one request; the ids that link them; the chain of work the end waited for.
  • head and tail sampling — keeping a trace by a coin at its start, or by its outcome at its end.
  • coordinated omission, open and closed load — a load generator's pauses lining up with the server's; arrivals regardless of the system, or users who wait.
  • sampling profiler, folded stacks, flame graph, off-CPU time — periodic samples of where a program is; counts per stack; frames as wide as their share; time spent waiting.
  • USE, RED, golden signals — utilisation, saturation and errors per resource; rate, errors and duration per service; latency, traffic, errors and saturation.
  • capacity planning, change-point detection — servers for a forecast load; finding where a series' mean shifts.
  • incident, incident commander, post-mortem, blameless culture — a broken service and the people restoring it; the person in charge; the written account afterwards; asking why an action made sense.
  • Swiss-cheese model — harm getting through only where the holes in every defence line up.
  • chaos engineering, steady-state hypothesis, blast radius, fault injection — experiments that break a system on purpose; what should not change; how much can be harmed; crashes, partitions and delays introduced deliberately.

Sources

  • B. Beyer, C. Jones, J. Petoff and N. R. Murphy (eds.), Site Reliability Engineering (2016); B. Beyer, N. R. Murphy, D. K. Rensin, K. Kawahara and S. Thorne (eds.), The Site Reliability Workbook (2018), chapter 5, "Alerting on SLOs".
  • M. Nygard, Release It! (2007; 2nd ed. 2018); B. Gregg, Systems Performance (2nd ed., 2020) and BPF Performance Tools (2019); R. Jain, The Art of Computer Systems Performance Analysis (1991); M. Harchol-Balter, Performance Modeling and Design of Computer Systems (2013).
  • Amazon Web Services, "Summary of the Amazon S3 service disruption in the Northern Virginia (US-EAST-1) region" (2017); Cloudflare, "Details of the Cloudflare outage on July 2, 2019" (2019); CrowdStrike, preliminary post-incident review and root cause analysis of the 19 July 2024 channel file update (2024).
  • C. E. Shannon, "A symbolic analysis of relay and switching circuits", Trans. AIEE 1938; E. F. Moore and C. E. Shannon, "Reliable circuits using less reliable relays", J. Franklin Institute 1956; J. Gray, "Why do computers stop and what can be done about it?", Tandem Technical Report 85.7 (1985).
  • R. D. Schlichting and F. B. Schneider, "Fail-stop processors: an approach to designing fault-tolerant computing systems", ACM TOCS 1983; P. Huang, C. Guo, L. Zhou, J. R. Lorch, Y. Dang, M. Chintalapati and R. Yao, "Gray failure: the Achilles' heel of cloud-scale systems", HotOS 2017.
  • N. Bronson, A. Aghayev, A. Charapko and T. Zhu, "Metastable failures in distributed systems", HotOS 2021; L. Huang, M. Magnusson, A. B. Muralikrishna, S. Estyak, R. Isaacs, A. Aghayev, T. Zhu and A. Charapko, "Metastable failures in the wild", OSDI 2022.
  • R. M. Metcalfe and D. R. Boggs, "Ethernet: distributed packet switching for local computer networks", Comm. ACM 1976; M. Brooker, "Exponential backoff and jitter", AWS Architecture Blog (2015); J. Dean and L. A. Barroso, "The tail at scale", Comm. ACM 2013; B. Maurer, "Fail at scale", ACM Queue 2015; K. Nichols and V. Jacobson, "Controlling queue delay", ACM Queue 2012.
  • D. Ongaro and J. Ousterhout, "In search of an understandable consensus algorithm", USENIX ATC 2014.
  • C. Masson, J. E. Rim and H. K. Lee, "DDSketch: a fast and fully-mergeable quantile sketch with relative-error guarantees", PVLDB 2019; Z. Karnin, K. Lang and E. Liberty, "Optimal quantile approximation in streams", FOCS 2016; G. Tene, HdrHistogram and wrk2.
  • B. H. Sigelman, L. A. Barroso, M. Burrows, P. Stephenson, M. Plakal, D. Beaver, S. Jaspan and C. Shanbhag, "Dapper, a large-scale distributed systems tracing infrastructure", Google Technical Report (2010); W3C, Trace Context; the OpenTelemetry project (2019).
  • B. Schroeder, A. Wierman and M. Harchol-Balter, "Open versus closed: a cautionary tale", NSDI 2006.
  • B. Gregg, "The flame graph", Comm. ACM 2016; S. Williams, A. Waterman and D. Patterson, "Roofline: an insightful visual performance model for multicore architectures", Comm. ACM 2009; A. K. Erlang, "Solution of some problems in the theory of probabilities of significance in automatic telephone exchanges" (1917); D. Daly, W. Brown, H. Ingo, J. O'Leary and D. Bradford, "The use of change point detection to identify software performance regressions in a continuous integration system", ICPE 2020.
  • J. Allspaw, "Blameless postmortems and a just culture", Code as Craft (Etsy, 2012); J. Reason, Human Error (1990); R. I. Cook, "How complex systems fail" (1998).
  • A. Basiri, N. Behnam, R. de Rooij, L. Hochstein, L. Kosewski, J. Reynolds and C. Rosenthal, "Chaos engineering", IEEE Software 2016; Netflix Technology Blog, "The Netflix Simian Army" (2011).
  • T. Ahmed, S. Ghosh, C. Bansal, T. Zimmermann, X. Zhang and S. Rajmohan, "Recommending root-cause and mitigation steps for cloud incidents using large language models", ICSE 2023.
About this partfrom its README

Part 50 of a sixty-one-part course in computer science (see the series plan and the syllabus), the sixth and last part of Act IX, Systems at Scale. A system is only as good as its worst hour, and reliability engineering turns that into arithmetic: availability composes in series and in parallel, an error budget makes unreliability a resource to spend, retries can hold a server in collapse long after its trigger has gone, and metrics, traces and profiles tell you what actually happened, provided they do not lie. The part ends by breaking the Job's own service on purpose and pricing each defence against the month's error budget.

The instruments are in explainer/cs/ops/ (tested in tests/test_cs50_ops.py), with Part 45's Erlang C (explainer/cs/cloud/control.py), Part 46's KLL (explainer/cs/data/columnar.py), Part 38's Raft cluster (explainer/cs/dist/raft.py) and the Pebble emulator:

  • reliability.py: nines as downtime per year, 30-day month and week; evaluate, availability of a tree of series, parallel and k-of-n parts (k of n exactly, by a dynamic program over parts of different availability); the two laws on parts of 99%; a request path (DNS, load balancers, app servers, database) replicated against built from one of each; an alternating renewal process (exponential up times of mean 720 h, repairs of mean 2 h, 200 years) against MTBF/(MTBF + MTTR), and the two levers; common-mode failure, three replicas of 99.9% with a share c of each one's downtime shared, by Monte Carlo (2,000,000 trials) against the exact (1 − cq)(1 − q′³); a Raft majority; N + k.
  • slo.py: a synthetic 30-day month (Poisson requests around 1,000 a minute, binomial errors, background rate 0.01%) with six incidents (three blips, an outage, a degradation, a slow leak); the budget spent minute by minute and by incident; burn-rate thresholds b = f × 720 h / w; five alerting rules from The Site Reliability Workbook scored for detection time, reset time, missed significant incidents (at least 2% of the budget) and needless pages.
  • overload.py: clients contending for one record under optimistic concurrency (a write fails if another starts within one unit of it) with five backoff strategies; a server of capacity 100 a second, simulated in 10 ms steps, with users sending 80 a second, a 1 s client timeout, three retries and a trigger that halves capacity from 30 s to 40 s, under six policies (no retries, immediate retries, backoff with full jitter, a 10% retry budget as a token bucket, server-side shedding of requests that have waited over 0.5 s, client circuit breakers); the trigger sizes that tip it into the bad state; one thread pool against two bulkheads; hedged requests.
  • observe.py: DDSketch (Masson, Rim and Lee) and an HDR-style log-linear histogram (128 sub-buckets per power of two) against KLL and a sample of 1,000, on 200,000 latencies (lognormal around 20 ms, 5% cache misses around 120 ms, a 0.5% Pareto tail); ten servers, one four times slower, for the average of p99s against the fleet's p99; synthetic traces of nine spans with parallel children, their critical path, and head against tail sampling; coordinated omission, a closed-loop generator against the latencies from intended send times; exact mean-value analysis of a closed system against M/M/1 at the same throughput; change-point detection with a permutation test.
  • profile.py: a sampling profiler of Pebble running version zero of the Job (every 997th instruction's program counter mapped to its label, the labels to routines, the routines to stacks), checked against an exact count of every instruction with binomial standard errors; flame-graph rectangles from folded stacks; a CPU-time timer signal (SIGPROF, 1,000 Hz) sampling the emulator's own Python stack.
  • chaos.py: the Job's counting service as three replicas under a crash, a partition and a slow replica, with three client configurations; Part 38's five-node Raft cluster under a script of crashes and a partition, with its safety checker.

compute.py also plans the Job service's capacity by Erlang C, and appends ledger row 19 to Part 49's ledger.

Chapter notes
  • Hook. Three post-mortems, from the companies' own public reports: Amazon S3 on 28 February 2017 (one mistyped input to a tool removed far more capacity than meant, including two subsystems the region depended on), Cloudflare on 2 July 2019 (a firewall rule's regular expression backtracking catastrophically, Part 12, pushed everywhere at once) and CrowdStrike on 19 July 2024 (a content update that made a kernel driver read out of bounds, crashing about 8.5 million Windows machines by Microsoft's estimate). Each a routine change pushed too far, too fast. A year has 525,960 minutes: 99% allows 3.7 days of downtime, 99.9% 8.8 hours, 99.99% 53 minutes (4.3 a month), 99.999% 5 minutes (0.4 a month).
  • 1. Availability arithmetic. Nines = −log₁₀(1 − A); downtime = (1 − A) × T: two nines 3.7 days a year, three nines 43.2 minutes a 30-day month, four nines 4.3 minutes a month or 1.0 a week, five nines 5.3 minutes a year. Series and parallel as Part 3's switch circuits: 2, 10 and 50 parts of 99% in series give 98.0%, 90.4% and 60.5%; 2 and 3 in parallel give 99.99% and 99.9999%. A request path of four replicated stages (four name servers, two load balancers at 99.9%, three app servers at 99%, a database pair at 99.9%; illustrative) is 99.9997%, 5.5 nines, 1.6 minutes a year; one of each is 98.70%, 1.9 nines, 4.7 days. One simulated server's year (9 failures); 720/(720 + 2) = 99.72%, and 200 simulated years give 99.7%. Halving failures and halving repair time are worth exactly the same (24.3 hours down a year to 12.2; 2.6 nines to 2.9); repairing in 10 minutes gives 2.0 hours and 3.6 nines. Correlated failure: three replicas of 99.9% promise 9.0 nines, but with 1%, 5%, 10% and 30% of each one's downtime common they give 5.0, 4.3, 4.0 and 3.5; the shared cause is a switch in series, A = (1 − cq)(1 − q′³).
  • 2. SLOs and error budgets. Indicator, objective, agreement (99.9% over 30 days; an SLA of 99.5%, illustrative); this month's SLI 99.945%. The budget, one bad request in a thousand or 43.2 minutes of total outage, draining over the synthetic month: the outage (25 minutes at 25%) takes 14.5%, the degradation (6 hours at 1.2%) 10.1%, the slow leak (3 days at 0.2%) 18.8%, the three blips 1.6% and background errors 9.9%: 54.9% spent. Burn rate b = error rate/(1 − SLO): the budget lasts 30 days/b (15 days at 2, 5 days at 6, 50 hours at 14.4); to page at a share f within a window w, b = f × 720 h/w: 2% in 1 hour gives 14.4 (1.44% errors, page), 5% in 6 hours 6.0 (0.60%, page), 10% in 3 days 1.0 (0.10%, ticket). Five rules scored on the month: errors above 0.1% over 10 minutes catches everything at once but pages 20 times, 3 of them needlessly; over 36 hours it is quiet for the blips but takes 2.7 hours for the degradation and 16.6 for the leak, and keeps paging 35.9 hours after the outage; a single burn of 14.4 over an hour pages for the outage in 3 minutes and misses the degradation and the leak; two burn rates with a ticket catch all three significant incidents (outage 3 minutes, degradation 3.0 hours, leak 34.2 hours by ticket), but the outage alert lasts 5.9 hours after it ends; the multiwindow, multi-burn-rate rule (a short window a twelfth as long must agree) detects the same and stops 29 minutes after the outage.
  • 3. How systems fail: gray, cascading, metastable. Fault models nested from fail-stop (Schlichting and Schneider 1983) through crash, omission and timing to arbitrary, and gray failure outside the ladder (chapter 15). A cascade (illustrative): five servers at 72% each, u = u₀ n/(n − k), one lost puts four at 90%, a second puts three at 120%, and the rest go. A metastable failure simulated: without retries the server is answering again 11 s after the trigger ends; with three immediate retries the sent load climbs to about 320 a second, four times what users send, and requests answered in time stay at zero for the remaining 80 s. The loop (a long queue, timeouts, retries, load above capacity) and its states, stable, vulnerable, metastable (Bronson et al. 2021; Huang et al. 2022).
  • 4. Timeouts, retries, backoff and jitter. Timeouts a little above the dependency's p99.9, deadlines passed downstream; three layers trying four times each turn one tap into 64 attempts, so retry at one layer, and only idempotent requests (Part 43). Twenty clients on one record: no backoff makes 29,279 attempts by t = 3,000 and none finishes; exponential backoff 240 and none finishes; full jitter finishes all twenty by t = 318 after 175 attempts. Brooker's comparison with 100 clients (base 1, cap 1,000, ten runs): no backoff 975,654 calls and exponential 2,900, neither ever done by t = 20,000; full jitter 1,071 calls, all done at 1,624; equal jitter 1,059 at 2,124; decorrelated jitter 1,789 at 1,864 (with 50 clients decorrelated finishes first, 684 against 807). Back on chapter three's server, backoff with full jitter still sends about 320 a second and answers none; a 10% retry budget keeps the load near 80 and answers again 19 s after the trigger. Hedged requests (Dean and Barroso 2013): replies exponential with mean 5 ms but 2% hitting a 200 ms pause; p99 203 ms unhedged, 53 ms hedging at 50 ms for 2.0% more requests, 25 ms at 20 ms for 3.7% (19 ms at 12 ms for 10.8%).
  • 5. Breakers, bulkheads and load shedding. The circuit breaker's three states (Nygard 2007); ours opens for 5 s when over half of the last second's calls failed, letting 5% through as probes. On chapter three's trigger the breakers are open from 32 s to 38 s, and 9,110 requests are answered in time against 2,567. Shedding requests that have waited over 0.5 s (a rejection costs a fiftieth of an answer): at most 226 sent a second, 46 to 49 answered a second through the trigger, normal at once after; CoDel's idea (Part 37) in services, and Maurer's account of Facebook switching to newest-first. The six policies over 120 s (users send 80 a second, about 9,600 in all): no retries 8,078 (recovers after 11 s), immediate retries 2,567 and with backoff 2,567 (never recover), the retry budget 7,530 (after 19 s), shedding 9,355 and breakers 9,110 (never stuck). Bulkheads: 30 threads serving A at 40 a second and B at 20; when B turns slow (2 s a call instead of 50 ms, from 20 s to 40 s) the shared pool lets only 28% of calls to healthy A succeed in its worst second; two bulkheads of 15 leave A untouched, and B averages 40% while slow. Degrading instead of failing, backpressure (Part 43), and shedding by criticality as in Google's SRE book.
  • 6. Redundancy. Ten machines' capacity from machines up 99% of the time: N gives 90.4% (1.0 nines), N + 1 99.48% (2.3), N + 2 99.979% (3.7), N + 3 99.99933% (5.2); Gray's 1985 Tandem study (operations and software, not hardware, caused most outages). Active–passive against active–active: to lose one of n sites run each below (n − 1)/n, the cascade arithmetic in reverse (two sites at 45% each, one left at 90%). Evacuating one of three regions at 60% leaves two at 90%; headroom, data already replicated (recovery point and recovery time) and practice. A Raft group's availability, the binomial tail above a majority: at 99% a node, 1, 3, 5 and 7 nodes give 2.0, 3.5, 5.0 and 6.5 nines; at 99.9%, 3.0, 5.5, 8.0 and 10.5. Even sizes buy nothing; shared causes cap the nines.
  • 7. Metrics, and why averages lie. Counters, gauges and histograms (Prometheus, 2012). Two hundred thousand simulated latencies: mean 30.4 ms, median 20.5 ms, p99 177 ms, p99.9 834 ms, maximum 104 s; a page making 100 requests meets one beyond the p99 63% of the time. Ten servers, one four times slower: nine p99s of about 170 to 182 ms and one of 719; their average is 230 ms, the fleet's true p99 270 ms, and the ten DDSketches merged bucket by bucket give 268 ms. DDSketch's guarantee derived (γ = (1 + α)/(1 − α), x̂ = 2γⁱ/(γ + 1), |x̂ − x| ≤ αx); at α = 1% these latencies, 4 ms to 104 s, fill 332 buckets. Four summaries against the true quantiles (relative error at p50, p90, p99, p99.9 and p99.99): DDSketch 0.9%, 0.8%, 0.5%, 0.4%, 0.8% in 332 buckets; the log-linear (HdrHistogram) layout 0.1%, 0.2%, 0.1%, 0.0%, 0.3% in 1,070; KLL (Part 46) 0.7%, 0.5%, 9.8%, 48.5%, 84.7% with 238 values, since it bounds the error in rank; a sample of 1,000 0.5%, 2.1%, 2.2%, 52.0%, 68.0%. Cardinality (illustrative): 5 methods × 8 statuses × 40 routes × 200 instances = 320,000 series; a user label for a million users makes 3.2 × 10¹¹.
  • 8. Logs and traces. Structured logs as named fields, queries over them, and the trace id that joins them. Spans with trace, span and parent ids (Dapper, 2010), carried in the W3C traceparent header; OpenTelemetry. One synthetic trace of nine spans as a waterfall, catalog and recommender in parallel: 32.6 ms. Its critical path, the longest path through the DAG of work (Part 19): model 12.6 ms, render 6.0, features 5.8, recommender 4.0, front end 2.4, auth 1.7; the catalog and its 12.5 ms database are off it, with 7.3 ms of slack. Sampling 50,000 traces (876 with an error, 4,307 slower than 100 ms): head sampling at 1% kept 533, of them 4 errors and 54 slow ones; tail sampling kept 5,584, every error and every slow trace.
  • 9. Coordinated omission. A closed-loop generator meant to send 100 requests a second to a server that answers in 1 ms but freezes for 4 s in every 40 (10% of the time): of 20,000 requests due in 200 s it measured 18,005, and the 1,995 skipped are exactly those that would have waited. The closed loop reports 1.0 ms at p50, p90, p99 and p99.9, a maximum of 4.0 s and a mean of 2.1 ms; measured from intended send times, p50 1.0 ms, p90 402 ms, p99 3.6 s, p99.9 4.0 s, mean 223 ms. The ramp of true waits through one freeze; Tene's name for it, wrk2's open loop and HdrHistogram's correction. Open against closed load (Schroeder, Wierman and Harchol-Balter 2006): 10 to 150 users thinking for 1 s with 10 ms requests; at 92% busy the closed system answers in 82 ms and an open one at the same throughput (M/M/1, Part 31) in 132 ms; at 150 users the closed mean is 500 ms and the open one 15,358 s.
  • 10. Profiling and flame graphs. Pebble runs version zero of the Job on 20,000 bytes of a novel: 6,292,955 instructions, every 997th sampled (a prime, so as not to fall into step with a loop), 6,311 samples (scan 2,702, next 2,470, cmp 756, lower 108, read 105, the rest 170). The binomial standard error √(p̂(1 − p̂)/n) checked against exact counts: scan sampled at 42.81% ± 0.62 against 43.46% exactly (z = −1.0), next 39.14% ± 0.61 against 38.32% (+1.3), cmp 11.98% against 12.09% (−0.3), found 0.29% against 0.17% (+2.2); pdig ran 1,386 instructions and drew no sample. The flame graph (Gregg 2011): word 94.5% of samples, scan and next 82%, walking an unsorted table entry by entry, so the fix is Part 17's hash table. The emulator's own Python profiled by a 1,000 Hz CPU-time timer (600 samples): step itself 60%, load 15%, the decoded-instruction cache 12%, the loop in run 11%. Off-CPU time, and eBPF summing waits by stack in the kernel (Part 31).
  • 11. Performance method and capacity. USE for every resource and RED for every service (an illustrative disk only 60% busy yet saturated); Google's four golden signals. The roofline again (Williams, Waterman and Patterson 2009; schematic). Capacity for the Job service by Erlang C (Part 45), 80 ms a book, mean wait under 20 ms and at most 20% waiting: 12, 35, 100, 300 and 1,000 books a second need 3, 5, 12, 30 and 90 servers, 32%, 56%, 67%, 80% and 89% busy, with 2.0, 2.2, 4.0, 6.0 and 10.0 spare against √(busy) of 1.0, 1.7, 2.8, 4.9 and 8.9. A 3% regression from commit 52 of 80 under 2% noise: a naive 5% rule fires five times (commits 4, 49, 52, 68, 77); change-point detection splits at commit 52, mean 1.000 to 1.032, and none of 2,000 shuffles splits as well.
  • 12. Incidents and post-mortems. An incident minute by minute (illustrative): a change at minute 2, errors at 4, the fast-burn page at 11, acknowledged at 13, declared at 16, the status page at 21, rolled back at 34, recovered at 37; time to detect and time to mitigate; about 70% of Google's outages came from changes to a live system. Incident command (from the firefighters' Incident Command System): commander, operations, communication, planning. The blameless post-mortem and its sections, "where we got lucky" among them (Allspaw 2012). Reason's Swiss-cheese model with the four holes of the S3 outage. Six of Cook's eighteen observations (1998).
  • 13. Chaos engineering. Chaos Monkey and the Simian Army (Netflix, 2011); Basiri et al.'s principles (2016): steady state, hypothesis, real-world events, a difference between experiment and control, in production, continuously. Blast radius: 1% of traffic to the experiment and 1% to a control; crashing one of three replicas under the naive client loses 33% of the experiment's requests, and aborting after a minute costs 0.008% of the month's error budget, against 13% for chapter 14's whole hour on all traffic. Injecting crashes, partitions and slowness (tc netem); the hypotheses for Part 38's Raft cluster, written before the run.
  • 14. The Job service under faults. Three counter replicas, 20 requests a second (lognormal, median 40 ms); the steady state: 99.9% of requests answered within 300 ms. Counter 1 crashes from minute 10 to 15, counter 2 is cut off from 25 to 30, counter 3 is ten times slow from 40 to 50. The naive client keeps 66.7% of requests through the crash and the partition and 76% while one is slow, 90.48% over the hour; a 150 ms timeout with one retry elsewhere keeps 99.91%; adding outlier ejection (five failures in a row) and a hedge at 100 ms keeps 100.00%. The cost: 6,835, 66 and 0 bad requests, 13.22%, 0.13% and 0.00% of the month's budget, for 0.0%, 11.3% and 1.2% extra requests. Raft under a crashed leader, a minority partition and two crashed followers: 1,195 of 1,221 commands committed; besides the first second, before a leader is elected, the share dips only in the seconds of the leader crash (67%) and the partition (50%), not at all when two followers crash, and the safety checker finds no violation. Ledger row 19: thirty books on 42 workers, one ten times slow, take 0.71 s without hedging and 0.30 s with a hedge at 240 ms (healthy and unhedged, 0.32 s), for 2.0 extra requests a run.
  • 15. Frontier: gray failure and metastability. Gray failure and differential observability (Huang et al. 2017); health judged from real requests, as the Job's best client did. Where a trigger tips chapter three's server over: capacity left 90%, 80%, 70%, 60% and 50% for 2, 5, 10 and 20 s; 7 of the 20 triggers leave it collapsed a minute after they end (70% and 60% for 10 s or more, 50% for 5 s or more). Research on metastability models, safer change and machines on call. Four open problems and the ★ research problem.
  • Outro. Recap, payoffs, practice, problems, next part.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record

Observability (metrics, logs, traces, profiles) is how you find out what happened. Performance engineering is the same discipline aimed at speed.

  1. Hook: three post-mortems (the 2017 S3 typo, the 2019 regex, the 2024 endpoint update, all cited), each a lesson.
  2. Availability arithmetic:
    • nines as downtime budgets;
    • series ∏Aᵢ against parallel 1 − ∏(1 − Aᵢ), derived and drawn as Part 3's switch circuits;
    • A = MTBF/(MTBF + MTTR);
    • correlated failures break the independence assumption.
  3. SLIs, SLOs and SLAs; error budgets; multiwindow burn-rate alerts (thresholds derived).
  4. Failure modes: fail-stop against gray failure; cascading failures; metastable failures (Bronson et al. 2021; Huang et al. 2022), where a retry-amplified overload persists after its trigger (simulated).
  5. Timeouts, retries, backoff and jitter (full, equal and decorrelated jitter compared; Brooker 2015); retry budgets; hedged requests (callback to Part 39).
  6. Circuit breakers, bulkheads, load shedding and admission control (CoDel for services, callback to Part 37); graceful degradation; backpressure (callback to Part 43).
  7. Redundancy: N + 1 and N + 2; active–passive against active–active; regional evacuation; a Raft group's availability (callback to Part 38).
  8. Metrics: counters, gauges, histograms; why averages lie; quantile sketches (HDR histograms; DDSketch and its relative-error guarantee, derived; callback to Part 46); cardinality.
  9. Traces: structured logs; distributed tracing (Dapper 2010) with spans and context propagation; head against tail sampling; critical-path analysis of a trace (callback to Part 19's DAGs).
  10. Coordinated omission: how load generators under-report tail latency (measured against true p99 in simulation); open against closed load (Schroeder et al. 2006).
  11. Profiling:
    • sampling profilers and the binomial error of a sample count;
    • flame graphs (Gregg), built from a profile of our own Pebble emulator running the Job;
    • off-CPU time; eBPF (callback to Part 31).
  12. Performance method: USE and RED; the roofline again (callback to Part 9 and AI, Built 17); capacity planning with queueing (callbacks to Parts 31 and 45); catching performance regressions in CI by change-point detection.
  13. Incidents: on-call, incident command, communication; blameless post-mortems; the Swiss-cheese model; Cook's "How Complex Systems Fail".
  14. Chaos engineering (Chaos Monkey 2011; Basiri et al. 2016): hypotheses and blast radius; fault injection on our Job service and Raft cluster.
  15. The Job service under crashes, partitions and slow nodes, with its availability and SLO burn measured. Ledger row 19. Outro.

Computed: availability compositions; burn-rate alerts on synthetic error streams; a metastable retry storm; backoff contention with and without jitter; circuit-breaker dynamics; sketch errors; trace-sampling coverage; coordinated omission; a flame graph of the emulator; capacity plans; chaos experiments on our services. Visuals: availability as series and parallel circuits; an error budget draining; a metastable loop stuck in its bad state; backoff timelines with and without jitter; a flame graph; a trace waterfall with its critical path lit. In practice: SRE and on-call; Prometheus, Grafana, OpenTelemetry; load testing; performance engineering; incident management. Reading: Beyer, Jones, Petoff & Murphy, Site Reliability Engineering, and The Site Reliability Workbook; Nygard, Release It!; Gregg, Systems Performance (2nd ed.) and BPF Performance Tools; Jain, The Art of Computer Systems Performance Analysis; Harchol-Balter; Sigelman et al. 2010; Masson, Rim & Lee 2019; Bronson et al. 2021; Huang et al. 2022; Brooker 2015; Schroeder, Wierman & Harchol-Balter 2006; Cook 1998; Basiri et al. 2016.


中文讲义

本讲的中文部分(与英文版对应)。

习题与解答
  1. 可用性。 一个请求要经过五个服务,每个 99.95%,每个服务有两个副本。它的可用性是多少?如果每个服务的停机时间中有 10% 是 共因的,又是多少?

    解答

    每个副本有 q = 0.0005 的时间停机。副本相互独立时,只有两个都停机,服务才停机,概率为 q² = 2.5 × 10⁻⁷,所以服务的可用性 为 1 − q²;五个服务串联得 (1 − q²)⁵ ≈ 1 − 5q² = 1 − 1.25 × 10⁻⁶:99.99988%,5.9 个九,每年约 0.66 分钟(39 秒)。(没有副本时, 0.9995⁵ = 99.750%,2.6 个九,每年 21.9 小时。)现在像第 1 章那样,设每个副本停机时间中有 c = 0.1 的份额是让两个副本同时停机的共因 事件:共因部分有 cq = 5 × 10⁻⁵ 的时间停机;为了让每个副本自身的停机时间仍为 q,独立部分的停机比例为 q′ = (1 − c)q/(1 − cq) = 4.5002 × 10⁻⁴。共因不发生、且两个独立部分不同时停机时,服务才可用:(1 − cq)(1 − q′²) = 1 − 5.020 × 10⁻⁵, 4.3 个九。五个串联:(1 − 5.020 × 10⁻⁵)⁵ = 99.9749%,3.6 个九,每年 132 分钟(2.2 小时),是独立情形的两百倍。一阶近似下不可用度为 5(cq + q′²) ≈ 5cq:共因份额相当于一个串联的部件,每个服务的可用性被封顶在 1 − cq,副本带来的平方项已无关紧要。

  2. 消耗速率阈值。 推导在 6 小时内花掉 30 天预算的 5% 时发出呼叫的消耗速率阈值,以及消耗速率为 10 时的检测时间。

    解答

    一个月有 N 个请求,预算为 (1 − SLO)N 个错误。消耗速率 b 意味着错误率为 b(1 − SLO),所以 w 小时的窗口(含 N w/720 个 请求)花掉 b(1 − SLO)N w/720,即预算的 b w/720。令它等于 f,得 b = f × 720 小时/w = 0.05 × 720/6 = 6:目标为 99.9% 时,就是六小时内 0.6% 的错误率。从一个干净的窗口开始,消耗速率为 10 时,t 小时后 6 小时窗口的平均消耗速率为 10t/6,在 t = 6 × 6/10 = 3.6 小时时达到 6 (计入第 2 章 0.1 的背景消耗速率为 3.58 小时)。一般地,长窗口在 w b*/b 之后检测到 b ≥ b* 的消耗,此时已花掉的预算为 b(w b*/b)/720 = f,无论 b 是多少都是同样的 5%:消耗越快,发现得越早,但代价并不更小。多窗口规则的 30 分钟窗口在 18 分钟后就达到 6, 所以起决定作用的是 6 小时窗口。1 小时、阈值 14.4 的规则对消耗速率 10 永远不会触发,而这样的消耗会在 72 小时内耗尽预算。与第 2 章 对照:那次降级的消耗速率为 12,179 分钟后发出呼叫,而公式给出 6 × 6/12 = 3 小时(计入背景为 2.97 小时)。

  3. 重试放大。 证明当 L 层每层重试 r 次时,一个出故障的后端会收到 (r + 1)ᴸ 次尝试,而 10% 的重试预算把它限制在 1.1ᴸ。

    解答

    从用户一侧把各层编号为 1 到 L,第 L 层调用后端;设 aₖ 为每次用户操作中第 k 层发出的尝试次数。后端故障时,每次尝试都会一路 失败上来,所以一层收到的每个请求都会在下游变成 r + 1 次尝试:a₁ = r + 1,aₖ = (r + 1)aₖ₋₁,归纳得后端收到 a_L = (r + 1)ᴸ 次(第 4 章 三层、每层四次尝试时为 64;十层时 4¹⁰ ≈ 10⁶)。重试预算允许客户端追加的重试至多为其首次尝试的 β = 0.1,实现为令牌桶:每次首次尝试 挣得 β 个令牌,至多存 B 个。一层的首次尝试就是它收到的请求 nₖ₋₁(上层的重试作为新请求到达),所以在任何时段内 nₖ ≤ (1 + β)nₖ₋₁ + B,归纳得 n₀ 次用户操作至多让后端收到 1.1ᴸn₀ + B(1.1ᴸ − 1)/0.1 次尝试:长期看每次操作 1.1ᴸ 次(三层 1.331,十层 2.59),外加一个受令牌桶限制的突发。这个界按层相乘,所以像第 4 章建议的那样只在一层重试更好:1.1。

  4. DDSketch。 证明 DDSketch 的保证:桶 i 中的每个值与 2γⁱ/(γ + 1) 的相对误差都在 α 以内。

    解答

    取 γ = (1 + α)/(1 − α),值 x 落入桶 i = ⌈log_γ x⌉,所以 γⁱ⁻¹ < x ≤ γⁱ。于是 x̂/x = 2γⁱ/((γ + 1)x) 落在 [2γⁱ/((γ + 1)γⁱ), 2γⁱ/((γ + 1)γⁱ⁻¹)) = [2/(γ + 1), 2γ/(γ + 1)) 中。由于 γ + 1 = 2/(1 − α),有 2/(γ + 1) = 1 − α, 2γ/(γ + 1) = γ(1 − α) = 1 + α,所以 1 − α ≤ x̂/x < 1 + α,即 |x̂ − x| ≤ αx。这个估计是桶两端的调和平均,是按相对误差到两端距离相等的 唯一一点。关于分位数:各桶的计数是精确的,所以累计计数第一次越过该秩的那个桶里正好有真实的 q 分位数,回答与它的相对误差在 α 以内。 α 相同的草图合并时逐桶相加计数,合并后的草图恰好就是并集的草图,保证不变;这就是第 7 章合并后的 p99(268 毫秒)正确、而各 p99 的 平均(230 毫秒)不正确的原因。从 m 到 M 的值至多需要约 log_γ(M/m) ≈ ln(M/m)/(2α) 个桶:α = 1% 时,4 毫秒到 104 秒约需 509 个, 我们的延迟填了其中 332 个。

  5. 动手。 给一个客户端加上断路器和重试预算,并测量容量下降期间的有效吞吐量(goodput)。

    解答

    解答要点。 从 explainer/cs/ops/overload.py 中的 overload 出发,它已经有 "breaker" 和 "budget" 两种策略,各用 policy == ... 判断。让一个策略表示一组机制(例如 "breaker+budget",按成员关系判断),使超时的请求只有在断路器闭合且客户端持有 令牌(每次首次尝试挣得 0.1 个,至多 10 个)时才重试。模拟器中的断路器是所有客户端共享的一个状态:上一秒的尝试过半失败时打开 5 秒, 打开期间仍有 5% 的调用作为探测通过;更完整的答案给若干客户端各自一个三态机(闭合:在滑动窗口上计数失败,并要求最少调用数;打开:在 冷却期内立即失败;半开:放行少量探测,成功则闭合,失败则重新打开)。在第 3 章的触发事件上以及 trigger_sizes 的整个网格上,测量每秒 和总的有效吞吐量、发出的负载,以及 recovered_s(触发事件结束后到有效吞吐量回到需求的 90% 所需的时间)。组合策略的一个快速实现在第 3 章的触发事件上及时回答了 9,098 个请求(只用断路器 9,110,只用预算 7,530):这里起作用的是断路器。在更深、更长的下降(降到 30%,持续 20 秒)中,只用预算在运行结束前都没有恢复(回答了 2,496 个),因为服务器仍按先来先服务处理一批客户端早已放弃的积压请求,而且只能用 预算留下的余量来消化它;组合的客户端回答了 8,133 个,下降结束一秒后就恢复了。应补充的测试:组合策略在网格的每一格上都能恢复;断路器打开时, 发出的负载保持在探测速率附近;重试从不超过首次尝试的 10% 加上令牌桶容量。

  6. ★ 研究。 一个会重试的服务器无法从中恢复的触发事件的精确集合。

    讨论。 尚未解决。对容量为 μ、用户发送 λ < μ、客户端超时为 τ、重试 r 次的服务器,可以并存两个稳态:好的稳态,队列短、没有超时; 坏的稳态,每个请求的等待都超过 τ,于是每个用户请求变成 r + 1 次尝试,发出的负载为 λ(r + 1),当 λ(r + 1) > μ 时它自我维持(第 3 章: 80 × 4 = 320 > 100)。触发事件的集合,就是把状态带出好稳态吸引域的扰动(这里是容量比例 f 持续 D 秒)的集合。难点在状态本身:带截止 时间的先来先服务队列要用所有等待者的年龄来描述,是一个无穷维、有时滞的随机系统,边界附近的结果不只取决于积压量。我们的网格就说明了 这一点:降到 70% 持续 10 秒和降到 60% 持续 5 秒都留下约 100 个请求的缺口,但前者崩溃、后者恢复,很可能是因为前者有更长的时间处于等待超过超时、 不断产生重试的状态。边界附近的结果是随机的,所以"精确集合"其实是崩溃概率作为 (f, D) 的函数。好的部分答案应当采用流体或扩散模型, 明确处理超时和被放弃的工作,证明双稳态的条件,并给出崩溃区域的内界和外界(必然恢复的状态和不可能恢复的状态),两者彼此接近,并在一系列 λ、μ、τ 和 r 上与 trigger_sizes 吻合;即使只在确定性极限下给出边界的闭式解,也已经是新的。

Build the film

python -m videos.cs.cs50.compute        # the part's numbers, into .cache/cs50
python tools/build.py cs50                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs50 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/cs/cs50. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it
python -m videos.cs.cs50.compute
python -m unittest tests.test_cs50_ops
python tools/build.py cs50