CComputer Science, Built

Act VII · Many Machines

Part 38 of 61

Distributed Systems I: Agreement

Degreestarts at this level47 min of film13 chaptersprerequisites: Part 33, Part 36, Part 37

How can machines agree on anything when messages are lost and a slow machine looks like a dead one?

The part opens with five Pebbles running Raft for nine seconds through a crashed leader, a partition and a restart: 236 commands committed in 15 terms, every invariant holding. It then starts from nothing. The two generals can never be certain over a lossy link, and without a shared clock the order of events is a definition: Lamport's clocks respect causality, vector clocks characterize it, and Chandy and Lamport's markers photograph a bank that never stops. With synchronized rounds, FloodSet reaches consensus in f + 1 rounds and no fewer, checked against every crash pattern. Then the part turns: Fischer, Lynch and Paterson prove that with unbounded delays no deterministic protocol can guarantee a decision if one process may crash, and an exhaustive explorer shows the bivalent configurations of two tiny protocols. Coins, failure detectors and partial synchrony are the ways around, and Paxos and Raft take the last: always safe because majorities intersect, live when the network behaves. The series' Raft survives a thousand storms while three planted bugs are caught. It ends with traitors, 3f + 1, PBFT and Nakamoto's chain of work, and with what is known about proving and breaking such protocols.

What you need. Proof by induction and by contradiction; elementary probability for the randomized protocols.

Mathematics, ideas and history
two generals, Lamport and vector clocks, snapshots, FLP, Paxos, Raft, Byzantine generals and PBFT, Nakamoto consensus
What we build or compute
a fault-injected Raft cluster

What you will be able to do

Degree

  • Explain why the two generals cannot agree, and why a timeout cannot tell a crash from a delay.
  • Stamp a space-time diagram with Lamport and vector clocks and read off which events are concurrent.
  • Trace a Raft election and a log replication, and say why two majorities always share a server.

Graduate

  • Prove that vector clocks characterize happened-before, and that a Chandy-Lamport snapshot is a consistent cut.
  • Walk through the FLP proof: a bivalent initial configuration, and a step that keeps it bivalent.
  • Prove Paxos's safety invariant by induction on ballots, and Raft's leader completeness.

