Lecture 21 · Consensus II: Paxos in practice and replicated state machines

Distributed Systems · Lecture 21。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: CMU 15-440/640 Spring 2026, learning outcomes “consensus: majority (leader election, Paxos)” and “high availability: replication and one-copy semantics”; the readings Mazières, Paxos Made Practical, and Chandra, Griesemer and Redstone, Paxos Made Live — An Engineering Perspective. Problem set: PS4’s Paxos questions are about single-decree message sequences (Lecture 20); this lecture builds on them but answers nothing there. Sources:

  • D. Mazières, Paxos Made Practical (2007 manuscript) — the reading;
  • T. Chandra, R. Griesemer and J. Redstone, Paxos Made Live — An Engineering Perspective (PODC 2007) — the reading;
  • L. Lamport, Paxos Made Simple (2001), section 3, “Implementing a State Machine”;
  • F. B. Schneider, Implementing Fault-Tolerant Services Using the State Machine Approach: A Tutorial (ACM Computing Surveys 1990);
  • B. Oki and B. Liskov, Viewstamped Replication (PODC 1988);
  • M. Burrows, The Chubby Lock Service for Loosely-Coupled Distributed Systems (OSDI 2006);
  • D. Ongaro and J. Ousterhout, In Search of an Understandable Consensus Algorithm (USENIX ATC 2014) — Raft;
  • C. Gray and D. Cheriton, Leases (SOSP 1989).

The slides are not public; this is not a transcript. Every number not attributed to a paper comes from code/lecture21/, run on the author’s machine (Apple M4 Pro, macOS, Python 3.13 and 3.9). Everything is simulated, seeded and deterministic. Code: code/lecture21/. Reading time: ~110 minutes, plus ~2 to run the demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Explain the replicated state machine approach, and the two conditions it rests on: determinism and one agreed order.
  2. Describe Multi-Paxos: one Paxos instance per log slot, one phase 1 for all slots, a stable leader, and why skipping phase 1 is safe.
  3. Say what a new leader must do with half-finished slots (learn, carry forward, fill with no-ops), and why each step is needed.
  4. Explain client retries, why they create duplicates in the log, and where the duplicate table must live.
  5. Describe catch-up, snapshots and log truncation, and the instability caused by a replica that rejoins with a high ballot.
  6. Explain master leases: what they promise, why the leader counts from the send time, how much clock drift a margin absorbs, and what leases cost at failover.
  7. State when two configurations can have disjoint quorums, and two ways to change membership safely.
  8. Explain how Paxos Made Live tested its system, and what a randomized, seeded test can and cannot find.
  9. Compare Raft and Viewstamped Replication with Multi-Paxos.

0.2 Prerequisites and scope

  • Prerequisites:
    • Lecture 20: single-decree Paxos, its rules, P2c, and the stable-storage requirements;
    • Lecture 19: quorums, primary-backup, split brain, leases for one primary;
    • Lecture 7: leases as a cache-consistency tool;
    • Lecture 4: at-most-once RPC with a duplicate table;
    • Lecture 17: logs, checkpoints and truncation;
    • Lecture 15: deterministic replay.
  • Scope: crash-recover servers, an asynchronous lossy network, and a key-value store as the state machine. Byzantine replication (PBFT) is mentioned only in passing; Lecture 14 covered Byzantine agreement.

0.3 Section → code map

SectionIdeaDemo in code/lecture21/
§1replicated state machines01_state_machines.py
§2–3Multi-Paxos and its costs02_multipaxos.py, multipaxos.py
§4leader change, retries, duplicates03_leader_failover.py
§5catch-up, snapshots, churn, masked faults04_catch_up.py
§6reads and master leases05_leases.py
§7membership changes06_membership.py
§8testing; disk corruption07_chaos_test.py
§9Raft and Viewstamped Replication(notes only)

0.4 Notation

  • Servers S1…Sn; each is acceptor and learner for every slot, and one of them leads. Clients C1, C2, ….
  • Slot i of the log holds the command chosen by Paxos instance i.
  • Ballot n: a proposal number, unique per server: attempt k of server i uses n = 10k + i, as in Lecture 20.
  • Messages: the course’s names with a slot number added:
    • Prepare(n, from i) asks for promises on every slot ≥ i at once;
    • Promise(n, report) lists, for each slot ≥ i, either “chosen v” or AlreadyAccepted(nk, ak);
    • PleaseAccept(n, slot i, v) and Accept_OK(slot i) are phase 2 for slot i;
    • NAK(Np) is a refusal;
    • Decide(slot i, v) tells the learners that slot i is chosen.
  • Applied index: the highest slot a server has executed. It executes slots in order, so all slots below it are done.

1. The replicated state machine (demo 01)

1.1 The idea

A service is a state machine: it has a state (a key-value store, a lock table, a file system’s metadata), it receives requests, and each request changes the state and produces a reply. Schneider’s tutorial makes the classical observation: start several copies of a deterministic state machine in the same state, give them the same requests in the same order, and they go through the same states and produce the same replies. Any of them can then answer, and any minority of them can crash without losing anything.

The idea reduces replication to two conditions:

  1. Determinism: a request’s effect may depend only on the state and the request.
  2. One agreed order of requests at every replica.

Both look easy. Neither is.

1.2 Order matters (demo 01 Part A)

Four commands on a small store {x: 1, y: 0, log: ”}: incr x, double x, y := x, log += 'd'. Their 24 orders lead to 6 different final states. Only 3 of the 6 pairs commute: the three pairs with the command that touches only log. incr x then double x gives x = 4, the other way x = 3.

Commutativity is a real optimization: commands on different keys commute, and some systems (Generalized Paxos, EPaxos, CRDTs in Lecture 22) exploit it. But in general a replica cannot apply commands in whatever order they arrive.

1.3 Determinism matters (demo 01 Part B)

The same four-entry log on three replicas, with two nondeterministic commands: stamp t (store the local clock) and token id (store a random number). The clocks differ by a few milliseconds and each replica has its own random generator. Result: 3 different states on 3 replicas, although every replica executed the same log in the same order.

Mazières’ fix, from Paxos Made Practical §2, splits execution in two:

  • choose(request) runs on one replica, the primary, and picks every nondeterministic value: the timestamp, the random number, the file’s modification time;
  • the chosen values travel in the log entry;
  • execute(request, extra) runs on every replica and uses them.

Demo 01: 1 state on 3 replicas. Real servers hide nondeterminism in many places: the time, random numbers, thread scheduling, hash-table iteration order, the amount of free memory, a timeout firing. Every one of them has to be either removed or decided once and logged. This is the same discipline as deterministic replay in Lecture 15.

1.4 Why the order needs agreement (demo 01 Part C)

Why not let every client send its command to every replica? Three clients each send four appends to all three replicas, which apply them in arrival order:

how commands reach the replicasruns with replicas that differ (of 300)
broadcast, each client every 2 ms300
broadcast, each client every 10 ms183
broadcast, each client every 50 ms38
Multi-Paxos log0
Multi-Paxos log, leader crashes mid-run0

The race needs two commands from different clients sent within the latency spread (2 ms here), so sparse traffic makes it rarer but never removes it. Lecture 1’s demo 04 cured it with a single sequencer, which works until the sequencer fails. Choosing “the command in position i” despite failures is a consensus problem, one per position. The rest of this lecture builds that.


