Clients share one file through a lock with a 10-second lease. Each client checks its lease before every write. In one simulated hour, 15 writes still land after the lease ran out, each on top of the next holder's work. A 2-second margin leaves 2. Fencing tokens reject all 15.
Pick how the clients protect the file and replay the hour. Then we build each part from zero: silence, delays, clocks, pauses, the majority, fencing tokens, lying nodes and system models.
You need a little Python and what a probability is. We build the rest from zero.
Illustrative and seeded. 360 leases of 10 s, one after another, each to the next client. A holder writes every 100 ms. 2% of writes meet a pause with a long tail: Pareto, scale 50 ms, shape 1.2. A message takes 1 ms. Clocks are exact, so the danger is the pause between check and write.
Chapter 0
Send requests over a lossy network and count how often the silence hides finished work
On one computer, a function call returns or the machine is broken. Over a network there is a third outcome. A payment service asks the bank to charge a card, and no reply comes.
The request may be lost. The bank may have crashed or be busy, or the reply may be lost. To the sender, all of these look the same. This is partial failure: some parts work, some do not, and you cannot tell which.
Each row is one request as the sender sees it: a teal reply, or grey silence. Turn on the truth to see what happened to each silent one. Move the loss.
Illustrative and seeded: 20,000 requests; each request, and each reply, is lost with chance p on its own. Crashes and slow replies add more silence; they are left out so the count matches the formula.
Suppose the only trouble is loss. Call the chance that one message is lost p, the same each way. Call the chance that the bank did the work, given that you heard nothing, Pdone.
P-done equals one minus p, over two minus p.
Silence happens two ways. The request is lost, with chance p, and nothing was done. Or the request arrives and the reply is lost, with chance (1 − p) times p, and the work was done. P-done is the second way's share of all silence.
With made-up numbers: p = 1%. P-done = 0.99 / 1.99 = 49.7%. Our 20,000 seeded requests gave 395 silences, and 196 of them were done: 49.6%. For any small loss, a silent request was done about half the time.
So both obvious moves are wrong half the time: give up and lose a real charge, or retry and charge twice. The fix is a safe retry. Send an idempotency key: a request ID the bank stores with the charge. A repeat then returns the first answer.
This lesson follows Chapter 9 of Designing Data-Intensive Applications, 2nd edition, by Martin Kleppmann and Chris Riccomini (O'Reilly, 2026). We explain its ideas in our own words, with our own examples and simulations. Its question is: what can one node know? Failure Detection and Time and Failure Modes and Isolation simulate the timers, clocks and failure patterns. We link to them and keep to the book's angle.
Failure. Symptom: a customer is charged twice after a timeout and a retry. Measure: duplicate charges with the same order and amount within seconds. Cause: the first request succeeded and only its reply was lost. Fix: an idempotency key stored with the charge, checked before any retry runs.
Chapter 1
Break a server five ways and see which faults announce themselves
Datacenter networks fail often. Bailis and Kingsbury's survey "The Network is Reliable" cites a study of several Microsoft datacenters. It found an average of 5.2 device failures and 40.8 link failures a day, with a median repair time of about five minutes. That is about 14,900 link failures a year. Redundant network gear helped less than you would hope: during a failure it improved median traffic by only 43%.
A network partition is a fault that splits nodes into groups that cannot reach each other. Every node is still running. Each side may keep serving clients and make decisions the other side never sees.
When a server goes quiet, sometimes you get a signal. If the process died but the machine is up, the operating system answers a new connection with a reset, so the client sees "connection refused" at once. Often there is no signal at all.
The client sends a request at time 0. Pick a fault and watch what comes back, and when. Then move the timeout.
Illustrative: one request, a 1 ms network, fixed fault times. The reset is what a Linux host sends when no process listens on the port.
Only one of the five faults announces itself. The other four give the same silence until the timeout. Two of those four servers are alive: the paused one and the busy one. Declare them dead, and you may start a second leader while the first is still working.
Google's paper on Chubby, its lock service, lists 61 outages over 700 days. Of the nine that lasted over 30 seconds, four came from network maintenance and two from suspected network problems. Faults like these are the normal case. Plan for them, and test them by injecting them on purpose.
Failure. Symptom: a failover starts while the old leader is still serving writes. Measure: overlapping periods when two nodes accept writes as leader. Cause: a pause or a cut link looked like a crash. Fix: let a majority decide (Chapter 5) and fence the old leader (Chapter 6).
Chapter 2
Load one switch queue and watch a fixed timeout start to accuse healthy servers
Suppose the network promised that every packet arrives within a time d, and the server promised to answer within a time r. Then a reply always comes within 2d + r, and that would be a perfect timeout. Our networks promise neither.
The reason is queueing. A switch port, an operating system's socket buffer and a busy CPU each hold work in a line. A telephone circuit reserves a fixed slot for each call, so its delay is fixed. A packet network shares every link, which uses the capacity well but lets lines grow without limit when traffic bursts.
The histogram shows 20,000 packet delays through one queue. Delays past the yellow timeout line are red: healthy servers declared slow or dead. Raise the load.
Illustrative and seeded: one first-in, first-out queue, random arrivals, service times averaging 1 ms (an M/M/1 queue). Real paths stack several queues, plus TCP retransmits of 200 ms and more.
Call the queue's service rate μ (mu), in packets a millisecond, and the arrival rate λ (lambda). The load is ρ = λ/μ. Call the chance that a packet's delay is longer than a timeout t the tail P(T > t).
P of T greater than t equals e to the minus, mu minus lambda, times t.
Subtract the arrival rate lambda from the service rate mu: that is the spare capacity. Multiply it by the timeout t. The tail is e to the minus that number. As lambda nears mu, the spare capacity nears zero, and the tail grows for every t.
With made-up numbers: mu = 1 a ms, t = 20 ms. At 50% load, lambda = 0.5 and the tail is e−10 = 0.005%. At 90% load, lambda = 0.9 and the tail is e−2 = 13.5%; our seeded queue gave 12.4%. The same timeout now accuses one healthy reply in eight.
So no fixed timeout is safe. Short timeouts detect crashes fast but accuse healthy nodes under load. A false verdict moves the node's work to others, which adds load, which causes more false verdicts. Long timeouts mean users wait while a dead node keeps getting requests. Measure the delay distribution and set timeouts from its tail, or let them adapt: Heartbeats and Timeouts and Phi Accrual simulate both.
Failure. Symptom: failovers and "node down" alerts during traffic peaks, with every node healthy. Measure: the 99th percentile delay at peak against the timeout. Cause: queueing near full load stretches the tail past a timeout set in a quiet hour. Fix: set the timeout from the peak tail, add capacity, or use an adaptive detector.
Chapter 3
Skew one replica's clock and count the writes that "last write wins" throws away
A computer has two clocks. The time-of-day clock gives the date and time, such as Python's time.time(). NTP can step it forward or back, so it can jump. The monotonic clock, time.monotonic(), only moves forward. Use it to measure a duration, such as a timeout. Its value means nothing on another machine.
Every clock drifts. Spanner assumes a worst case of 200 parts per million: 6 ms off after 30 seconds unsynced, 17 seconds after a day. NTP pulls clocks back, but RFC 5905 counts half the round trip to the server in its "maximum error".
So a clock reading is a range, not a point. Spanner's TrueTime returns the range, about 1 to 7 ms wide in Google's production; TrueTime simulates how Spanner waits it out. Most clock APIs hide the range.
Last write wins (LWW) keeps the write with the highest timestamp; Cassandra resolves conflicting writes to a cell this way. If one replica's clock runs behind, its newer writes carry older stamps, and the database drops them without an error.
The top lane is real time: filled dots are writes to replica A, hollow dots to B. The bottom lane places them by timestamp. Red writes were dropped. Move B's skew.
Illustrative and seeded: 20,000 writes to one key at random times, each to A or B with equal chance. Each write is stamped with its replica's clock; a write whose stamp is older than the newest kept stamp is dropped.
Call the write rate on the key λ, in writes a second, and B's skew s, in seconds. Call the share of all writes dropped D.
D equals one half, times one minus e to the minus lambda s over two.
A write on B gets a stamp s too early. It loses if a write on A came in the last s seconds. Writes reach A at rate lambda over two, so the chance of none is e to the minus lambda s over two. Take one minus that, and halve it.
With made-up numbers: lambda = 100 writes a second and s = 10 ms = 0.01 s. lambda-s over two = 0.5, so D = 0.5 × (1 − e−0.5) = 19.7%. Our 20,000 seeded writes lost 3,949: 19.7%. A 10 ms skew, well inside normal NTP error, silently drops one write in five.
Failure. Symptom: users report saved changes that vanish, with no error anywhere. Measure: clock offsets between replicas, and writes to the same key closer together than that offset. Cause: last write wins with time-of-day timestamps. Fix: version numbers or logical clocks (Lamport clocks), or keep both values and merge.
time.time() and get −300 ms. What happened?Chapter 4
Pause a lock holder at random and see that no safety margin brings late writes to zero
A lease is a lock with an end time, so a dead holder's lock frees itself. A careful holder checks the time left before each write:
while True: if lease.expires_at - time.monotonic() < MARGIN: break # give the lock up # <-- a pause here outlives the lease storage.write(data)
The bug is the gap between the check and the write. A stop-the-world garbage collection freezes every thread. A hypervisor can suspend a virtual machine to move it. The operating system can swap memory to disk. Bailis and Kingsbury collect cases where pauses of seconds made a cluster elect a second leader. The paused thread does not notice: when it wakes, it sends the write.
Top: one lease with its writes (blue) and pauses (pink); a write that lands after the yellow lease ends is red. Bottom: late writes in one hour against the bound. Move the margin.
Illustrative and seeded, the hero's model: 360 leases of 10 s and a write every 100 ms. Pauses have a Pareto tail, scale 50 ms, shape 1.2. The pause figures are made up; measure your own runtime's pauses.
A margin m helps: the holder stops when less than m remains, so a write is late only if its pause outlasts m. Call the chance that a write pauses p. A pause's length has a long tail: the chance it exceeds x is (x0/x)α, for a scale x0 and a shape α (alpha). Call the chance that a write lands late Plate.
P-late is at most p times, x-zero over m, to the alpha.
After a passed check, at least m of the lease is left. The write is late only if a pause happens, chance p, and lasts longer than m, chance x-zero over m to the alpha. Multiply them. It is "at most", because often more than m is left.
With made-up numbers: p = 2%, x-zero = 50 ms, alpha = 1.2, m = 2 s. P-late ≤ 0.02 × 0.0251.2 = 0.024%. An hour has 27,952 writes, so at most 6.7 late writes; our seeded hour had 2. With no margin, it had 15. The bound shrinks as m grows, but never reaches zero.
A margin also costs: 2 s of a 10 s lease leaves the lock unused 20% of the time. Hard real-time systems, such as an airbag controller, bound every pause with special operating systems. A database on a cloud server cannot. It must stay correct after a pause: Chapter 6.
Failure. Symptom: two clients both wrote while "holding" the lock, after a long garbage collection. Measure: GC and VM pause logs next to lease grants. Cause: a pause between check and write. Fix: no margin is enough; have the storage reject stale holders with fencing tokens.
Chapter 5
Let several nodes vote on whether one is dead, and see false verdicts fall, until they share a switch
A node cannot judge its own state. A paused node thinks no time passed. A node whose outgoing messages are dropped still receives requests, so it believes it is fine, while the others hear nothing and call it dead. The book's point: truth in a distributed system is what a quorum, here a majority of nodes, agrees on.
So a node that the majority declares dead must accept the verdict and step down, even if it feels healthy. A leader that the majority replaced is no longer the leader, whatever its own memory says.
The centre node is healthy. Each other node suspects it (red) or not, on its own. Bars compare false "dead" verdicts from one observer and from a majority vote. Move the suspicion, then share a switch.
Illustrative and seeded: 20,000 rounds. The node under test does not vote on itself, so n nodes give n − 1 observers. With the switch on, 2% of rounds make every observer suspect at once.
Why does voting help? Call the number of observers kobs, the votes a verdict needs q, and each observer's chance of a false suspicion s. Call the chance of a false "dead" verdict Pfalse.
P-false equals the sum, over j from q to k-obs, of k-obs choose j, times s to the j, times one minus s to the k-obs minus j.
For each count j from q up to all k-obs observers, count the ways to choose j suspicious observers. Multiply by the chance that exactly those suspect and the rest do not. Add the terms. It assumes each observer errs on its own.
With made-up numbers: n = 5 nodes, so k-obs = 4 observers and q = 3 votes. s = 13.5%, the 90% load tail from Chapter 2. P-false = 4 × 0.1353 × 0.865 + 0.1354 = 0.88%; our seeded rounds gave 0.85%. One observer alone was wrong 13.3% of the time.
Two majorities of the same cluster always share at least one node, so two groups cannot both win a vote. That is why a cluster of 5 survives 2 failures and a cluster of 4 survives only 1. Consensus and Replication builds quorum intersection step by step.
Failure. Symptom: the whole cluster declares a healthy node dead at once. Measure: whether the observers share a switch, a rack or a software version. Cause: one shared fault makes every vote fail together, so the formula's independence is false. Fix: spread observers across failure domains; see gray failure.
Chapter 6
Step through a stale lock holder's write, with and without a storage that checks tokens
The client cannot protect itself from its own pauses, so move the check to a place that does not pause at the wrong moment: the storage. Each time the lock service grants a lease, it also hands out a fencing token, a number that grows with every grant. The client sends its token with every write.
The storage remembers the highest token it has accepted. A write with a lower token comes from a holder whose lease was replaced, so the storage refuses it. The stale client learns that it lost the lock from the refusal.
Three lanes: client A, client B and the storage, on one time line. Step through the story, then turn the token check off and step again.
A scripted example with made-up times and tokens. The hero runs the same rule over 360 leases.
Call the token on an arriving write tw, and the highest token the storage has accepted tmax.
Accept, if and only if t-w is at least t-max.
Compare the write's token t-w with the highest token seen, t-max. If t-w is equal or higher, apply the write and store t-w as the new t-max. If t-w is lower, refuse it. "Equal" lets the current holder write many times.
With made-up numbers: A holds token 41, pauses, and its lease ends. B gets 42 and writes, so t-max = 42. A wakes and sends a write with t-w = 41. 41 ≥ 42 is false, so the storage refuses it. In the hero's hour, this rule refused all 15 late writes.
Three conditions make it work. The tokens must come from one source that never repeats a number. That is why lock services, such as ZooKeeper and etcd, run on consensus; etcd's revision numbers only grow. Every storage node the client writes to must check the token. And a client must never write without one.
A fencing token does not stop the stale client from acting. It stops the action from mattering. That shift, from "trust the client" to "check at the resource", is the main idea of this chapter.
Failure. Symptom: tokens are in place, yet a stale write still overwrote newer data. Measure: which storage paths accept writes without a token: a cache, a second replica, a file on shared storage. Cause: one path does not check. Fix: check the token at every resource the lock protects.
Chapter 7
Let one general lie in every possible way, and count when the loyal ones still agree
Fencing assumes the client sends its real token. A Byzantine fault is a node that sends wrong or conflicting messages: a bug, a flipped bit, or an attacker. Lamport, Shostak and Pease named it in 1982 with a story. Generals surround a city and must all attack or all retreat. A commander sends an order; some generals may be traitors.
The loyal generals need two things. Every loyal lieutenant obeys the same order. And if the commander is loyal, they obey the order it sent. In the paper's "oral messages" algorithm with one traitor, each lieutenant passes on the order it got, then takes the majority of what it heard. A tie means retreat.
The commander orders ATTACK. Each loyal lieutenant's ballot shows what it heard: blue is a true report, red a lie. Step through every lie, then add a general.
Exact enumeration of the paper's oral-messages algorithm with one round of relays (OM(1)) and one traitor. The traitor may send any order to anyone.
With 3 generals, a lying lieutenant can tell the other one "the commander said retreat". That lieutenant hears one ATTACK and one RETREAT, ties, and retreats against a loyal order. The paper proves that no algorithm with oral messages fixes this. Call the number of traitors f and the number of generals n.
n is at least three f plus one.
Count the traitors f you must survive. Multiply by three and add one. You need at least that many nodes n, when messages carry no signatures.
f = 1 needs n = 4. In our enumeration, 3 generals fail in 1 of 2 lieutenant lies. 4 generals fail in none of 12 lies. 7 nodes survive f = 2. Crash faults need only a majority alive: n = 2f + 1, so 7 nodes survive 3 crashes.
Most data systems do not need this. Their nodes run in one organisation's datacenter, and the cost of Byzantine agreement is high. They guard against weak forms of lying instead: checksums against corrupted packets, input checks against bad requests, and NTP clients that ask several servers and drop the outlier. Byzantine fault tolerance matters where nodes do not trust each other, as in blockchains, and in aerospace, where radiation can corrupt a computer's memory.
Failure. Symptom: replicas disagree after a bit flip or a buggy release, and votes cannot fix it. Measure: checksums on messages and on stored data. Cause: a node sent wrong data while voting honestly on it. Fix: end-to-end checksums and validation; Byzantine agreement only where nodes may be hostile.
Chapter 8
Run one election under four sets of assumptions and see which promise breaks
A system model lists the faults an algorithm must handle; its proof holds under those. Two choices matter most.
The usual choice is partial synchrony with crash-recovery. Safety means nothing bad ever happens, such as two leaders in one term; it must always hold. Liveness means something good eventually happens, such as electing a leader; it may wait for good periods.
Five lanes, one per node, over 20 s: warm while leader, blue while candidate, red while crashed. The green band shows when a leader is in charge. Pick a model.
Illustrative and seeded: Raft's voting rule without a log; timeouts 150 to 300 ms; heartbeats every 50 ms. Before GST, and always for "no bound", 85% of messages take about 1.5 s. After it they take 1 to 10 ms. Injected fault: a node crashes right after 30% of its granted votes and restarts within 8 ms.
Why does a leader appear after GST? A follower runs for leader after its timeout T with no heartbeat. Call the longest message time after GST Δ (delta), and a node's answer time r.
T is greater than two delta plus r.
After GST, a request and its answer take at most two delta plus r. If the timeout T is longer, a live leader's heartbeats always arrive in time, and an election finishes before the next one starts. This is the 2d + r timeout of Chapter 2, which only exists after GST.
After GST in our model, delta = 10 ms; take r = 1 ms. 2 × 10 + 1 = 21 ms, far below the 150 ms timeout. Before GST, most messages take about 1,500 ms, so heartbeats miss the timeout and elections pile up.
Over 50 seeds, the assumed model never had two leaders in one term. A leader was in charge 10% of the time before GST and 93% after. With no bound on delays, it stayed safe, but a leader was in charge only 17% of the time. Fischer, Lynch and Paterson (1985) proved that, with no timing bound and one possible crash, no deterministic algorithm can guarantee a decision. Outside the model, safety broke: a node that forgets its vote let two leaders win a term in 3 of 50 seeds, and a node that votes twice in 7.
Failure. Symptom: a "proven" protocol shows two leaders in one term. Measure: whether a restarted node kept what it wrote to disk, including after an fsync that the disk ignored. Cause: the real system left the model, here by losing a vote. Fix: state the model, test outside it with fault injection, and check the assumptions you can at runtime.
Chapter 9
Turn every knob of the hero's lock and see what each protection costs
Back to the hero's lock, with every knob. Pauses come more or less often, and longer or shorter. Leases are short or long. The margin trades safety for idle time. The storage checks tokens, or does not. Every setting replays the same seeded hour.
Each tile is one lease of the hour; red tiles had a late write land. Bars count late writes, overwrites and refusals, and the share of time the lock sat idle. Push the pauses, then fence.
Illustrative and seeded, the hero's engine. One hour of leases back to back; a holder writes every 100 ms; pause shape 1.2; messages take 1 ms. A margin cannot exceed the lease.
At the hero's settings, 15 writes land late, and every one lands on the next holder's work. Make pauses four times longer (scale 200 ms) and 56 land late. A 2 s margin cuts that to 10 and leaves the lock idle 20% of the time. A 5 s margin cuts it to 3, at 50% idle. Turn on the token check and the count of overwrites is zero at every setting.
Lease length cuts both ways. A 30 s lease meets a lease end less often, so 6 writes land late instead of 15. With a 2 s margin it had none in this hour, at 7% idle. But if a holder crashes, the lock stays stuck until the lease ends, up to 30 s.
Failure. Symptom: a lock that "never fails" in tests corrupts data in production about once an hour. Measure: the longest process pauses in production, from GC and VM logs. Cause: tests run small heaps on idle machines, so the long tail of pauses never shows. Fix: fence every write; then tune lease and margin for speed, not safety.
Chapter 10
Keep the numbers, the rules and the code for the next system you design
A node knows only the messages it has received. Silence could be a lost request, a lost reply, a crash, a pause or a queue. Delays have no upper bound, clocks drift and jump, and a process can freeze between a check and an act. So a node cannot decide alone that it is the leader or that another is dead: a majority decides, and the resources it guards check fencing tokens. Each algorithm states its model; safety holds always, liveness when the network behaves.
| Idea | Rule | This lesson's number |
|---|---|---|
| Silence | Pdone = (1 − p)/(2 − p) | 1% loss: 49.7% of silent requests were done |
| Network faults | measured, not derived | Microsoft study: 5.2 devices and 40.8 links a day, median repair 5 min |
| Queueing tail | P(T > t) = e−(μ − λ)t | 20 ms timeout: 0.005% at 50% load, 13.5% at 90% |
| Last write wins | D = ½(1 − e−λs/2) | 100 writes a second, 10 ms skew: 19.7% dropped |
| Clock drift | error = drift rate × time since sync | 200 ppm: 6 ms in 30 s, 17 s in a day |
| Pauses | Plate ≤ p(x0/m)α | 2 s margin: at most 6.7 late writes an hour (seeded 2) |
| Majority verdict | binomial tail from q votes | 5 nodes, s = 13.5%: 0.88% |
| Fencing | accept ⇔ tw ≥ tmax | hero hour: 15 late writes, 15 refused |
| Byzantine | n ≥ 3f + 1 | f = 1: 4 nodes; 7 nodes: f = 2 |
| Partial synchrony | T > 2Δ + r after GST | Δ = 10 ms, r = 1 ms: 21 ms, timeout 150 ms |
pythonfrom math import exp, comb def p_done_given_silent(p): # loss chance each way return (1 - p) / (2 - p) def queue_tail(mu, lam, t): # M/M/1: share of delays above t return exp(-(mu - lam) * t) def lww_dropped(rate, skew): # writes a second, seconds of skew return 0.5 * (1 - exp(-rate * skew / 2)) def late_bound(p, x0, alpha, m): # Pareto pauses, margin m >= x0 return p * (x0 / m) ** alpha def false_verdict(k_obs, q, s): # majority wrongly says "dead" return sum(comb(k_obs, j) * s**j * (1 - s)**(k_obs - j) for j in range(q, k_obs + 1)) class FencedStore: def __init__(self): self.t_max, self.data = 0, None def write(self, token, value): if token < self.t_max: raise PermissionError(f"stale token {token} < {self.t_max}") self.t_max, self.data = token, value print(round(p_done_given_silent(.01), 4), round(queue_tail(1, .9, 20), 4)) # 0.4975 0.1353 print(round(lww_dropped(100, .01), 4), round(late_bound(.02, .05, 1.2, 2), 6)) # 0.1967 0.000239 print(round(false_verdict(4, 3, .135), 4)) # 0.0088 s = FencedStore(); s.write(41, "A"); s.write(42, "B") try: s.write(41, "A, late") except PermissionError as e: print(e) # stale token 41 < 42
Now press Present or Teach and explain four things from memory. Why is a silent request done about half the time? Why does load make a fixed timeout accuse healthy nodes? Why can no margin make a lease safe? Why does the storage, not the client, check the token? Then go back to the hero and find the setting that keeps the file safe.