Research

  • State the lower bounds on agreement (f + 1 rounds, FLP, 3f + 1, Dolev-Reischuk's quadratic messages) and which protocols meet them.
  • Design a fault-injection strategy that exposes a deep protocol bug, and say why no theory yet bounds the runs it needs.

Industry

  • Choose the number of voters and the election timeouts of an etcd or ZooKeeper cluster, and explain why four voters tolerate no more than three.
  • Protect a lock with a fencing token, and test a replicated system with injected faults.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Degree 18 min · Graduate 44 min · Research 47 min · Industry 22 min.

  1. 0Five Pebbles, one logDegree2 min
  2. 1Partial failureDegree3 min
  3. 2Time without a clockDegree4 min
  4. 3SnapshotsDegree3 min
  5. 4Models and consensusGraduate4 min
  6. 5FLPGraduate5 min
  7. 6PaxosGraduate4 min
  8. 7RaftDegree4 min
  9. 8Our Raft, attackedIndustry5 min
  10. 9Byzantine generalsGraduate5 min
  11. 10Nakamoto consensusGraduate4 min
  12. 11Frontier: proving and breakingResearch3 min
  13. 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.

Five Pebbles, one logDegree2 min

Five Pebbles keep one log of commands between them, a replicated log, and agree on every entry. One of them leads; the others follow. Here are nine seconds of their lives, while we do our worst. At one and a half seconds we crash the leader. Within a fifth of a second the others notice, hold an election, and a new leader carries on. At three seconds we cut the network in two: two Pebbles on one side, three on the other, one of the three already down. Neither side has a majority, so neither can commit anything, and the candidates on one side call election after election, in vain. We heal the network, restart the dead, crash another leader. Every time, the survivors agree. In this run they commit two hundred and thirty-six commands through fifteen terms of leadership, and every check we know of passes. We ran a thousand random storms like it. Not one broke the agreement.

And yet there is a theorem that says this is impossible. Leslie Lamport once defined a distributed system as one in which the failure of a computer you did not even know existed can render your own computer unusable. In 1985 Michael Fischer, Nancy Lynch and Michael Paterson proved that no deterministic protocol can guarantee that machines agree on even a single bit, if messages can be delayed without limit and even one machine may crash. The five Pebbles agree anyway. So what did they give up? That is the story of this part.

1Partial failureDegree3 min

A program on one computer never has to think about three things that every distributed program must. Partial failure: some machines crash while the rest carry on, and the rest must decide what to do without them. No global clock: every machine's clock drifts, by tens of parts per million, seconds a day, so two machines cannot even agree what time it is. And asynchrony: a message can take any time to arrive. Wait for a reply that does not come, and you cannot tell whether the other machine is dead or merely slow. Every protocol in this part is a way of living with these three facts, and every impossibility theorem in it is one of them, stated precisely.

Jim Gray told the problem as a story in 1978. Two generals camp on two hills with an enemy in the valley between. Together they can win; alone, either is destroyed. They can communicate only by messenger, and any messenger may be captured. General A sends: attack at dawn. But A cannot attack until it knows B got the message, so B must reply. Then B cannot attack until it knows its reply arrived, so A must acknowledge the reply. And so on, for ever. Whatever the last message is, its sender does not know whether it arrived. Sending many messengers makes success likely: with one in ten captured, six messengers make it a millionth of a chance that all are lost. But likely is not certain, and the theorem says certain is impossible.

The proof is an induction on messages. Suppose some protocol does guarantee that both attack or neither does. Look at a run in which both attack, using as few messages as possible: k of them. Now imagine the last message is lost. Its sender sees exactly what it saw before, so it still attacks, and so, for the guarantee to hold, the receiver must attack too. But that is a run with k minus one messages in which both attack: fewer than the fewest. The only escape is k equal to zero, and with no messages neither general can know the other's plan. No single message can be the one that makes agreement certain. Real protocols, like TCP's handshake and its closing, settle for likely, and use timeouts for the rest.

2Time without a clockDegree4 min

First, the obvious approach: set every clock from a good one. David Mills's network time protocol does this across the Internet. The client notes its time when it sends a request, t zero; the server notes when it receives it, t one, and when it replies, t two; the client notes when the reply arrives, t three. If the trip there and the trip back take equal time, the offset between the clocks is this average, and the round trip is this difference. With a true offset of five seconds and forty milliseconds each way, the estimate is exact. But if the request takes seventy milliseconds and the reply ten, the estimate is thirty milliseconds off, and nothing the client can measure reveals it. Clocks set this way are good to milliseconds on the Internet and microseconds on a local network. Useful, but never good enough to decide which of two nearly simultaneous events came first.

In 1978 Leslie Lamport replaced time by causality. Draw each process as a line, its events as dots in order, and messages as arrows. Event a happened before event b if a comes earlier on the same process, or a sends a message that b receives, or there is a chain of such steps from a to b. If neither happened before the other, they are concurrent: no information could have passed between them, so no observer can ever say which came first, and it does not matter. Happened-before is a partial order, and it is the only order a distributed system can know.

Lamport's clocks turn the partial order into numbers. Each process keeps a counter and adds one at every event. Every message carries the sender's counter, and the receiver jumps past it: the maximum of its own and the message's, plus one. Then if a happened before b, a's number is smaller. Ties are broken by process number, and the result is a total order that every process agrees on, consistent with causality, which is enough to build a mutual exclusion lock with no central server. But the converse fails. In two hundred random executions we checked, concurrent pairs got different numbers almost every time, nineteen thousand of twenty-three thousand, so a smaller number does not mean earlier.

To capture causality exactly, each process keeps not one counter but a vector, one entry per process: how many events of each process it has heard of. This is Colin Fidge's and Friedemann Mattern's vector clock, from 1988. A process increments its own entry at each event, and on receiving a message takes the element-wise maximum with the vector it carries. Now a happened before b exactly when a's vector is less than or equal to b's in every entry and smaller in one. The proof: a's entry for its own process counts a's position, and b's vector reaches that count only if some chain of messages carried it there. We checked the theorem on two hundred random executions, forty-two thousand pairs of events: exact every time. The data race detectors of Part 33 use exactly this, with threads for processes.

3SnapshotsDegree3 min

A snapshot records each process's state, but the processes cannot all stop at the same instant, because there is no instant. So a snapshot is a cut through the space-time diagram: one point on each process's line. A cut is consistent if every message received before it was also sent before it. Such a cut is a state the system could have been in, even if it never was at any one real moment. Here the red cut records a message arriving at P one that, in the picture, P zero has not yet sent. Money appears from nowhere, or a lock is held by two processes. That cut describes a state that could never have happened.

K. Mani Chandy and Leslie Lamport found how to take a consistent cut while the system keeps running, in 1985. The process that starts the snapshot records its own state and sends a special message, a marker, on each of its outgoing channels. A process receiving its first marker records its own state at that moment, notes that channel as empty, and sends markers on all of its own channels. On every other incoming channel, it records whatever arrives until that channel's marker comes: those messages were in flight across the cut. It works because channels are first in, first out: the marker divides everything sent before the sender recorded its state from everything sent after.

We gave four processes a thousand units of money and let them send random amounts to each other over channels with random delays, never stopping. Then process zero started a snapshot. The recorded balances add up to seven hundred and forty-eight, and the money caught in transit on five channels to two hundred and fifty-two: exactly a thousand. A naive survey, asking each process its balance one second after the other, found seven hundred and forty-seven: money in flight was missed, and some was counted twice. Over fifty runs every snapshot was exact, and every survey was wrong. The same algorithm checkpoints the stream processors of Part 46, and detects when a distributed computation has deadlocked or finished.

4Models and consensusGraduate4 min

Every result in this part depends on two choices of model. The first is how machines may fail. A crash: the machine stops and never sends another message. Crash and recovery: it stops, then restarts with whatever it had saved on disk, which is the model Raft is designed for. Omission: some of its messages vanish. And Byzantine failure, named for Lamport's generals: the machine may do anything at all, including telling different lies to different listeners. A bug, a flipped bit in memory and a hostile operator all look like this.

The second choice is how time behaves. In a synchronous system there are known bounds on how long a message takes and how slow a machine can be, so computation proceeds in rounds, and a missing message proves a crash. In an asynchronous system there are no bounds at all, and a slow machine looks exactly like a dead one. Between them, Cynthia Dwork, Nancy Lynch and Larry Stockmeyer's partial synchrony: bounds exist but are unknown, or hold only after some unknown moment. That is the Internet on a good day. Tushar Chandra and Sam Toueg packaged timing as an oracle, a failure detector that suspects machines and may be wrong, and found the weakest one that makes consensus possible: it need only, eventually, stop suspecting one correct machine.

Now the problem itself. Each process proposes a value, and each correct process must eventually decide on one. Agreement: no two correct processes decide differently. Validity: the decision is one of the proposals, so the trivial protocol, always decide zero, is ruled out. Termination: every correct process does decide. Solve this for one value and you can solve it for a sequence: the next entry in a log, the next leader, whether a transaction commits, who holds a lock. Consensus is the core of every replicated system.

If time is kept, consensus is easy, given enough rounds. In FloodSet, each round every process sends every value it has seen to everyone, and after the last round each decides the smallest value it has seen. The difficulty is a crash part-way through a round, when some processes get the dying machine's message and others do not. We checked every crash pattern: who crashes, in which round, and exactly which messages get out first. With f crashes allowed, f rounds always have a counterexample, and f plus one rounds never do. Here is the simplest: three processes, one round. Process zero, holding the only zero, crashes after its message reaches process one but not process two. One decides zero, two decides one.

Both halves are provable. Sufficiency first. With at most f crashes in f plus one rounds, some round has no crash at all. In that clean round every live process sends its whole set to every other, so afterwards all the live sets are equal, and later rounds keep them equal: everyone sees the same minimum. Necessity was proved by Michael Fischer and Nancy Lynch, and by Danny Dolev and Ray Strong. Against any protocol that decides in f rounds, crash one process per round, each just after it has told a single other. This builds a chain of executions, each indistinguishable from the next to some correct process, running from all inputs zero to all inputs one, and somewhere along it two neighbouring executions must decide differently. So even with perfect clocks, tolerating f crashes costs f plus one rounds of messages. And without clocks it gets much worse.

5FLPGraduate5 min

The proof of Fischer, Lynch and Paterson rests on one idea. A configuration is a snapshot of everything: every process's state and every message in flight. Call it zero-valent if every way the run can continue ends in the decision zero, one-valent if every way ends in one, and bivalent if both outcomes are still possible. A correct protocol must, at some step, pass from bivalent to univalent: that step is where the decision is really made. The theorem shows that an adversary who controls only the order of message delivery, and may crash one process, can always avoid that step.

We can watch the dilemma on tiny protocols. Three processes, each with a bit; one may crash. Each sends its bit to the others, and our explorer tries every order of delivery and every crash. The first protocol waits for two values, since it cannot wait for a process that may have crashed, and decides the majority, breaking ties toward zero. Three input patterns are bivalent, and in each of them some schedule makes two processes decide differently: one hears zero and one, the other hears one and one. The second waits for all three values. It never disagrees, but if one process crashes, the others wait for ever. Wait too little and you can be wrong; wait for everyone and you can be stuck. FLP says every deterministic protocol, however clever, falls into one of these two holes.

The proof has two lemmas. The first says some starting configuration is bivalent. Line up the inputs from all zeros to all ones, changing one process at a time. The first is zero-valent and the last one-valent, so somewhere two neighbours differ. They differ only in one process's input, and if that process crashes at the very start, no one can tell them apart, so they cannot have opposite valencies after all: one of them must be bivalent. We saw three such configurations in our table. The second lemma says that from a bivalent configuration, whatever message is pending, the adversary can deliver it and still land somewhere bivalent. Otherwise there would be a critical step, and a case analysis shows that steps on different processes commute, while a step on the same process can be hidden by crashing that process. Now start bivalent and keep delivering the oldest message, staying bivalent each time. Every message arrives eventually; no one is ever silenced; and no one ever decides.

FLP is about guarantees, and there are three ways to weaken what is guaranteed. Give up determinism: flip coins. The adversary controls the schedule but cannot predict the coins, and Michael Ben-Or's protocol of 1983 terminates with probability one. Give up pure asynchrony: assume the network eventually behaves, for long enough. Dwork, Lynch and Stockmeyer showed that protocols can then be always safe, and live whenever that happens. Or add an oracle: a failure detector, which in practice is a timeout that is sometimes wrong. What nobody can have is a deterministic protocol that is always safe and always live. Paxos and Raft choose: safety always, liveness only while the network is good. That is what the five Pebbles gave up.

Here is Ben-Or's protocol at work. In each phase every process reports its value. If a majority reports the same value, a process proposes it; if more than f processes propose the same value, it decides; if it sees any proposal it adopts that value, and otherwise it flips a coin. Once enough coins agree, the next phase decides. With five processes, two of them crashed, and random delays, we ran it two thousand times. On average it decided in four rounds, three quarters of the time within five, and the longest run took twenty-seven. It never disagreed. It always terminated, eventually, but no bound on the number of rounds holds in every run, exactly as FLP requires.

6PaxosGraduate4 min

Leslie Lamport wrote Paxos up in 1989 as the legislature of an imaginary Greek island, and the parable was so baffling that the paper waited nine years to be published. Here it is plainly. Some processes propose values, and a set of acceptors, five here, vote. In phase one a proposer picks a ballot number larger than any it has used, and asks every acceptor to prepare. Each acceptor that has not promised a higher ballot promises to ignore lower ones from now on, and reports the highest-numbered proposal it has already accepted, if any. With promises from a majority, the proposer enters phase two. It must propose the value of the highest ballot reported to it; only if none was reported may it propose its own. Acceptors accept unless they have since promised a higher ballot, and a value is chosen the moment a majority have accepted it in the same ballot.

Safety is a short induction. Suppose v was chosen in ballot b. We show every accept request with a larger ballot carries v. Take such a ballot, b prime. Its proposer collected promises from some majority, and the majority that accepted v in ballot b overlaps it, because any two majorities of five acceptors share at least one. That shared acceptor reported having accepted something in ballot b or later, so the highest ballot reported to the proposer lies between b and b prime, and by the induction its value is v. The proposer is forced to propose v. So whatever happens later, and however messages are delayed, no other value can ever be chosen. The proof uses no timing assumption at all; the intersection of majorities does all the work.

Paxos is always safe, but it need not make progress. Two proposers can duel: A prepares ballot one, B prepares ballot two before A's accepts arrive, so A's accepts are refused; A prepares ballot three, which refuses B's accepts; and so on. We ran it four hundred times with one to four proposers, five percent loss, and proposers that retry the instant they are refused. With four, a value took thirty-four ballots on average. With a random pause before retrying, about four. Safety held in every run; only progress suffered, which is exactly the freedom FLP leaves. The real cure is to elect one distinguished proposer, a leader, and electing a leader needs timeouts, so it relies on the network eventually behaving.

One decision is not a system. Multi-Paxos runs one instance per slot of a log. A stable leader runs phase one once, for all future slots at once, and from then on each command costs a single round trip to a majority. Google built its Chubby lock service on this, and later Spanner. Brian Oki and Barbara Liskov's viewstamped replication, of 1988, is essentially the same protocol, found independently. But the engineers who built Chubby wrote that the gap between the paper and a working system was enormous: disk corruption, leases, snapshots, changing the set of machines, all left as exercises. Raft was designed to close that gap.

7RaftDegree4 min

Diego Ongaro and John Ousterhout designed Raft in 2014 with one explicit goal: to be understood. It decomposes consensus into leader election, log replication and safety. Every server is a follower, a candidate or a leader. A follower that hears nothing from a leader for a while times out and becomes a candidate; a candidate that gathers votes from a majority becomes leader; anyone who sees a message from a higher term steps down to follower. Time is cut into numbered terms, each with at most one leader, and every message carries its sender's term, which plays the role of Paxos's ballot. In a study with students at Stanford and Berkeley, Raft was indeed easier to learn than Paxos.

An election. The candidate increments the term, votes for itself, and asks everyone else. Each server grants one vote per term, to the first candidate that asks, and only if that candidate's log is at least as up to date as its own; we will see why. If two servers time out at the same moment, they split the votes, nobody wins, and they time out together again: FLP's endless indecision, in practice. Raft's remedy is to randomize the timeouts. We crashed the leader of five servers three hundred times and timed the election. With identical timeouts, nobody was ever elected, not even at the start. With two percent of randomness, most runs never elected a leader either, and the rest needed ten terms. With timeouts spread over a factor of two, as the paper recommends, a new leader took one term and under two hundred milliseconds.

Once elected, the leader takes commands from clients, appends them to its log, and sends them to the followers. Each square here is a log entry, labelled with the term in which a leader created it. Each AppendEntries message carries the new entries and the index and term of the entry just before them. A follower whose log does not hold that entry refuses, and the leader backs up one entry and tries again, until it finds where they agree; then the follower discards anything after that point and takes the leader's entries. This gives the log matching property: if two logs hold an entry with the same index and term, they are identical up to that point, by induction, since every append checked its predecessor. The third follower here holds two entries from term two that a deposed leader never managed to commit. They will be overwritten.

When is an entry safe? An entry is committed once the leader that created it has stored it on a majority of servers, and committed entries are applied, in order, to each server's state machine. Commitment must survive changes of leader. That is the job of the voting restriction: a server votes only for a candidate whose log is at least as up to date, and since a winner needs a majority of votes, and the entry is on a majority, some voter holds it, so the winner must too. Every committed entry is in every later leader's log. There is one subtle trap, the paper's Figure 8. A leader must not commit an entry from an earlier term just by counting replicas: such an entry can sit on a majority and still be overwritten by a later leader. It commits old entries only indirectly, by committing one of its own term after them. We planted exactly that bug in our Raft. In a thousand random fault schedules, it was exposed once: a later leader lacked an entry that had been committed. The bug is real, and random testing barely finds it.

8Our Raft, attackedIndustry5 min

Our Raft is about three hundred lines of Python, following the paper's one-page summary of the rules. Correctness is not something you can see by reading it, so we check, after every single event, the four properties the paper proves. Election safety: at most one leader per term. Log matching. Leader completeness: a committed entry is in the log of every later leader. And the one that users care about: no two servers ever apply different commands at the same position. Servers keep their term, their vote and their log across crashes, as if on disk, and forget everything else; messages are delayed, lost one in ten, and cut off by partitions.

Here is the storm from the opening again, now as each server's commit index: how many log entries it knows to be committed. In calm weather the five lines climb together, a few milliseconds apart. When the leader crashes, its line drops to zero, because the commit index is not saved to disk, and the others pause for a fifth of a second, elect a new leader and climb on. Through the partition every line is flat. The side with the old leader has only two servers, and the other side has two live servers of three, so neither has a majority of five. Raft chooses consistency over availability, exactly as Part 39's CAP theorem says something must. When the network heals, the restarted servers relearn everything from the new leader, and within a second all five lines are together again.

We ran a thousand six-second storms against correct Raft and against three versions with one rule broken each. Correct Raft: no violation in any run, with random faults or with targeted ones. A version that commits older terms' entries by counting replicas, the Figure 8 trap: broken once in a thousand. A version whose voters skip the up-to-date check: broken in eight hundred and seventy-seven, losing committed entries all over the place. A version that forgets its vote when it restarts, so it can vote twice in a term: random faults never caught it. But aim one fault, crash a voter in the instant after it votes, and eighty-seven runs elected two leaders in the same term. Testing distributed systems is a search problem, and where you look matters more than how long.

What is the log for? Fred Schneider's state machine approach, of 1990. If every replica starts in the same state and applies the same deterministic commands in the same order, every replica ends in the same state. Consensus supplies the order. Any service, a lock server, a key-value store, a configuration database, can be made fault-tolerant this way. The commands must really be deterministic: no reading the clock, no random numbers, not even iterating over a hash table whose order depends on a random seed, as Part 17's tables do. etcd, ZooKeeper and Consul are exactly this, and Kubernetes keeps its whole state in etcd.

One more trap: reads. A leader might answer a read from its own state, but it may have been deposed without knowing it, cut off by a partition while a new leader commits writes on the other side. Its answer would be stale. To be linearizable, the leader first confirms that it is still leader, with one round of heartbeats to a majority, or puts the read through the log like a write. Or it holds a lease: followers promise not to elect anyone else for some period, so the leader may answer alone until the lease runs out. That trades a round trip for an assumption about clocks. With a ten-second lease and clocks drifting by a hundred parts per million, the margin must exceed two milliseconds, which is easy, but a process paused for a long garbage collection, as in Part 15, can outlive any lease and wake up believing it still leads.

9Byzantine generalsGraduate5 min

In 1982 Lamport, Robert Shostak and Marshall Pease asked what happens when the faulty machines may lie. They told it as Byzantine generals: a commander sends an order, attack or retreat, to lieutenants, who then tell each other what they heard. Loyal lieutenants must agree, and if the commander is loyal, they must obey it. With three generals and one traitor it is impossible. On the left the commander is loyal and orders attack, but traitorous lieutenant one tells lieutenant two that the commander said retreat. On the right the commander is the traitor: it orders lieutenant one to retreat and lieutenant two to attack, and loyal lieutenant one truthfully reports: he said retreat. Lieutenant two receives exactly the same messages in both worlds, so it must act the same in both. On the left it must attack, to obey a loyal commander, so on the right it attacks too. Now apply the same argument to lieutenant one, comparing the right-hand world with one where the commander loyally orders retreat and lieutenant two is the liar: lieutenant one must retreat. On the right, the two loyal lieutenants disagree.

With more generals it works. In the oral messages algorithm, OM of m, the commander sends its value, and every lieutenant then acts as commander in a recursive OM of m minus one, to tell the others what it heard; each lieutenant decides the majority. We checked it exhaustively, letting every message a traitor sends be zero or one in every combination. Three generals with one traitor: broken, as the argument says. Four generals with one traitor, wherever it is: always agree. Four with two traitors: broken. Seven generals, two traitors and two rounds: always agree, in every strategy we tried.

The bound is exact. Necessary: if three f generals or fewer could tolerate f traitors, divide them into three groups of at most f, and let each of three generals simulate a whole group. That would solve the three-general problem with one traitor, which we just proved impossible. Sufficient: OM of f works whenever there are at least three f plus one generals, though its messages grow as n to the power f plus one. Signatures change everything: a traitor cannot forge what the commander signed, and with the digital signatures of Part 30, agreement is possible with any number of traitors. In an asynchronous network, the three f plus one bound holds for every Byzantine protocol. To survive one liar you need four machines; to survive two, seven.

Here is PBFT deciding one request, with four replicas, one of them faulty and silent. The client sends its request to the primary. The primary assigns it a sequence number and sends a pre-prepare to every backup. Each backup that accepts it broadcasts a prepare to all the others. A replica that holds the pre-prepare and matching prepares from two f plus one replicas, itself included, knows that no loyal replica can prepare a different request with this number. Then everyone broadcasts commit, and once two f plus one commits arrive, the request is executed. That second all-to-all round makes the order survive a change of primary. Each replica replies, and the client waits for f plus one identical answers, of which at least one is from a loyal replica. Faulty replica three said nothing, and nothing was lost.

Practical Byzantine protocols came much later. Miguel Castro and Barbara Liskov's PBFT, in 1999, ran a file system that tolerated lying replicas at nearly the speed of an unreplicated one. A primary orders the requests, and each passes three phases, pre-prepare, prepare and commit, each waiting for two f plus one matching signed messages, so that any two such quorums share a loyal replica. If the primary misbehaves, a view change replaces it. Every replica talks to every other, so the messages grow as n squared. HotStuff, in 2019, sends votes only to the leader, which combines them into a single threshold signature: linear messages per phase. For a hundred replicas, OM would need ten to the sixty-sixth messages, PBFT about twenty thousand, HotStuff six hundred.

10Nakamoto consensusGraduate4 min

Every protocol so far assumes we know who the participants are. Byzantine agreement needs at least three f plus one of them, which presumes counting. On an open network, where anyone can join, one attacker can pretend to be a million participants. In 2008 the pseudonymous Satoshi Nakamoto replaced identities with computation. A block of transactions counts only if its hash, Part 29's SHA-256, falls below a target, which takes on average a fixed amount of guessing to find. Votes are weighted by computing power, which cannot be faked. Every block names its predecessor, and everyone extends the chain with the most work behind it. Two miners may find blocks at once and fork the chain, but one side soon pulls ahead. A merchant trusts a payment once z blocks are built on top of it.

How safe is a payment with z confirmations? An attacker with a share q of the computing power mines a rival chain in secret, one that omits the payment, and races to overtake the honest chain. Each block found is the attacker's with probability q, a random walk biased against it, and from k blocks behind it ever catches up with probability q over p to the k. Nakamoto's paper computed the risk with a Poisson approximation. The exact answer, worked out by Meni Rosenfeld in 2014, uses the negative binomial, and our two hundred thousand simulated races agree with the exact answer, not the paper's: for a ten percent attacker and six confirmations, the risk is not two hundredths of a percent but six hundredths. For a risk of one in a thousand you need six blocks against a ten percent attacker, thirty-two against thirty percent, a hundred and thirty-three against forty. Safety here is probabilistic, and it decays exponentially with waiting.

Bitcoin's security argument assumed that a miner's best strategy is to follow the rules. In 2014 Ittay Eyal and Emin Gün Sirer showed otherwise. A selfish pool keeps the blocks it finds secret, and publishes them only to override blocks the honest miners find, so the honest work is wasted. We simulated two hundred thousand blocks at each pool size, and the results lie on their formula. On the dashed line, revenue equals hash power, the fair share. The selfish pool rises above it once it has a third of the power, or a quarter if half the honest miners side with its blocks in a tie. An honest majority is not enough. In open systems, the incentives are part of the protocol.

Open membership has a price. Bitcoin settles about seven transactions a second, one block every ten minutes, and its miners consume electricity on the scale of a mid-sized country: the cost of voting by computation. Proof of stake weights votes instead by currency deposited, which a validator caught signing conflicting blocks forfeits. Ethereum switched in 2022 and cut its energy use by more than ninety-nine point nine percent. Underneath, proof-of-stake chains run a Byzantine agreement protocol among their validators, and the bound of three f plus one returns, counted in coins rather than machines. The difference that remains is finality: Nakamoto's chain is only ever probably final, more so the longer you wait; a BFT decision is final the moment a quorum signs it.

11Frontier: proving and breakingResearch3 min

How does anyone know a distributed system is correct? There are three answers, and the field uses all of them. Check a model. Engineers at Amazon wrote specifications of S3, DynamoDB and other systems in Lamport's TLA plus, and the model checker found bugs that design reviews and testing had missed, one needing a precise sequence of thirty-five steps. Test the real thing. Kyle Kingsbury's Jepsen partitions real databases and checks the histories against linearizability, the property of Part 33, and it has found lost writes and stale reads in a long list of systems whose documentation promised otherwise. Or prove the implementation itself. In 2015 the Verdi project, in Coq, and IronFleet, in Dafny, verified working implementations of Raft and Paxos, at the cost of several lines of proof for every line of code. Our own campaign shows why the first two are hard: the Figure 8 bug surfaced once in a thousand random storms, and the forgotten vote never, until one well-aimed fault exposed it in eighty-seven.

Fifty years of lower bounds say what agreement must cost. Crash failures with clocks: f plus one rounds. Without clocks, no deterministic protocol at all. Lying machines: n at least three f plus one, unless messages are signed. And Danny Dolev and Rüdiger Reischuk proved that any deterministic Byzantine agreement must, in the worst case, send a number of messages growing as n squared. Only in 2022 did protocols for partial synchrony match that bound in the worst case. HotStuff's linear cost per leader is the good case: a run of faulty leaders makes it quadratic again, and designing protocols that are cheap when things go well and optimal when they do not is current research.

Where this leaves the field. Finding bugs efficiently: which fault schedules expose which bugs? Random search is hopeless for deep ones, and smarter strategies, guided by coverage or by which messages each result depended on, help in practice, without any theory of how many runs suffice. Verifying what actually runs: proofs cover protocols, but real systems add changes of membership, snapshots and storage that silently corrupts data, and the proofs rarely keep pace with the code. The best achievable combination of latency and message count for Byzantine agreement. And gray failure: machines that are slow, or fail only some requests, which defeat every clean model in this part. This part's research problem asks for a fault-injection strategy that finds all three of our planted Raft bugs in as few runs as possible.

Recap, problems, and where this comes backAll tracks3 min

What we built in this part. The two generals, who cannot be certain. Causality instead of time, with Lamport's clocks and vector clocks, and snapshots of a system that never stops. Consensus in f plus one rounds when time is kept, and FLP's proof that it cannot be guaranteed when it is not. Coins, failure detectors and partial synchrony as the ways around. Paxos and Raft, safe because majorities intersect, and our Raft surviving a thousand storms while its broken twins did not. And traitors: three f plus one, PBFT, HotStuff, and Nakamoto's chain of work.

Where this comes back. Part 39 replicates data at scale: quorums, two-phase commit, the CAP theorem, Spanner's atomic clocks, and the Job itself on sixteen Pebbles, one of which crashes. Part 45's Kubernetes keeps its state in etcd, which is Raft. Part 46's stream processors checkpoint with Chandy and Lamport's snapshots. And Part 54 returns to TLA plus and proofs.

In practice. Do not write your own consensus: use etcd, ZooKeeper or Consul for leader election, locks and configuration. Run three or five voters, never four, since four tolerate no more failures than three. Make election timeouts much longer than a round trip, randomize them, and beware of garbage-collection pauses. Give every lock a fencing token that the protected resource checks, or a paused holder will wake up and write. And test with injected faults, aimed at the moments that matter.

Six problems, with full solutions in the part's notes. Pause on any of them. The fifth is a build problem: add membership changes to our Raft, the part every real deployment needs, and extend the checker to cover them. The last, marked with a star, is a research problem: find a way of injecting faults that exposes all three of our planted bugs quickly, and argue that it would find bugs you have not planted.

Next time, Part 39: Distributed systems, scale. Replication and quorums, two-phase commit and why it can block for ever, the CAP theorem stated precisely, and Spanner, which buys consistency with atomic clocks. And the Job runs on sixteen Pebbles, one of which crashes in the middle: ledger row fifteen.

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

Where it goes next. Part 39 replicates data at scale with quorums, two-phase commit and Spanner's clocks, and runs the Job on sixteen Pebbles. Raft returns as etcd under Kubernetes in Part 45, Chandy and Lamport's snapshots as stream checkpoints in Part 46, and TLA+ and proofs of protocols in Part 54.

Key results

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

Vector clocks\(\displaystyle a\to b\iff V(a)<V(b)\)
Synchronous crash consensus\(\displaystyle f+1 \text{ rounds }\allowbreak \text{are }\allowbreak \text{sufficient }\allowbreak \text{and }\allowbreak \text{necessary}\)
FLP\(\displaystyle \text{asynchronous, }\allowbreak \text{one }\allowbreak \text{crash}\ \Rightarrow\ \text{no }\allowbreak \text{deterministic }\allowbreak \text{consensus}\)
Majorities intersect\(\displaystyle |Q_1|,|Q_2|>\tfrac n2\ \Rightarrow\ Q_1\cap Q_2\neq\varnothing\)
Byzantine agreement\(\displaystyle n\ge 3f+1 \quad\allowbreak \text{(without }\allowbreak \text{signatures)}\)
Nakamoto's race\(\displaystyle P=1-\sum_{k=0}^{z}\frac{\lambda^{k}e^{-\lambda}}{k!}\Bigl(1-\bigl(\tfrac qp\bigr)^{z-k}\Bigr),\ \lambda=\tfrac{zq}{p}\)

Try it

Lab 38 · Raft under attack: invariants, a planted bug, and split votes

Run five-node Raft clusters through seeded storms of crashes, restarts, partitions and message loss, and check the paper's four safety invariants after every event: correct Raft must never break one, and Raft without the voters' log check must. Then start clusters with election timeouts spread over 0%, 2% and 100% of the base timeout and count how many elect a leader within a second.

Figure produced by Lab 38: Raft under attack: invariants, a planted bug, and split votes
Produced by the lab below, seed 0, in 0.6 s.
python -m videos.cs.labs 38 needs numpy, scipy, matplotlib · download lab38.py · source on GitHub
correct Raft, 60 storms                         0 broke an invariant   (mean 94 commands committed)   the film: 0 of 1,000
votes granted without the log check, 60 storms  52 broke an invariant   the film: 877 of 1,000
invariants the bug broke (storms)               leader completeness 52, state machine safety 45
timeouts in [T, 1 T]: no leader after 1 s       60 of 60 clusters
timeouts in [T, 1.02 T]: no leader after 1 s    47 of 60 clusters
timeouts in [T, 2 T]: no leader after 1 s       0 of 60 clusters

Safety held in every storm and failed as soon as one line of the voting rule was removed; liveness is the part FLP says cannot be guaranteed, and randomized timeouts buy it with probability.
The code (85 lines; it asserts its own result)
"""Lab 38: attack the series' Raft with random storms, plant a bug, and take the randomness out of its elections."""

from videos.coursekit import labs

import numpy as np

from explainer.cs.dist.raft import Cluster, random_faults

TITLE = "Raft under attack: invariants, a planted bug, and split votes"
GOAL = ("Run five-node Raft clusters through seeded storms of crashes, restarts, partitions and message loss, and "
        "check the paper's four safety invariants after every event: correct Raft must never break one, and Raft "
        "without the voters' log check must. Then start clusters with election timeouts spread over 0%, 2% and 100% "
        "of the base timeout and count how many elect a leader within a second.")
TASKS = [
    "Plant bug='commit-old-term' (the paper's Figure 8) instead. How many of the storms expose it, and why so few?",
    "Raise the loss from 0.1 to 0.4 on correct Raft. Which changes: safety, or the number of commands committed?",
    "Run seven nodes instead of five with the timeouts spread by 0.02. Does a larger cluster split its votes more or less often?",
]
STORMS, STARTS = 60, 60
SPREADS = (0.0, 0.02, 0.1, 0.5, 1.0)


def storm(seed, bug=None):
    """One cluster, six simulated seconds, about eight faults a second, as in the film's campaign."""
    c = Cluster(5, seed=seed, loss=0.1, bug=bug, delay=(0.005, 0.08))
    random_faults(c, 6, rate=8)
    c.run(until=6, client_rate=40)
    return c


def run(seed=0):
    base = 10_000 * seed
    lab = labs.Lab()
    kinds, results = {}, {}
    for bug in (None, "no-log-check"):
        broken, committed = 0, []
        for k in range(STORMS):
            c = storm(base + k, bug)
            broken += bool(c.violations)
            committed.append(len(c.committed))
            if bug:
                for kind in {v[1] for v in c.violations}:
                    kinds[kind] = kinds.get(kind, 0) + 1
        results[bug] = (broken, np.mean(committed))
    ok, bad = results[None], results["no-log-check"]
    lab.row(f"correct Raft, {STORMS} storms", f"{ok[0]} broke an invariant   (mean {ok[1]:.0f} commands committed)   the film: 0 of 1,000")
    lab.row(f"votes granted without the log check, {STORMS} storms", f"{bad[0]} broke an invariant   the film: 877 of 1,000")
    lab.row("invariants the bug broke (storms)", ", ".join(f"{k} {v}" for k, v in sorted(kinds.items())))
    assert ok[0] == 0, "correct Raft keeps all four invariants in every storm"
    assert ok[1] > 20, "and it still commits commands between the faults"
    assert bad[0] > 0.6 * STORMS, "without the election restriction a stale candidate wins and overwrites committed entries"
    assert "leader completeness" in kinds

    leaderless = []
    for sp in SPREADS:
        none = 0
        for k in range(STARTS):
            c = Cluster(5, seed=base + k, spread=sp, delay=(0.002, 0.012))
            c.run(until=1.0, client_rate=0)
            none += not any(nd.role == "leader" for nd in c.nodes)
        leaderless.append(none)
        if sp in (0.0, 0.02, 1.0):
            lab.row(f"timeouts in [T, {1 + sp:g} T]: no leader after 1 s", f"{none} of {STARTS} clusters")
    assert leaderless[0] == STARTS, "identical timeouts: every election is a split vote, for ever"
    assert leaderless[-1] == 0, "timeouts spread over [T, 2T]: every cluster elects a leader"
    assert leaderless[1] > leaderless[-2] >= leaderless[-1], "a little randomness is not enough"
    lab.note = ("Safety held in every storm and failed as soon as one line of the voting rule was removed; liveness "
                "is the part FLP says cannot be guaranteed, and randomized timeouts buy it with probability.")

    fig, ax = labs.figure(2, size=(11, 4.2))
    names = ["correct Raft", "no log check\nwhen voting"]
    ax[0].set_axisbelow(True)
    ax[1].set_axisbelow(True)
    ax[0].bar(names, [STORMS, STORMS], color=labs.GRID)
    ax[0].bar(names, [ok[0], bad[0]], color=labs.RED)
    for k, v in enumerate((ok[0], bad[0])):
        ax[0].text(k, v + 1.5, f"{v} of {STORMS} broke an invariant", ha="center", color=labs.INK)
    ax[0].set(title="Six seconds of crashes, partitions and loss", ylabel="storms (grey: run, red: broke an invariant)", ylim=(0, STORMS * 1.15))
    ax[1].bar(range(len(SPREADS)), np.array(leaderless) / STARTS, color=labs.GOLD)
    ax[1].set(title="Clusters with no leader after one second", xlabel="spread of the election timeout (fraction of T)",
              ylabel="share of clusters", ylim=(0, 1.1), xticks=range(len(SPREADS)), xticklabels=[f"{s:g}" for s in SPREADS])
    for k, v in enumerate(leaderless):
        ax[1].text(k, v / STARTS + 0.03, f"{v}/{STARTS}", ha="center", color=labs.INK)
    lab.fig = fig
    return lab

Now change it

  1. Plant bug='commit-old-term' (the paper's Figure 8) instead. How many of the storms expose it, and why so few?
  2. Raise the loss from 0.1 to 0.4 on correct Raft. Which changes: safety, or the number of commands committed?
  3. Run seven nodes instead of five with the timeouts spread by 0.02. Does a larger cluster split its votes more or less often?

Problems, with solutions

Try each problem before opening its solution.

  1. Vector clocks. Prove that a → b iff V(a) < V(b).

    Solution

    (⇒) Along each step of a happened-before chain the vector never decreases (local steps increment one entry; a receipt takes a maximum that includes the message's vector), and the step to b's own event increments b's entry, so V(a) ≤ V(b) with V(a) ≠ V(b). (⇐) Let a be on process i, with V(a)[i] = k: a is the k-th event of i. If V(a) ≤ V(b) then V(b)[i] ≥ k. Entry i of any vector only grows by i's own events or by maxima with vectors that carried i's count along messages, so b's knowledge of "k events of i" must have travelled from i's k-th event, a, to b along a chain of program order and messages: a → b (or a = b, excluded since V(a) ≠ V(b)). Our check: 200 executions, 42,170 pairs, no exception.

  2. FloodSet. Prove that f + 1 rounds solve consensus with up to f crashes, and give a run defeating f rounds for n = 4, f = 2.

    Solution

    With f + 1 rounds and at most f crashes, some round r has no crash. In round r every process alive sends its set W to every other alive process, so after r all live processes hold the union of the live sets, the same set. Later rounds only merge equal sets (and sets of processes that crash, which are subsets of the union), so the sets stay equal; all decide its minimum, a proposed value. For f rounds: inputs (0, 1, 1, 1); in round 1, P0 crashes after sending only to P1; in round 2, P1 crashes after sending only to P2. Now P2 has seen 0 and P3 has not: P2 decides 0, P3 decides 1 (our checker's counterexample).

  3. Paxos's invariant. Prove that if v is chosen in ballot b, every accept request with ballot b′ > b carries v.

    Solution

    Strong induction on b′. The proposer of b′ received promises from a majority Q. The majority A that accepted (b, v) intersects Q in an acceptor a; a accepted (b, v) before promising b′ (it would have refused b after promising b′ > b), so its promise reported an accepted ballot c_a with b ≤ c_a < b′. Hence the highest reported ballot c satisfies b ≤ c < b′, and the proposer must use the value accepted in c. If c = b that value is v (one value per ballot); if c > b, the accept request of ballot c carried v by the induction hypothesis. So b′'s accept request carries v; and any value chosen in a later ballot was in such a request, so equals v.

  4. Three generals. Show that OM(1) fails for three generals and one traitor, and that no protocol succeeds.

    Solution

    OM(1): commander loyal sends "attack"; traitor L1 relays "retreat" to L2; L2 sees one of each and its majority with ties to retreat decides retreat, disobeying a loyal commander (our exhaustive check found this as the only strategy needed). Impossibility: suppose a protocol works. World A: commander loyal orders attack, L1 traitor behaves as if it had received retreat. World B: commander traitor tells L2 attack and L1 retreat, L1 loyal. World C: commander loyal orders retreat, L2 traitor behaves as if it had received attack. L2's view is the same in A and B, and it must attack in A, so it attacks in B. L1's view is the same in B and C, and it must retreat in C, so it retreats in B. In B the loyal lieutenants disagree: contradiction. (The same scaling argument gives n ≥ 3f + 1.)

  5. Build: membership changes. Add membership change to our Raft and extend the checker.

    Solution

    Solution sketch. The simplest safe method changes one server at a time (Ongaro's thesis, §4): a configuration entry in the log takes effect as soon as a server appends it (not when committed), and a leader will not start a second change until the first commits. Any two majorities of configurations differing by one server intersect, so election safety holds. Extend Cluster with add(i)/remove(i) as special commands, make majorities computed from the latest configuration in each server's log, and add an invariant: no two leaders in a term even across configurations. A removed leader must step down after committing its removal. Fault-inject around the moments the configuration entry is appended and committed.

  6. ★ Research: finding bugs fast. Design a fault-injection strategy that exposes all three planted bugs in few runs, and argue it generalizes.

    What is known. Our numbers: random storms found the Figure 8 bug in 1 of 1,000 runs and the forgotten vote in none; crashing voters immediately after they vote found the latter in 87 of 1,000. Approaches that work in practice: targeting the moments between persistent-state changes and messages (crash after vote, crash after append before acknowledgement); lineage-driven fault injection (Alvaro et al., 2015), which removes the messages a successful result depended on; coverage-guided search over schedules; deterministic simulation (FoundationDB) that makes every failing seed replayable. The Figure 8 bug needs a leader to replicate an old-term entry to a majority, crash, and be replaced by a leader that lacks it: a strategy that preferentially crashes a leader just after it has replicated an entry from an earlier term to a bare majority should find it far faster than random. What is open is a theory: for which classes of bugs does a strategy of bounded "depth" (Burckhardt et al.'s probabilistic concurrency testing, 2010) guarantee detection in a polynomial number of runs?

Notes and sources

Glossary

  • partial failure: some components fail while others continue; asynchrony: no bound on message delay.
  • happened-before (→): the causal order of program order and messages; concurrent (∥): neither precedes.
  • Lamport clock: a counter consistent with →; vector clock: a vector that characterizes →.
  • consistent cut, snapshot: a global state in which every received message was sent; Chandy–Lamport: markers on FIFO channels.
  • crash, crash-recovery, omission, Byzantine: failure models; synchronous, partially synchronous: timing models; failure detector: an oracle that suspects processes.
  • consensus: agreement, validity, termination; valency: which decisions remain reachable; bivalent: both.
  • FLP: no deterministic consensus in an asynchronous system with one crash.
  • Paxos: ballots, promises and majorities; Multi-Paxos: one instance per log slot with a stable leader.
  • Raft: terms, elections, log replication; log matching, leader completeness, election restriction.
  • replicated state machine: deterministic replicas fed one agreed sequence of commands; lease; fencing token.
  • Byzantine generals, OM(m); n ≥ 3f + 1; PBFT, view change, HotStuff, threshold signature.
  • Sybil attack: one party posing as many; proof of work, longest chain, confirmations, selfish mining, proof of stake, finality.
  • Jepsen, TLA⁺, model checking, deterministic simulation: ways to find distributed bugs.

Sources

  • N. Lynch, Distributed Algorithms; H. Attiya and J. Welch, Distributed Computing.
  • C. Cachin, R. Guerraoui and L. Rodrigues, Introduction to Reliable and Secure Distributed Programming.
  • M. van Steen and A. S. Tanenbaum, Distributed Systems; M. Kleppmann, Designing Data-Intensive Applications, ch. 8–9.
  • J. Gray, "Notes on Data Base Operating Systems" (1978) (the two generals).
  • L. Lamport, "Time, Clocks, and the Ordering of Events in a Distributed System", CACM (1978).
  • C. J. Fidge (1988); F. Mattern, "Virtual Time and Global States of Distributed Systems" (1988).
  • D. L. Mills, "Internet Time Synchronization: the Network Time Protocol", IEEE Trans. Comm. (1991).
  • K. M. Chandy and L. Lamport, "Distributed Snapshots", ACM TOCS (1985).
  • M. Fischer and N. Lynch, "A Lower Bound for the Time to Assure Interactive Consistency", IPL (1982); D. Dolev and H. R. Strong, "Authenticated Algorithms for Byzantine Agreement", SIAM J. Comput. (1983).
  • M. Fischer, N. Lynch and M. Paterson, "Impossibility of Distributed Consensus with One Faulty Process", JACM (1985).
  • M. Ben-Or, "Another Advantage of Free Choice", PODC (1983).
  • C. Dwork, N. Lynch and L. Stockmeyer, "Consensus in the Presence of Partial Synchrony", JACM (1988).
  • T. D. Chandra and S. Toueg, "Unreliable Failure Detectors for Reliable Distributed Systems", JACM (1996).
  • L. Lamport, "The Part-Time Parliament", ACM TOCS (1998); "Paxos Made Simple" (2001).
  • B. Oki and B. Liskov, "Viewstamped Replication", PODC (1988).
  • T. Chandra, R. Griesemer and J. Redstone, "Paxos Made Live", PODC (2007); M. Burrows, "The Chubby Lock Service", OSDI (2006).
  • F. B. Schneider, "Implementing Fault-Tolerant Services Using the State Machine Approach", ACM Computing Surveys (1990).
  • D. Ongaro and J. Ousterhout, "In Search of an Understandable Consensus Algorithm", USENIX ATC (2014); D. Ongaro, Consensus: Bridging Theory and Practice, PhD thesis (2014).
  • L. Lamport, R. Shostak and M. Pease, "The Byzantine Generals Problem", ACM TOPLAS (1982).
  • G. Bracha and S. Toueg, "Asynchronous Consensus and Broadcast Protocols", JACM (1985); D. Dolev and R. Reischuk, "Bounds on Information Exchange for Byzantine Agreement", JACM (1985).
  • M. Castro and B. Liskov, "Practical Byzantine Fault Tolerance", OSDI (1999); M. Yin et al., "HotStuff: BFT Consensus with Linearity and Responsiveness", PODC (2019); A. Lewis-Pye, "Quadratic Worst-Case Message Complexity for State Machine Replication in the Partial Synchrony Model" (2022).
  • S. Nakamoto, "Bitcoin: A Peer-to-Peer Electronic Cash System" (2008); M. Rosenfeld, "Analysis of Hashrate-Based Double Spending" (2014); I. Eyal and E. G. Sirer, "Majority Is Not Enough: Bitcoin Mining Is Vulnerable", FC (2014).
  • C. Newcombe et al., "How Amazon Web Services Uses Formal Methods", CACM (2015); K. Kingsbury, Jepsen analyses (2013–); J. R. Wilcox et al., "Verdi", PLDI (2015); C. Hawblitzel et al., "IronFleet", SOSP (2015).
  • P. Alvaro, J. Rosen and J. M. Hellerstein, "Lineage-driven Fault Injection", SIGMOD (2015).
About this partfrom its README

Part 38 of a sixty-one-part course in computer science (see the series plan and the syllabus), the third part of Act VII, Many Machines. With no shared clock and failures that look like slowness, agreeing on even one bit is provably impossible in general (FLP). Paxos and Raft agree anyway, by giving up a guarantee that FLP says no one can have. We build Raft and attack it a thousand times.

The instruments are in explainer/cs/dist/ (tested in tests/test_cs38_dist.py):

  • clocks.py: random executions; Lamport and vector clocks; happened-before by transitive closure, and the characterization theorem checked pair by pair; NTP's offset and delay; a bank of processes on FIFO channels with a Chandy–Lamport snapshot, against a naive survey.
  • consensus.py: an exhaustive explorer of tiny asynchronous protocols (every delivery order, up to f crashes) giving valency, disagreement and blocking; FloodSet checked against every crash pattern (who, which round, which messages escape); Ben-Or's randomized consensus; single-decree Paxos with several proposers, NACKs, loss and optional backoff.
  • raft.py: Raft on a simulated network (delays, loss, partitions, crash–recovery with persistent term, vote and log); the four invariants of the paper's Figure 3 checked after every event; three plantable bugs (committing old-term entries by counting, voting without the log check, forgetting the vote on restart); random and targeted fault injection; randomization of election timeouts.
  • byzantine.py: OM(m) with every lying strategy enumerated; message counts for OM, PBFT and HotStuff; Nakamoto's double-spend probability, the exact (negative-binomial) value and a simulation; Eyal and Sirer's selfish mining by formula and simulation.
Chapter notes
  • Hook. Five Pebbles run Raft for nine seconds through a crashed leader, a partition, a restart and another crash: 236 commands committed in 15 terms, every invariant holding; a new leader 0.22 s after the first crash. A thousand random storms: no violation. Lamport's definition; FLP.
  • 1. Partial failure. Partial failure, clock drift, asynchrony. The two generals (Gray 1978) as a sequence diagram; messengers needed for 99% and 99.9999% confidence (2 and 6 at 10% capture, 7 and 20 at 50%); the impossibility by induction on messages.
  • 2. Time without a clock. NTP's offset θ and delay δ; with 70 ms out and 10 ms back the estimate is 30 ms off, undetectably. Happened-before on a space–time diagram; Lamport clocks and the clock condition; vector clocks and the characterization theorem, checked on 200 executions (42,170 pairs, all exact; Lamport numbers ordered 19,143 of the 22,869 concurrent pairs).
  • 3. Snapshots. Consistent and inconsistent cuts; Chandy and Lamport's markers. A bank of four: balances 748 plus 252 in transit = 1,000; a naive survey 747; 50 of 50 snapshots exact, surveys from 610 to 1,006.
  • 4. Models and consensus. Crash, crash-recovery, omission, Byzantine; synchronous, asynchronous, partially synchronous (DLS 1988); failure detectors (Chandra and Toueg). Agreement, validity, termination. FloodSet against every crash pattern: f rounds fail, f + 1 succeed (n = 3, f = 1: 13 and 25 patterns; n = 5, f = 2: 10,401 and 23,281); the counterexample; the proofs of both directions.
  • 5. FLP. Valency. Two protocols explored exhaustively: "wait for n − f" has three bivalent inputs and can disagree; "wait for all" never disagrees and can block. The two lemmas and the theorem. Three ways around. Ben-Or on five processes with two crashed: mean 4.1 rounds, 75% within 5, longest 27 of 2,000 runs.
  • 6. Paxos. Prepare/promise, accept/accepted; the safety invariant by induction on ballots. Duelling proposers (35 ms timers, 5% loss, 400 runs each): with four proposers retrying at once 33.6 ballots and 224 ms, with random backoff 4.3 and 37 ms; always safe. Multi-Paxos, Chubby, Viewstamped Replication.
  • 7. Raft. Terms and roles; elections; randomized timeouts (identical timeouts: no leader in 300 of 300 runs; 2% spread: 249 of 300 never, 10.7 terms otherwise; [T, 2T]: 1.07 terms, median 177 ms). Log replication and log matching; the commit rule, the election restriction and leader completeness; Figure 8.
  • 8. Our Raft, attacked. The four invariants. The opening storm as commit indexes. A thousand storms each: correct Raft 0 broken (random or targeted); counting old-term entries 1; skipping the log check 877; forgetting the vote 0 with random faults, 87 with one targeted fault. Replicated state machines (Schneider 1990); linearizable reads, ReadIndex and leases.
  • 9. Byzantine generals. The three-general impossibility; OM(m) checked over every lying strategy (3 generals and 1 traitor broken; 4 and 1 always agree; 4 and 2 broken; 7 and 2 agree); n ≥ 3f + 1 by simulation; signatures. PBFT's normal case on four replicas; messages for n = 100: OM ≈ 10⁶⁶, PBFT 19,800, HotStuff 594.
  • 10. Nakamoto consensus. Sybil attacks, proof of work, the longest chain. Double-spend risk: Nakamoto's formula, the exact value and 200,000 simulated races (q = 0.1, z = 6: 0.024%, 0.059%, 0.062%); confirmations for 0.1%: 6, 13, 32, 133 against 10–40% attackers. Selfish mining on Eyal and Sirer's curve (profitable above 1/3, or 1/4 with γ = 1/2). Energy, proof of stake, finality.
  • 11. Frontier: proving and breaking. TLA⁺ at Amazon, Jepsen, Verdi and IronFleet; our campaign. Lower bounds (f + 1 rounds, FLP, 3f + 1, Dolev–Reischuk Ω(n²)); quadratic worst-case BFT in partial synchrony (2022). Four open problems.
  • 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
  1. Partial failure, no global clock, asynchrony.
  2. The two generals cannot agree over a lossy link (proved by induction on messages).
  3. Time: NTP and its limits; happened-before and Lamport clocks (1978) on space–time diagrams; vector clocks characterize causality (proved); race detectors (callback to Part 33).
  4. Chandy–Lamport snapshots (1985): consistent cuts, animated.
  5. Failure models (crash, omission, Byzantine); synchrony, asynchrony, partial synchrony (DLS 1988); failure detectors (◇S).
  6. Consensus defined; synchronous crash consensus in f + 1 rounds, with the lower bound.
  7. FLP (1985): the bivalence proof walked through (an initial bivalent configuration; the critical step).
  8. Ways around FLP: randomization (Ben-Or), failure detectors, partial synchrony.
  9. Paxos (Lamport 1989/98): prepare/promise and accept/accepted; the safety invariant (proved); Multi-Paxos.
  10. Raft (Ongaro & Ousterhout 2014): randomized elections, log replication, log matching, the commit rule, the safety argument, membership changes.
  11. Our Raft: five nodes on our network, with crashes and partitions; the logs animated; invariants checked over thousands of seeded fault schedules.
  12. Replicated state machines (Schneider 1990); linearizable reads; leases.
  13. Byzantine generals (Lamport, Shostak & Pease 1982): n ≥ 3f + 1 is necessary (the three-general proof) and sufficient; signatures; PBFT (1999); HotStuff.
  14. Nakamoto consensus (2008): proof of work, the longest chain, the double-spend probability recomputed; selfish mining; proof of stake.
  15. Checking protocols: TLA+ at Amazon (Part 54); Jepsen's findings (cited). Outro.

Computed: vector-clock causality; snapshots; FLP's valency explored exhaustively on a tiny protocol; Raft with fault injection and invariant checks; the Byzantine counterexample; PBFT message counts; Nakamoto's probabilities against Monte Carlo. Visuals: space–time diagrams with clock stamps; consistent and inconsistent cuts; Raft terms and logs lining up; configuration graphs colored by valency; a traitor sending split messages. In practice: etcd, ZooKeeper and Consul, leader election inside every distributed database, blockchains. Reading: Lynch, Distributed Algorithms; Attiya & Welch, Distributed Computing; Cachin, Guerraoui & Rodrigues, Introduction to Reliable and Secure Distributed Programming; van Steen & Tanenbaum, Distributed Systems; Kleppmann, Designing Data-Intensive Applications ch. 8–9; Lamport 1978, 1998, 2001; Fischer, Lynch & Paterson 1985; Ongaro & Ousterhout 2014; Lamport, Shostak & Pease 1982; Castro & Liskov 1999; Nakamoto 2008; Dwork, Lynch & Stockmeyer 1988; Chandy & Lamport 1985.

中文讲义

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

习题与解答
  1. 向量时钟。 证明 a → b 当且仅当 V(a) < V(b)。

    解答

    (⇒)沿 happened-before 链的每一步,向量都不会减小(本地事件给一个分量加一;接收取最大值,而最大值包含消息携带的向量), 而到 b 自身事件的那一步会给 b 的分量加一,所以 V(a) ≤ V(b) 且 V(a) ≠ V(b)。(⇐)设 a 在进程 i 上,V(a)[i] = k:a 是 i 的第 k 个事件。若 V(a) ≤ V(b),则 V(b)[i] ≥ k。任何向量的第 i 个分量只会因 i 自己的事件增长,或者因与沿消息携带了 i 的计数的向量取 最大值而增长,所以 b 对“i 的 k 个事件”的了解一定是沿着程序顺序与消息组成的链,从 i 的第 k 个事件 a 传到 b 的:a → b(a = b 的 情形被 V(a) ≠ V(b) 排除)。我们的检验:200 次执行,42,170 对事件,无一例外。

  2. FloodSet。 证明 f + 1 轮能在至多 f 次崩溃下解决共识,并对 n = 4、f = 2 给出一个击败 f 轮的运行。

    解答

    f + 1 轮、至多 f 次崩溃时,必有某一轮 r 没有崩溃。在第 r 轮,每个存活进程都把自己的集合 W 发给每个其他存活进程,所以 r 之后所有存活进程都持有存活集合的并集,是同一个集合。之后的轮次只合并相等的集合(以及崩溃进程的集合,它们都是该并集的子集), 所以集合保持相等;大家都决定它的最小值,一个被提议过的值。f 轮的反例:输入 (0, 1, 1, 1);第 1 轮 P0 只发给 P1 后崩溃;第 2 轮 P1 只发给 P2 后崩溃。此时 P2 见过 0 而 P3 没有:P2 决定 0,P3 决定 1(我们的检查器找到的反例)。

  3. Paxos 的不变式。 证明:若 v 在选票 b 中被选定,则每个选票 b′ > b 的 accept 请求都携带 v。

    解答

    对 b′ 作强归纳。b′ 的提议者收到了某个多数派 Q 的承诺。接受了 (b, v) 的多数派 A 与 Q 相交于某个接受者 a;a 在承诺 b′ 之前接受了 (b, v)(承诺 b′ > b 之后它会拒绝 b),所以它的承诺报告了一个已接受的选票 c_a,满足 b ≤ c_a < b′。于是报告中最高的选票 c 满足 b ≤ c < b′,提议者必须使用 c 中被接受的值。若 c = b,这个值就是 v(每个选票只有一个值);若 c > b,由归纳假设,选票 c 的 accept 请求携带 v。所以 b′ 的 accept 请求携带 v;之后任何选票中被选定的值都出自这样的请求,因而等于 v。

  4. 三将军。 证明 OM(1) 对三个将军、一个叛徒失败,并且没有协议能成功。

    解答

    OM(1):忠诚的指挥官发出“进攻”;叛徒 L1 向 L2 转述“撤退”;L2 各收到一个,多数(平局取撤退)决定撤退,违背了忠诚的指挥 官(我们的穷举检查只需这一种策略就找到了它)。不可能性:假设某协议可行。世界 A:指挥官忠诚,命令进攻,叛徒 L1 装作收到的是撤退。 世界 B:叛徒指挥官对 L2 说进攻、对 L1 说撤退,L1 忠诚。世界 C:指挥官忠诚,命令撤退,叛徒 L2 装作收到的是进攻。L2 在 A 与 B 中 的所见相同,而在 A 中它必须进攻,所以在 B 中也进攻。L1 在 B 与 C 中的所见相同,而在 C 中它必须撤退,所以在 B 中也撤退。在 B 中两个 忠诚的副将意见不一:矛盾。(同样的放缩论证给出 n ≥ 3f + 1。)

  5. 动手:成员变更。 给我们的 Raft 加上成员变更,并扩展检查器。

    解答

    解答要点。 最简单的安全方法是一次只变更一台服务器(Ongaro 的博士论文第 4 章):日志中的配置条目在服务器追加它时立即生效(而不 是提交时),并且在第一次变更提交之前,领导者不开始第二次变更。相差一台服务器的两个配置的任意两个多数派都相交,所以选举安全成立。 给 Cluster 加上作为特殊命令的 add(i)/remove(i),让多数派按每台服务器日志中最新的配置计算,并加一条不变式:即使跨越配置,同 一任期也不能有两个领导者。被移除的领导者在提交自己的移除后必须下台。在配置条目被追加和被提交的时刻附近注入故障。

  6. ★ 研究:快速找到错误。 设计一种故障注入策略,在很少的运行次数内暴露全部三个植入的错误,并论证它能推广。

    已知结果。 我们的数据:随机风暴在 1,000 次运行中只有 1 次暴露了 Figure 8 错误,遗忘投票则一次也没有;让投票者在投票后立即崩溃, 在 1,000 次中有 87 次暴露了后者。实践中有效的方法:瞄准持久状态改变与消息之间的时刻(投票后崩溃、追加后确认前崩溃);基于血缘的故障 注入(Alvaro 等,2015),去掉一个成功结果所依赖的消息;对调度做覆盖率引导的搜索;确定性模拟(FoundationDB),让每个失败的种子都能 重放。Figure 8 错误需要一个领导者把旧任期的条目复制到多数派、崩溃,再被一个缺少该条目的领导者取代:优先在领导者刚把旧任期条目复制 到恰好多数派之后让它崩溃的策略,应当比随机快得多。未解决的是理论:对哪些类别的错误,有界“深度”的策略(Burckhardt 等 2010 年的概率 并发测试)能保证在多项式次运行内发现它们?

Build the film

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

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

Build it
python -m videos.cs.cs38.compute
python -m unittest tests.test_cs38_dist
python tools/build.py cs38