2. From one value to a log: Multi-Paxos

2.1 One instance per slot

Lamport’s §3 makes the step explicit. Run a separate instance of Paxos for each slot of a log: instance 1 chooses the first command, instance 2 the second, and so on. Each server applies slot i only after slots 1…i − 1. Since Paxos chooses one value per instance and every server applies the same values in the same order, the replicas stay identical.

Each instance is exactly Lecture 20’s protocol, with the slot number added to every message. In particular an acceptor keeps, per slot, the highest-numbered proposal it accepted, (na, va), on stable storage.

2.2 One phase 1 for all slots

Running both phases for every slot costs two round trips and two forced writes per command. Lamport’s observation is that phase 1 does not depend on the value, so it can be done for all slots at once:

  • A server that wants to lead picks a ballot n and sends Prepare(n, from i): “promise me n for every slot from i on.”
  • An acceptor keeps one promise Np for all slots. If n > Np it sets Np := n and answers with a report covering all slots ≥ i:
    • for slots it knows are chosen, the chosen value;
    • for the others, its AlreadyAccepted(nk, ak).
  • With a majority of promises, the new leader knows, for every slot, what P2c allows it to propose (§4). From then on it runs only phase 2 for each new command, with the same ballot.

Lamport describes the result as a “distinguished proposer” that is also the distinguished learner, and calls it the leader. In the steady state a command costs one round trip from the leader to a majority, and one forced write per acceptor.

2.3 Why skipping phase 1 is safe

The leader skips phase 1 for slot 47 because its earlier Prepare(n, from 1) already covered slot 47. Every acceptor that promised n will refuse any lower-numbered proposal in slot 47, and promised n’s majority reported everything accepted in slot 47 before that promise. The argument of Lecture 20 §4 applies slot by slot.

Paxos Made Live states the important consequence: any server can still try to become leader at any time by sending a Prepare with a higher number. Nothing in the protocol relies on there being one leader. The stable leader is a performance optimization; safety comes from the ballots. Two servers that both believe they lead cannot both get a value chosen in the same slot, because the one with the lower ballot gets NAKs from the majority that promised the higher one.

2.4 The pieces of multipaxos.py

The demos run on a replicated key-value store with three operations: put, append(key, token) (which appends a unique token to a tuple) and get. The tokens let the checker detect lost and duplicated operations. Its parts, each explained in a later section:

piecewhat it does§
electiona follower that hears no heartbeat for a random 50–100 ms campaigns with a higher ballot4
takeoverlearn chosen slots, carry accepted values forward, fill gaps with no-ops4
normal casePleaseAccept(n, slot, v) to all, chosen at a majority, Decide to the learners3
diska forced flush takes disk_ms; writes that arrive during a flush share the next one (group commit)3
clientsretry with the same request id; a duplicate table in the replicated state4
catch-upheartbeats carry the leader’s applied index; a lagging server fetches entries or a snapshot5
readsthrough the log, from the leader’s memory, or under a master lease6
disk lossa server that lost its disk rebuilds as a non-voting member8
ghostchecks every safety property after the run8

3. The normal case and what it costs (demo 02)

3.1 A trace

Three servers; S1 is elected and then runs two client commands (delivered messages, 1–3 ms links):

 0.00 ms  S1 -> S1: Prepare(11, slots >= 1)        3.80 ms  S2 -> S1: Promise(11, {null})
 1.27 ms  S1 -> S2: Prepare(11, slots >= 1)        4.21 ms  S3 -> S1: Promise(11, {null})
 2.69 ms  S1 -> S3: Prepare(11, slots >= 1)
12.30 ms  C1 -> S1: Request(#1 append(x, a1))
12.30 ms  S1 -> S1: PleaseAccept(11, slot 1, C1#1 append(x, a1))     12.30 ms  S1 -> S1: Accept_OK(slot 1)
13.49 ms  S1 -> S3: PleaseAccept(11, slot 1, ...)                    14.55 ms  S3 -> S1: Accept_OK(slot 1)  <- majority
14.88 ms  S1 -> S2: PleaseAccept(11, slot 1, ...)                    16.41 ms  S1 -> S2: Decide(slot 1, ...)
19.11 ms  C1 -> S1: Request(#2 append(x, a2))   ... the same exchange for slot 2, with no Prepare

The client’s two commands were answered after 7.2 and 6.5 ms, including its own round trip to S1. The second command needed no phase 1.

3.2 Messages, writes and round trips per command (demo 02 Part B)

One client issues 60 appends back to back. The per-command costs are:

serversprotocolPrepares / cmdPaxos messages / cmdforced writes / cmdmedian latency
3phase 1 + 2 in every slot3.014.16.010.9 ms
3stable leader0.18.13.07.9 ms
5phase 1 + 2 in every slot5.024.110.011.6 ms
5stable leader0.114.25.17.9 ms

These match the counting of Lecture 20’s exercise 5:

  • Basic Paxos per slot: n Prepare + n Promise + n PleaseAccept + n Accept_OK + (n − 1) Decide = 5n − 1 messages, and 2n forced writes;
  • Multi-Paxos: 3n − 1 messages and n forced writes, one per acceptor. Paxos Made Live (§4.2) reduces its own count of five writes per instance in the same way, to one write per replica.

The latency falls by one round trip. The stable leader’s price is a stream of heartbeats: 1,000 messages in 5 s here, whether or not there is work.

3.3 The disk sets the pace (demo 02 Part C)

On a local network the round trip is a fraction of a millisecond. A forced write to disk is milliseconds: ~3 ms for a durable 64-byte write on this machine (Lecture 20, demo 05). So in a data center the disk, not the network, sets the latency. Paxos Made Live says as much: disk flushes can dominate when replicas are close together.

Demo 02 Part C: 5 servers, one-way latency 0.1–0.3 ms, a 2 ms flush, and closed-loop clients (each sends its next command when the previous one is answered). Each cell is throughput, then median latency.

leader policy1 client5 clients20 clients50 clients
one slot at a time, one command per slot295/s, 2.8 ms418/s, 11.9 ms410/s, 47.5 ms393/s, 118.8 ms
up to 16 slots in flight (pipelining)295/s, 2.8 ms1,247/s, 4.0 ms3,989/s, 4.1 ms3,972/s, 12.0 ms
one slot at a time, all queued commands in it (batching)295/s, 2.8 ms1,051/s, 4.7 ms4,201/s, 4.7 ms10,501/s, 4.7 ms
pipelining + batching295/s, 2.8 ms1,247/s, 4.0 ms4,489/s, 4.0 ms9,472/s, 5.9 ms

Three lessons:

  1. One slot at a time caps throughput at about one flush plus one round trip per command. That is ~418/s here, however many clients come; they just queue, and latency grows to 119 ms with 50 clients.
  2. Pay the disk per flush, not per command. Two mechanisms share each flush among many commands:
    • batching puts many commands into one slot;
    • pipelining keeps many slots in flight, and the disk’s group commit writes their acceptances in one flush. Batching reached 10,501 commands/s at 50 clients while keeping the latency at 4.7 ms. Paxos Made Live reports the same effect on Chubby (its Table 1): 91 operations/s with one worker, 490 with 10 and 640 with 20, gains it attributes to batching.
  3. Each technique has its own ceiling. Pipelining flattens at the window: 16 slots per flush plus round trip, ~4,000/s. Combining both was slightly slower than batching alone (9,472/s against 10,501/s). With free slots in its window, the leader proposes commands as they arrive, in smaller batches, and pays more flushes. This model charges nothing for message size or CPU time, which limit real batches.

4. When the leader changes (demo 03)

4.1 What the new leader must do

A leader can die at any moment. At that moment its slots are in every possible state, and the new leader’s phase 1 must sort them out. Demo 03 Part A builds the hardest case on purpose:

  • S5 is cut off from the start, so it knows nothing;
  • S1’s PleaseAccept for slot 12 reaches nobody but S1;
  • the Accept_OKs for slot 13 never reach S1, so slot 13 is chosen but nobody knows it;
  • S1 crashes at 80 ms, and S5 is reconnected and campaigns at once.
slotstatus when S1 crashedfinal entry
10, 11chosen; known to the survivorsC3#4, C1#4
12accepted by S1 onlyno-op
13chosen; nobody knows itC2#4 append(x, C2.4)
14chosen; known to the survivorsC1#5
15not proposed yetC2#5

S5’s phase 1 (ballot 15) finished 5 ms after the crash. With a majority of promises it did three things:

  1. Learned 12 slots that some promise reported as chosen.
  2. Carried forward 1 accepted value. Slot 13 was chosen, but every promise reported it only as AlreadyAccepted(11, C2#4 …). By P2c, applied slot by slot, S5 had to propose exactly that value, and did, so the chosen value survived although nobody had known it was chosen.
  3. Filled a gap with a no-op. Slot 12 was reported by no promise: only the dead S1 had accepted it. So it cannot have been chosen, since any majority that chose it would intersect S5’s majority. S5 proposed a no-op there. The command S1 had placed in slot 12 (C3#5) was not lost: its client timed out, retried, and the command ended up in slot 27.

Why fill the gap at all? Because no replica can apply slot 13 before slot 12. Lamport makes this point: the new leader proposes no-ops for missing slots so that execution can proceed past them. Part C below shows what happens otherwise.

4.2 How long is the service down? (demo 03 Part B)

The outage after a leader crash is roughly the election timeout plus one phase 1 plus one round trip. A short timeout shortens the outage, but under message loss it also replaces healthy leaders:

election timeoutoutage after a crash: medianworst of 40needless leader changes in 5 s (no crash, 20% loss)
20–40 ms43 ms57 ms38.4
50–100 ms80 ms106 ms0.3
150–300 ms199 ms248 ms0.0
400–800 ms485 ms633 ms0.0

With heartbeats every 10 ms and 20% loss, a 20–40 ms timeout expires after 2 to 4 heartbeats in a row are lost, which happens often. Every needless election costs a phase 1 and stalls the pipeline. Paxos Made Live describes the production version of this failure. Its first release starved key threads under load, which caused timeouts and rapid master failovers. Large numbers of clients then migrated to the new master, overwhelmed it, and caused more failovers.

4.3 Which takeover rule matters? (demo 03 Part C)

The same scripted crash, with one rule broken at a time:

takeoverslots with 2 values chosenacknowledged appends lostops never answered
correct: phase 1, carry forward, no-ops for gaps000
skip_phase1: the new leader starts after the slots it knows13120
no_noop: phase 1 done, gaps left empty003
  • Skipping phase 1 is a safety bug. S5 knew nothing, so it started proposing in slot 1, over slots that were chosen long ago and whose clients had been answered: 12 acknowledged appends vanished.
  • Leaving gaps is a liveness bug. Nothing was lost, but no replica could apply past slot 11, so every client waited forever.

4.4 Clients, retries and duplicates (demo 03 Part D)

A client cannot tell a slow leader from a dead one. So it retries: after a timeout it sends the same request (same client id, same request id) to another server. A redirect from a follower names the leader it knows. Retrying is what lets clients survive a failover; in Part D 589 requests were retried across 200 runs.

Retries put duplicates into the log. Suppose the old leader got the command chosen in slot 30 but crashed before replying. The new leader carries slot 30 forward, and the client’s retry arrives and is proposed again in slot 41. Both slots hold the command. In 200 runs with a leader crash at a random moment:

state machineruns with a command executed twiceextra executions
no duplicate detection1420
duplicate table (client → last request id, result)00

Two points about where the table lives:

  • It must be part of the replicated state, updated by execute on every replica. A table kept only at the leader dies with the leader, which is exactly when it is needed. Mazières says so directly: each cohort records the result of the last operation executed for each client, in case the reply was lost and the primary then failed. This is Lecture 4’s at-most-once RPC moved inside the state machine.
  • Request ids must increase per client. Then one entry per client suffices, and a slot holding an older id than the table’s is a stale duplicate that is skipped.

Chubby needed one more mechanism of this kind, epoch numbers (Paxos Made Live §5.3). A request had to fail if the master lost and regained its role while handling it. Every database operation therefore carries a guard on a replicated “epoch” entry that changes with every change of master.


5. Catch-up, snapshots, and the replica that comes back (demo 04)

5.1 Catching up

A replica that was partitioned, crashed or slow misses Decide messages, and its applied index stalls. In multipaxos.py the leader’s heartbeats carry the leader’s applied index. A follower that has been behind for 30 ms asks: CatchUp(from slot i). The answer is the missing chosen entries, or, if the leader has truncated them, its snapshot plus the entries after it. Paxos Made Live’s replicas do the same, and use the same mechanism to help a replica that recovers from a crash.

5.2 The replica that comes back with a higher ballot (demo 04 Part A)

A first surprise. S5 is cut off from all servers for a while, then reconnected:

leasessnapshotscut off forslots behindS5 caught up viaafterleader changeslongest pause in replies
nonone50 ms1830 log entries36.5 ms08 ms
nonone1,000 ms374S5’s own phase 150.5 ms151 ms
yesnone1,000 ms370385 log entries46.0 ms09 ms
yesevery 251,000 ms370snapshot + 20 entries46.0 ms09 ms

While cut off, S5 hears no heartbeats, so it keeps starting elections that cannot succeed, each with a higher ballot. When it comes back, its ballot is higher than the leader’s:

  • its Prepare wins promises from servers that have promised less;
  • a NAK to the leader’s heartbeat deposes the leader.

S5 becomes leader through its own phase 1, and the service pauses. Nothing is lost, because phase 1 recovers everything, but it is a needless leader change. Paxos Made Live §5.2 describes exactly this “master churn” under intermittent network outages. A disconnected replica can raise its sequence number, reconnect, replace the master, disconnect again, and repeat.

Their cure has two parts, both in multipaxos.py’s lease mode (§6):

  • Leases: while a lease runs, replicas, the master itself included, ignore Paxos messages from anyone else, so S5’s Prepare is ignored.
  • Boosting: the master periodically runs a full phase 1 to raise its own sequence number; they say this happens in under 1% of instances in a loaded system. Here the leader boosts when a NAK reveals a higher ballot: it outbids the number instead of resigning.

With leases S5 catches up as a follower, and replies never pause more than 9 ms. Raft has the same problem and solves it the same way, with a “pre-vote” and a check that the leader still hears from a majority (§9).

5.3 Snapshots (demo 04 Parts A, B)

Without truncation the log grows forever. That has two costs, which Paxos Made Live names: unbounded disk space, and unbounded recovery time, since a restarting replica replays everything. The fix is a snapshot: a serialized copy of the state machine at some slot s, after which slots ≤ s can be deleted.

snapshots (Part A)biggest log after ~630 slots
none1,274 entries
every 25 slots24 entries
snapshots (Part B)S2 restarts: slots replayed from its own log
none266
every 100 slots66
every 10 slots6

Paxos Made Live §5.5 lists what makes snapshots harder than they look:

  • Only the application can take them. The Paxos layer knows nothing about the data structure, so the application takes snapshots and tells the framework.
  • Each snapshot comes with a handle recording the slot it corresponds to and the group membership at that slot, so that snapshot and log stay mutually consistent.
  • Snapshots must not freeze the replica. They are taken in three phases (get a handle, snapshot in the background, inform the framework), and a shadow data structure absorbs updates meanwhile.
  • The log is truncated only after a snapshot is known to be good, so a failed snapshot costs nothing.
  • A replica that is far behind needs a snapshot from a peer, and that peer may already have moved on to a newer one.

In demo 04 a replica whose missing slots were truncated got the leader’s snapshot plus the entries after it: 370 slots of catch-up in 46 ms. Snapshots are not synchronized: each replica decides on its own when to take one.

5.4 Faults that fault tolerance hides (demo 04 Part C)

Paxos Made Live tells of a five-replica cell started with one replica’s name misspelled in the group. The four correct replicas made progress. The fifth kept running in catch-up mode and also looked fine. But the cell tolerated one failure instead of two. Demo 04 reproduces it: S5 receives everything, but its votes are lost.

configurationreplicas up to datereplicas whose votes arriveops done 0–300 ms300–600 ms (S3 down)600–1500 ms (S3, S4 down)
all 5 correct5 / 55 / 5111114314
S5 misnamed5 / 54 / 51061082

A health check that asks “is every replica up to date?” says 5/5, because S5 still learns every decision. Only a check that asks “whose votes are actually arriving?” sees 4/5. The general lesson: fault-tolerant systems mask faults, including their own misconfigurations, so monitoring must measure the margin left, not just whether the service works. The paper says the authors have no way of knowing what other such problems fault tolerance is masking.


6. Reads and master leases (demo 05)

6.1 Three ways to read

A get changes nothing. Must it go through Paxos?

  1. Through the log: the read takes a slot like any command. It is correct, since it is ordered after every write chosen before it, but it costs a round trip to a majority and a forced write.
  2. From the leader’s memory: fast, but wrong. A leader that has been deposed may not know it.
  3. Under a master lease: from the leader’s memory, but only while a majority has promised not to help anyone else become leader.

Demo 05 Part A shows why the second is wrong. S1 leads; at 100 ms it is cut off from the other servers and from the writing client C1, but the reading client C2 can still reach it.

read policyanswered by S1 after the cutS1’s last answerSTALE reads
through the log0—0
leader’s memory2011,395 ms after the cut187
leader’s memory under a lease24169 ms after the cut0

S2–S5 elected a new leader, which acknowledged C1’s appends. S1, alone, kept serving its frozen state; the first stale read came 102 ms after the cut. With reads through the log, S1 could not complete a slot without a majority, so C2 timed out and moved to the new leader.

6.2 What a lease promises

Paxos Made Live §5.2 defines it. As long as the master holds the lease, no other replica can get a value chosen, so the master’s local copy is up to date and can serve reads locally. In their implementation all replicas implicitly grant a lease to the master of the previous instance, and refuse Paxos messages from anyone else while the lease runs. The master renews it with periodic heartbeats; in production masters held leases for days.

Two details make it safe in multipaxos.py:

  • Count from the send time, and shorten. A follower’s promise runs for L on its clock from when it received the heartbeat. The leader’s lease runs for L(1 − margin) on its clock from when it sent that heartbeat. The send precedes the receipt, so the leader’s lease ends first unless the clocks run at very different rates. Paxos Made Live gives the master a shorter timeout than the replicas, to protect against clock drift.
  • A new leader must catch up before serving lease reads. It may serve local reads only after applying every slot its phase 1 found. Otherwise its own state could miss a write that the previous leader acknowledged. Raft does the equivalent by committing a no-op at the start of each term.

In Part A, S1 gave its last lease read 169 ms after the cut, and the new leader took over at 196 ms. The others had to wait for the leases they had granted to run out.

6.3 How much drift can a margin absorb? (demo 05 Part C)

Suppose the leader’s clock runs slow by a fraction ρ and the followers’ fast by ρ. The leader’s L(1 − m) local milliseconds then last L(1 − m)/(1 − ρ) real milliseconds, while a follower’s L lasts L/(1 + ρ). For the leader’s lease to end first we need (1 − m)/(1 − ρ) ≤ 1/(1 + ρ), that is

m  ≥  1−1−ρ1+ρ  ≈  2ρ.m \;\ge\; 1 - \frac{1-\rho}{1+\rho} \;\approx\; 2\rho .

Demo 05 cuts the leader off and measures the time during which two servers both believed they held the lease (lease 200 ms, 20 runs each):

clock driftlease marginS1 stops servingnew leader servesruns with two lease holdersworst overlap
0%0%190 ms204 ms0 / 200
5%0%200 ms194 ms20 / 207.8 ms
5%10%179 ms194 ms0 / 200
10%0%212 ms184 ms20 / 2029.2 ms
10%10%190 ms184 ms18 / 207.0 ms
10%20%168 ms184 ms0 / 200

The bound held exactly. Every configuration with m ≥ 1 − (1 − ρ)/(1 + ρ) (10% for 5% drift, 18% for 10%) never had two lease holders. The three without enough margin had overlaps in 58 of their 60 runs. During an overlap, a stale read is possible.

The drift rates here are exaggerated: quartz clocks drift by about 10⁻⁴. But a paused process (garbage collection, a virtual machine being migrated, a swapped-out page) behaves like a clock that stopped. That is how real lease bugs happen, and why margins are generous.

6.4 What leases cost (demo 05 Part B)

policyread latency (median)outage after a leader crash: medianworst
reads through the log, no lease8.84 ms79 ms106 ms
lease 60 ms4.03 ms83 ms103 ms
lease 200 ms4.03 ms215 ms246 ms

Lease reads cost one client round trip (4 ms) instead of a Paxos round plus a 1 ms flush. Since reads dominate most workloads (Chubby’s did), this matters. But the lease sits on the critical path of failover: after a crash, nobody can take over until the dead leader’s lease has run out. A lease shorter than the election timeout costs almost nothing extra (83 against 79 ms); a long one costs its full length.

Mazières (§6) describes the same optimization for read-only operations: a majority of backups promises not to form a new view for, say, 60 seconds. Paxos Made Live notes that leases could be extended to all replicas, letting any replica with a lease serve reads; they had studied this but not built it.


7. Changing the membership (demo 06)

7.1 Why it is hard

Machines are replaced, added for capacity, retired. The set of servers, the configuration, must change while the service runs. Mazières lists the questions the literature leaves open. Does “a majority” mean a majority of the old set, of the new set, or of both? How do you know it is safe to agree on a new set? Will the new set have all the state? What about operations in progress? Paxos Made Live agrees: group membership with basic Paxos is simple, but with Multi-Paxos and disk corruption the details are subtle, unpublished and unproven, and they had to fill the gaps themselves.

The danger is simple to state. Paxos is safe because any two quorums intersect. During a change, some servers may already use the new configuration while others still use the old one. If a quorum of the old and a quorum of the new can be disjoint, two values can be chosen.

7.2 When can they be disjoint? (demo 06 Part A)

Demo 06 enumerates every pair (majority of old, majority of new) for 17 changes. The exact rule, checked against the enumeration in all 17 cases:

A majority of the old configuration and a majority of the new one can be disjoint exactly when the two majority sizes fit side by side into the servers involved: ⌊|old|/2⌋ + 1 + ⌊|new|/2⌋ + 1 ≤ |old ∪ new|.

changeservers involvedmajority sizesdisjoint pairs
3 → 4 (add 1)42 + 30 / 20
3 → 5 (add 2)52 + 33 / 64
3 → 3 (replace 1)42 + 22 / 16
4 → 6 (add 2)63 + 40 / 110
5 → 7 (add 2)73 + 410 / 1,024
5 → 5 (replace 2)73 + 324 / 256

Adding or removing one server never allows it (6 of 6 such cases). Going from 2k + 1 to 2k + 2 servers, for example, the majorities are k + 1 and k + 2, out of 2k + 2 servers involved: they cannot fit side by side. Replacing one server by another allows it for odd sizes (3 → 3: 2 + 2 ≤ 4 servers involved; 5 → 5: 3 + 3 ≤ 6), but not for 4 → 4 (3 + 3 > 5). Even sizes behave differently in other cases too: 4 → 6 is safe (3 + 4 > 6), while 5 → 7 is not (3 + 4 ≤ 7).

7.3 Two configurations at once (demo 06 Part B)

Lecture 20’s Paxos with two proposers: S1 still uses {S1, S2, S3}, while the newcomer S5 already uses {S1, …, S5}. Both propose at time 0:

reconfigurationtwo values chosen: 1–3 ms everywheretwo sites ({S1, S2} | {S3, S4, S5})
each server switches when it hears1 / 300299 / 300
new-config servers need a majority of old AND of new0 / 3000 / 300
{S1, S2, S3} → {S1, S2, S3, S4}: one server added0 / 3000 / 300

With uniform latency the bug almost hid (1 in 300): each proposer’s messages usually reached the other’s quorum in time. With the two groups in different data centres it chose two values almost every time. That is exactly the kind of bug that passes tests and then fails in production.

7.4 Three safe ways

  1. The configuration is part of the replicated state, effective later (Lamport, end of §3). A command in the log changes the configuration. The configuration chosen in slot i governs slot i + α, so every server agrees which configuration rules each slot. The leader may have at most α slots in flight, so pipelining is bounded by α.
  2. Majorities of both while changing. Mazières’ view change forms a new view only when it is accepted by a majority of the old view and a majority of the new one. Raft’s joint consensus requires the same for every decision during the transition. Demo 06: 0 disjoint pairs in all 17 cases.
  3. One server at a time (Raft’s simpler scheme), which by §7.2 never allows disjoint majorities. Even this simple scheme had a bug in its first published form, when changes overlap with leader changes; Ongaro reported it in 2015 on the Raft mailing list. The fix is that a new leader must commit an entry of its own term before it starts a configuration change.

Mazières adds two refinements:

  • the view manager may conscript cohorts that wanted to leave, to make sure the new view contains someone who knows all committed operations;
  • a witness, a machine that votes but stores no state, lets two full replicas survive a failure.

8. Testing what you built (demo 07)

8.1 What Paxos Made Live learned

The authors found that their implementation ran to several thousand lines of C++, against a page of pseudo-code. Proofs that work for one page did not scale to that. Their remedies:

  • State machines in a specification language. The core algorithm was written as two explicit state machines in a small language, compiled to C++. When the membership algorithm had to change late in the project, the change took about an hour, and updating the tests took three days.
  • Runtime consistency checks. The master periodically puts a checksum request into the log. Every replica checksums its database at that point in the log, and the replicas compare. This found three inconsistencies in production: one operator error, one unexplained (possibly a hardware memory error), and one suspected wild write by unrelated code.
  • Randomized, repeatable tests. One test simulates a random number of replicas through random network outages, message delays, timeouts, crashes, recoveries, file corruptions and schedule interleavings. Everything is driven by one seed, and runs single-threaded so that a seed reproduces a run exactly. Each test runs in a safety mode (consistency required, progress not), then stops injecting failures and switches to a liveness mode (everything must complete). They left known bugs in on purpose to check that the test found them, and ran it on several hundred machines; some bugs took weeks of simulated time at very high failure rates to show up.

multipaxos.chaos(seed) follows the same recipe:

  • 1.5 s of random faults (crashes, recoveries, pairwise partitions and heals, message loss, and disk erasures);
  • then every fault is repaired and the system gets 2 s more;
  • safety is checked over the whole run, liveness at the end.

8.2 The correct system, and the planted bugs (demo 07 Parts A, B)

The correct system passed every run: 0 unsafe and 0 stuck in 4 configurations × 200 seeds, including disk loss with 3 servers under harsh faults. During development a further 2,000 runs under aggressive settings were also clean.

The planted bugs were found in very different numbers of seeds:

bugnormal faults (of 200 seeds)harsh faults (20% loss, faults every 15 ms)
skip_phase1118 unsafe, 130 stuck177 unsafe, 200 stuck
out_of_order (apply slots as learned)173 unsafe200 unsafe
no_dedup162 unsafe193 unsafe
no_noop1 stuck16 stuck
local reads, no lease1 unsafe2 unsafe
no rebuild rule after disk loss9 unsafe, 1 stuck76 unsafe
rebuilding mark not on disk1 unsafe44 unsafe
  • Bugs on frequent paths show up in most seeds. Every leader change exercises skip_phase1; every concurrent pair of decisions exercises out_of_order.
  • Bugs on rare paths show up in under 10% of seeds at the normal fault rate. A test run that happens to pass says little about them. Harsher faults raise most of them by 5–40×.
  • Stale local reads stayed rare (2 of 200). They need a leader cut off from every other server while a client still reaches it, a shape that random pairwise partitions seldom build. Demo 05’s targeted scenario hit it at once. Random testing complements thinking about specific scenarios; it does not replace it.

A failing seed is a complete bug report. Seed 18 replays the same 27 faults, including disk losses of S2 at 501 ms, S4 at 534 ms and S5 at 910 ms, and the same violation, every time.

8.3 Disk corruption, and two bugs this test found in the course’s own code

Paxos assumes that stable storage keeps its promises. Paxos Made Live met disks that did not: files changed (caught with checksums) or disappeared, for example erased by an operator. A replica that has lost its disk may renege on promises it made earlier, which breaks Paxos.

Their rule: a replica that knows it has lost its disk (Chubby leaves a marker in GFS) rejoins as a non-voting member. It catches up, but sends no promises and no acknowledgments, until it has observed one complete Paxos instance that started after it began rebuilding. Without the rule, demo 07 found violations in 9 of 200 seeds (76 under harsh faults). Seed 18’s verdict: 17 slots with two values chosen, 10 acknowledged appends lost.

Implementing the rule took three attempts. The chaos test caught both mistakes:

  1. The rebuilding mark lived in memory. A server that crashed again while rebuilding came back as an ordinary voter with an empty disk. This failed in 2 of 300 seeds. Chubby’s marker lives outside the replica for exactly this reason.
  2. Rebuilding ended too early. The server left the non-voting state as soon as it heard that a post-loss slot was chosen, before it had caught up on the older slots. Over time, three of the four servers that had chosen slot 8 lost their disks. The next leader’s majority then held no record of slot 8, and filled it with a no-op. This failed in 1 of 300 seeds. The rule must mean “caught up through a complete instance that started after the loss”.

Both were one-in-a-hundred bugs in about forty lines of code, in a mechanism the paper describes in one paragraph. The paper’s conclusion, that there are significant gaps between the description of Paxos and the needs of a real system, held even for a toy.

8.4 What went wrong in production

The paper’s list of unexpected failures over more than 100 machine-years is instructive because almost none of them is about Paxos:

  • the worker-thread starvation that caused cascading master failovers (§4.2);
  • a rollback to the old system, done by an operator unfamiliar with an undocumented procedure, used an old snapshot: 15 hours of data lost;
  • a later upgrade script had not deleted files from the failed upgrade, and the cell ran briefly on a months-old snapshot: about 30 minutes lost;
  • a semantic mismatch: Chubby expected an operation to fail if the master lost its role, which led to the epoch numbers of §4.4;
  • three inconsistent replicas, caught by the checksums;
  • a Linux 2.4 kernel bug: flushing a small file could take seconds while many buffered writes to other files were pending. This happened right after writing a snapshot, and stalled the Paxos log. The fix was to write large files in small chunks with a flush after each.

Three of the failures happened during upgrades or rollbacks, and two were operator errors during rollout. Their response was carefully tested scripts that minimize operator involvement. This is Lecture 13’s finding about operators again.


9. Raft and Viewstamped Replication

9.1 Same idea, different packaging

Three protocol families implement a replicated log with a leader, majorities and stable storage:

Multi-Paxos (as here)Viewstamped Replication (Oki and Liskov 1988; Mazières’ version)Raft (Ongaro and Ousterhout 2014)
leadership periodballot nview (view-id)term
order of entriesslot numberviewstamp (view-id, timestamp)(term, index)
who may leadanyone with a higher ballotthe view manager’s choiceonly a candidate whose log is at least as up to date as a majority’s
what the new leader does with old entriesphase 1 report, per slot: learn, carry forward, no-opadopt the latest log among a majoritynothing to recover: its log already contains every committed entry
logs may have holesyes (no-ops fill them)nono
membershipconfiguration in the log (α), or joint majoritiesmajority of old and new viewjoint consensus, or one server at a time

9.2 What Raft changes

Raft was designed to be easier to understand and teach than Paxos, and makes several restrictions that Multi-Paxos does not.

  • Election restriction. A server votes for a candidate only if the candidate’s log is at least as up to date as its own (higher last term, or same term and at least as long). Since a committed entry is on a majority, and the winner got votes from a majority, the winner already has every committed entry. There is no phase 1 report and no carrying forward.
  • Log matching. The leader’s AppendEntries message includes the (term, index) of the entry before the new ones. A follower accepts only if it has that entry, so if two logs agree at an index they agree on everything before it. Logs never have holes. A follower whose log diverges is overwritten by the leader’s, from the point of agreement on.
  • Commitment. A leader counts replicas only for entries of its own term. Entries of earlier terms become committed indirectly, when a later entry of the current term commits. Counting old-term entries directly is unsafe; the Raft paper’s Figure 8 shows the scenario. This is the same subtlety as Multi-Paxos’s re-proposal of carried-forward values with the new ballot.
  • Snapshots and catch-up: InstallSnapshot for followers that are too far behind, as in §5.
  • Liveness refinements (Ongaro’s dissertation):
    • pre-vote: a candidate first asks whether it could win before raising its term, which avoids §5.2’s disruptive returning replica;
    • check-quorum: a leader steps down if it has not heard from a majority recently.
    • Leases for reads, as in §6.

Neither protocol is “better”. Raft’s restrictions make it easier to implement correctly and to reason about. Multi-Paxos’s generality allows holes, out-of-order commitment, and variants such as leaderless or commutativity-aware Paxos. The engineering problems of §4–§8 (determinism, duplicates, leases, snapshots, membership, testing, disks that lie) are the same for both.


10. Design rules

  1. Make the state machine deterministic: decide clocks, random numbers and other nondeterminism once, at the leader, and log the decision.
  2. One Paxos instance per slot, one phase 1 for all slots, and execute strictly in slot order.
  3. A new leader learns, carries forward, and fills gaps with no-ops, and serves reads only after applying what its phase 1 found.
  4. Keep the duplicate table in the replicated state, keyed by client, with increasing request ids.
  5. Pay the disk per flush, not per command: batch, pipeline, group-commit.
  6. Snapshot and truncate, with a handle tying each snapshot to its log position, and serve lagging replicas from snapshots.
  7. Leases for local reads: count from the send time, keep a margin above twice the worst clock drift (and process pauses), refuse rivals while a lease runs, and boost instead of resigning.
  8. Change membership through the log, and make every quorum of the transition overlap every quorum of both configurations.
  9. Treat disk loss as a failure you must be told about, and rebuild without voting until caught up through a complete instance started after the loss.
  10. Monitor the margin, not just the service: count votes arriving, not replicas up to date.
  11. Test with seeded, repeatable fault injection in safety and liveness modes, plant bugs to measure the test, and add targeted scenarios for the rare shapes.

Summary

  • Replicated state machines: deterministic replicas, same commands, same order. Order matters (6 final states from 24 orders of 4 commands); so does determinism (3 states on 3 replicas until the leader chose the nondeterministic values). Broadcasting commands left replicas different in 38–300 of 300 runs; a Multi-Paxos log in 0.
  • Multi-Paxos: one instance per slot; one phase 1 for all slots; then one round trip and one forced write per acceptor per command (3n − 1 messages instead of 5n − 1). Batching and pipelining share each flush, raising throughput from ~418/s to ~10,500/s at the same 4.7 ms latency.
  • Leader change: learn the chosen slots, carry accepted values forward (a value chosen without anyone knowing survived), fill gaps with no-ops. Skipping phase 1 lost 12 acknowledged appends; leaving gaps stopped the service. Short election timeouts cut the outage (43 ms) but replace healthy leaders under loss (38 times in 5 s).
  • Retries create duplicates in the log (14 of 200 runs executed an append twice). The duplicate table must live in the replicated state.
  • Catch-up and snapshots: lagging replicas fetch entries or a snapshot. Snapshots shrink the log (1,274 → 24 entries) and the replay (266 → 6 slots). A returning replica with a high ballot deposes the leader unless leases and boosting stop it.
  • Faults hide: a misnamed replica looked up to date (5/5) while only 4/5 votes arrived, and the service died at the second crash.
  • Reads: from a deposed leader’s memory, 187 stale reads; under a lease, 0, as long as the margin covers the clock drift (m ≥ 1 − (1 − ρ)/(1 + ρ), confirmed exactly). Leases make reads cheap and failover slower.
  • Membership: old and new majorities can be disjoint exactly when they fit side by side in the servers involved. One-server changes and joint majorities are safe; switching on hearsay chose two values in 299 of 300 two-site runs.
  • Testing: the correct system passed 800 chaos runs; planted bugs on rare paths showed up in only 1–9 of 200 seeds; two bugs in the course’s own disk-loss rule were found exactly this way.
  • Raft restricts who can be elected, so a new leader has nothing to recover; the engineering problems are the same.

Common pitfalls

  • Nondeterminism in the state machine (clocks, random numbers, iteration order, local configuration).
  • Applying slots in the order they are learned instead of slot order.
  • Skipping phase 1 after a leader change, or recovering only the slots the new leader knows about.
  • Leaving gaps instead of proposing no-ops.
  • Keeping the duplicate table only at the leader, or reusing request ids.
  • Serving reads from the leader’s memory without a lease, or before the new leader has applied what its phase 1 found.
  • Counting a lease from the receipt time at the leader, or without a margin for drift and pauses.
  • Letting a reconnecting replica’s inflated ballot depose a healthy leader.
  • Switching configurations without overlapping quorums, or replacing several servers in one step.
  • Trusting a disk after it was lost or corrupted, or keeping the “I am rebuilding” mark in memory.
  • Monitoring progress instead of margin.
  • Believing a passing random test.

Exercises

  1. Counting. A five-server Multi-Paxos group with a stable leader runs 1,000 commands, one per slot, with no failures. PleaseAccept goes to all servers and Decide to every server but the leader. (a) How many Paxos messages and forced writes does it take? (b) The same with batches of 10 commands per slot? (c) With basic Paxos per slot, unbatched? (d) Which of these numbers does a 2 ms disk make most important, and why?

    Answer(a) Per slot 3n − 1 = 14 messages and n = 5 forced writes, so 14,000 messages and 5,000 writes, plus one phase 1 at the start (10 messages, 5 writes) and heartbeats. (b) 100 slots: 1,400 messages and 500 forced writes; each message is bigger. (c) Per slot 5n − 1 = 24 messages and 2n = 10 writes: 24,000 and 10,000. (d) The forced writes: each costs ~2 ms, against a fraction of a millisecond per message in a data center. Unless writes are shared by group commit, the 5,000 writes of (a) take 5,000 × 2 ms = 10 s of disk time per server for 1,000 commands, while (b) takes 1 s.
  2. The new leader’s job. Five servers; the old leader crashed. The new leader’s phase 1 got promises from S2, S3, S4 (starting at slot 40). For slot 40: S2 reports chosen “a”, the others nothing. Slot 41: S3 reports AlreadyAccepted(21, “b”), S4 AlreadyAccepted(32, “c”). Slot 42: nothing from anyone. Slot 43: S2 reports AlreadyAccepted(32, “d”). (a) What does the new leader propose in each slot? (b) Could “b” have been chosen in slot 41? (c) Why must slot 42 be filled at all?

    Answer(a) Slot 40: nothing to propose; it is chosen ("a"): learn it and tell the others. Slot 41: "c", the value of the highest-numbered AlreadyAccepted among the promises (32 > 21). Slot 42: a no-op. Slot 43: "d". New commands start at slot 44. (b) No. If "b" had been chosen with ballot 21, every higher-numbered proposal in slot 41 would carry "b" (P2 via P2c). "c" was proposed with ballot 32 after its proposer's phase 1, so "b" at 21 was not chosen. (c) Nobody can execute slot 43 before slot 42. Since no promise reports anything in slot 42, nothing was chosen there (a majority that chose it would intersect this one), so a no-op is safe and lets execution continue.
  3. Where the duplicate table lives. A colleague proposes keeping the table of executed (client, request id) pairs in the leader’s memory “since only the leader talks to clients”. Construct a run in which a command is executed twice. Then explain why the replicated table works even though duplicates are in the log.

    AnswerThe leader L gets command c (client C, request 7) chosen in slot 30 and executes it, but crashes before its reply reaches C. The new leader L′ has an empty table. C times out and resends request 7 to L′, which proposes it in slot 41. Every replica now executes c twice, at slot 30 and at slot 41. With the table in the replicated state, every replica, executing slot 30, records (C → 7, result). At slot 41 every replica finds 7 ≤ 7 in the table and skips the command, returning the stored result. The decision depends only on the log, so it is the same everywhere. L′ can also answer C's retry from its own table if it has already applied slot 30.
  4. Lease arithmetic. A leader’s lease is 10 s; heartbeats go out every second; the network delay is at most 50 ms; clocks drift by at most 200 ppm, and the service can pause for up to 2 s (garbage collection). (a) What margin is needed for drift alone? (b) Why does the pause matter, and how would you account for it? (c) After the leader crashes, how long until a new leader can serve lease reads, at worst?

    Answer(a) m ≥ 1 − (1 − ρ)/(1 + ρ) ≈ 2ρ = 0.04%, so 4 ms of 10 s; network delay only helps, because the leader counts from the send time. (b) A paused leader may check its lease just before the pause, then serve a read after it, believing the lease is valid while it has expired. The check and the reply must be atomic with respect to time, or the margin must exceed the longest pause: the leader serves only if at least 2 s of lease remain, so effectively the margin is 2 s plus the drift term. (c) Up to the remaining lease at the followers: 10 s after the last heartbeat they acknowledged. Then an election timeout (or immediately, if they campaign at lease expiry), a phase 1, applying what it found, and one heartbeat round to acquire its own lease: roughly 10 s plus a few round trips.
  5. Membership. (a) A group {A, B, C, D, E} must become {A, B, C, F, G} (replacing D and E). Show quorums of old and new that are disjoint. (b) Give a sequence of single-server changes that does it safely, and say how many configurations the system passes through. (c) Why might an operator be tempted to remove D and E first, and what does that risk?

    Answer(a) Majorities are 3 of 5 in each configuration, and 7 servers are involved, so by §7.2 two majorities fit side by side (3 + 3 ≤ 7). For example old {A, D, E} and new {B, C, F}: each is a majority of its configuration, and they share no server. (b) Add F (6 servers), remove D (5), add G (6), remove E (5): four changes, five configurations including the first, each step changing one server, so every adjacent pair of configurations has intersecting majorities. (c) Removing D and E first, one at a time, gives {A, B, C}, a 3-server group that tolerates only one failure while F and G are added. If one more server fails in that window, the group stops. Adding first keeps the fault tolerance at least as high during the change, at the cost of a moment with an even number of servers.
  6. Why not a single leader without Paxos? “If we have a stable leader anyway, let it simply number the commands and tell the replicas; no promises, no ballots.” (a) What goes wrong when that leader crashes, in terms of §4’s three kinds of slots? (b) What part of Multi-Paxos does the “simple” design lack?

    Answer(a) Its successor does not know which numbered commands reached which replicas. A command acknowledged to a client may have reached only some replicas (like slot 13 in demo 03, chosen without anyone knowing): the successor may reuse its number for another command and lose it. A command that reached only the dead leader (like slot 12) leaves a hole the successor cannot recognize as safe to fill. Two leaders, during a partition, would number commands independently: split brain. (b) Phase 1 with ballots: a successor must first make a majority stop listening to older leaders and report what they accepted, and every acceptance must be counted against a majority. That is the part that makes takeover safe; the stable leader only makes the normal case fast.
  7. Disk loss. In a 3-server group, S2’s disk is wiped and S2 restarts at once as a normal member. (a) Construct a run in which an acknowledged command is lost. (b) Why does the non-voting rule prevent it? (c) What if two of three disks are lost at the same time?

    Answer(a) S1 leads; command c is accepted by S1 and S2 in slot 9 (chosen) and acknowledged; S3 was briefly partitioned and missed it. S2 loses its disk and rejoins empty. S1 crashes. S3 campaigns: promises from S3 and S2 report nothing in slot 9, so S3 fills it with a no-op (or a new command), chosen by S3 and S2. Command c is gone, and S1, when it returns, holds a different slot 9. (b) Without S2's vote, S3 has only one voter and cannot form a majority, so it cannot overwrite slot 9 until S1 returns, and then S1's promise reports c. S2 votes again only after it has caught up through an instance that started after its loss, by which time slot 9 is back in S2's log. (c) Then only one server knows the past and two cannot vote, so the group cannot make progress, and safely so. Losing a majority of disks loses the guarantee; Paxos assumes stable storage at a majority. Recovering requires outside intervention, such as restoring from a snapshot or backup, with possible data loss.
  8. Testing. Demo 07’s local-read bug showed up in 1–2 of 200 seeds. (a) Why so rarely? (b) Design a fault schedule that hits it in nearly every run. (c) What does this say about combining random and targeted testing?

    Answer(a) A stale local read needs four things at once: a leader cut off from *every* other server; a client that can still reach it and reads; a new leader on the other side; and a write acknowledged by the new leader before the read. Random pairwise partitions seldom cut one server off from all four others while the clients still reach it. (b) Demo 05 Part A: partition the current leader from all other servers and from the writing client, keep a reading client attached to it, and keep writing on the other side. (c) Random testing explores combinations nobody thought of, but its yield on a particular shape depends on how likely the generator is to build it. Targeted scenarios cover the shapes you can name (isolated leader, returning replica, disk loss during rebuild), and planted bugs measure how good both are.
  • Problem Set 4’s Paxos questions concern single-decree message sequences, covered in Lecture 20. This lecture’s slot-numbered trace is an extension; it gives no answers.
  • Project 4 builds two-phase commit, not Paxos. §4.4 (retries and duplicate detection) and §8 (fault injection, recovering from logs) apply to it directly: its library loses and delays messages, and nodes crash and recover from logs.

Further reading

  • D. Mazières, Paxos Made Practical (2007) — the reading.
  • T. Chandra, R. Griesemer and J. Redstone, “Paxos Made Live — An Engineering Perspective”, PODC 2007 — the reading.
  • L. Lamport, “Paxos Made Simple”, ACM SIGACT News 32(4), 2001, §3.
  • F. B. Schneider, “Implementing Fault-Tolerant Services Using the State Machine Approach: A Tutorial”, ACM Computing Surveys 22(4), 1990.
  • B. Oki and B. Liskov, “Viewstamped Replication: A New Primary Copy Method to Support Highly-Available Distributed Systems”, PODC 1988; B. Liskov and J. Cowling, “Viewstamped Replication Revisited” (MIT TR, 2012).
  • M. Burrows, “The Chubby Lock Service for Loosely-Coupled Distributed Systems”, OSDI 2006.
  • D. Ongaro and J. Ousterhout, “In Search of an Understandable Consensus Algorithm”, USENIX ATC 2014; D. Ongaro, Consensus: Bridging Theory and Practice (PhD thesis, Stanford 2014).
  • R. van Renesse and D. Altinbuken, “Paxos Made Moderately Complex”, ACM Computing Surveys 47(3), 2015.
  • L. Lamport, D. Malkhi and L. Zhou, “Reconfiguring a State Machine”, ACM SIGACT News 41(1), 2010.
  • C. Gray and D. Cheriton, “Leases: An Efficient Fault-Tolerant Mechanism for Distributed File Cache Consistency”, SOSP 1989.

Preview of Lecture 22 — Optimistic replication and disconnected operation: Coda

Everything in Lectures 19–21 is pessimistic: no update is accepted unless a majority can agree on it now, and a partitioned minority stops. Coda takes the opposite bet, since conflicts are rare and availability is precious. A laptop that loses the network keeps working on its cached files, logs its updates, and reintegrates them when it reconnects, detecting and resolving the occasional conflict. Lecture 22 covers:

  • Coda’s three client states (hoarding, emulation, reintegration) and its client modification log;
  • version vectors and how they detect concurrent updates;
  • automatic resolution of directory conflicts and application-specific resolvers for files;
  • operation over weak links (trickle reintegration).

术语表 (Glossary, English → 中文)

English中文
replicated state machine复制状态机
deterministic / nondeterminism确定性的 / 非确定性
commute (commutative commands)可交换(可交换的命令)
log slot / instance日志槽位 / (Paxos)实例
Multi-Paxos多实例 Paxos(Multi-Paxos)
stable leader / distinguished proposer稳定领导者 / 指定提议者
ballot (proposal number)选票号(提案编号)
no-op / gap (hole) in the log空操作 / 日志空洞
carry forward (an accepted value)(将已接受的值)延续下去
applied index / commit index已应用位置 / 提交位置
heartbeat / election timeout心跳 / 选举超时
pipelining / batching流水线 / 批处理
group commit / forced write (flush)组提交 / 强制写(刷盘)
client retry / request id客户端重试 / 请求编号
duplicate detection / duplicate table重复检测 / 去重表
at-most-once / exactly-once至多一次 / 恰好一次
epoch number纪元号
catch-up / lagging replica追赶 / 落后副本
snapshot / snapshot handle快照 / 快照句柄
log truncation / replay日志截断 / 重放
master churn主节点频繁更替
boosting (the sequence number)提升(序号)
master lease / lease margin主节点租约 / 租约余量
clock drift / process pause时钟漂移 / 进程停顿
stale read / linearizable read陈旧读 / 线性一致读
configuration / membership change配置 / 成员变更
joint consensus联合共识
view / view change / viewstamp视图 / 视图变更 / 视图戳
witness (replica)见证者(副本)
disk corruption / non-voting member磁盘损坏 / 无投票权成员
fault injection / chaos testing故障注入 / 混沌测试
safety mode / liveness mode安全模式 / 活性模式
runtime consistency check (checksum)运行时一致性检查(校验和)
masked fault被掩盖的故障
Raft term / election restrictionRaft 任期 / 选举限制
log matching property日志匹配性质
pre-vote / check-quorum预投票 / 法定人数检查
← 返回课程目录