Goal

After this module you can prove that deterministic replicas fed the same sequence end in the same state, say what weaker broadcasts require of the updates, prove that consensus and total order broadcast are equivalent, state FLP and how practical algorithms live with it, and prove that tolerating crashes needs nodes.

Module 3 kept replicas of data consistent with timestamps and quorums, and ended with what that cannot do: an operation such as compare-and-set needs every replica to apply the operations in one agreed order. This module makes that idea precise. If each replica is a deterministic state machine and all replicas apply the same sequence of updates, they stay identical. This is state machine replication (SMR), and the lecturer called it the idea at the bottom of nearly every distributed system, blockchains included.

SMR needs total order broadcast, and Module 2 built total order broadcast with a sequencer, a single node that is a single point of failure. Making total order broadcast fault tolerant is the consensus problem. We prove that the two problems are the same problem, then ask in which system models consensus can be solved at all. The answers are the FLP impossibility in the asynchronous model, partial synchrony as the way out, and the rule that crashes need nodes. These are the facts that shape Raft and Paxos in the rest of the notes.

Lectures 06.01 (state machine replication, leader-based replication, weaker broadcast) and 06.02 (consensus, its relation to total order broadcast, system models, FLP). Kleppmann’s notes, Section 5.3 (slides 101-104) and Section 6.1 (slides 105-107) (1).

State machine replication

Deterministic state machines

The idea of lecture 06.01: replicate not the data but the process that computes it. Each replica runs the same program, starts in the same state, and receives the same inputs in the same order. If the program is deterministic, the replicas cannot diverge.

Definition 4.1 (Deterministic state machine).

A deterministic state machine is a tuple : a set of states , an initial state , a set of updates (inputs) , and a transition function . For a finite sequence of updates we write for the state reached from , defined by

where is the empty sequence and is followed by .

“Deterministic” is built into the type of : it is a function, so the next state depends only on the current state and the update. The lecturer’s non-example is an update “add a random number to the counter”: each replica draws a different number, so is not a function of alone. Kleppmann adds that even errors must be deterministic: an update that fails on one replica (disk full) and succeeds on another breaks the model.

Theorem 4.2 (Same start, same inputs, same state).

Let replicas and run the same deterministic state machine . If both start in and both apply the same finite sequence of updates, they end in the same state . More generally, if replica has applied and replica has applied , and is a prefix of , then replica ‘s state is a state that replica passed through.

SMR on top of total order broadcast

Theorem 4.2 needs every replica to apply the same sequence. Total order broadcast is exactly the tool that hands every node the same sequence. We use it in the following form.

Definition 4.3 (Total order broadcast).

A total order broadcast (TOB) protocol provides and with these properties, for crash-stop nodes:

  • Validity: if a correct node broadcasts , it eventually delivers .
  • Agreement: if some correct node delivers , every correct node eventually delivers .
  • Integrity: a node delivers each message at most once, and only if it was broadcast.
  • Total order: for any two nodes , the sequence of messages delivered by is a prefix of the sequence delivered by , or vice versa (at any moment).

FIFO-total order broadcast adds: if a node broadcasts before , no node delivers before .

Remark 4.4 (Two ways to state total order).

Kleppmann states total order as “if is delivered before on one node, then is delivered before on all nodes”, meaning that a node that delivers has already delivered . Together with agreement this gives the prefix form above: deliveries at all nodes follow one global sequence, and a node’s deliveries are an initial segment of it. The prefix form is the one the proofs below use.

The SMR algorithm is then two handlers (Kleppmann slide 102):

// State machine replication over FIFO-total order broadcast.
state := s0                              // same initial state everywhere
 
on request to perform update u:
    FIFO-TO-broadcast(u)                 // do NOT apply u yet
 
on FIFO-TO-deliver(u):
    state := delta(state, u)             // deterministic transition
  • The replica that receives a client request does not apply it at once: it applies it only when total order broadcast delivers it, in the common order. This is SMR’s main cost, since every update waits for the broadcast.
  • The lecturer explains the FIFO part: a node handles a client’s requests one after another, and a client that sends , , expects them applied in that order.
Corollary 4.5 (SMR replicas never diverge).

With the algorithm above, at every moment the states of any two replicas are states along one common sequence: the replica that has delivered fewer updates is in a state the other one passed through. Once both have delivered the same number of updates they are in the same state.

FIFO-total order broadcast u1, u2, u3 replica A s0, u1, u2, u3 -> s3 replica B s0, u1, u2, u3 -> s3 replica C s0, u1, u2, u3 -> s3 one sequence
Figure 4.1. State machine replication: total order broadcast delivers one sequence of updates, and deterministic replicas that start in the same state pass through the same states.

An important feature of SMR (Kleppmann 5.3): may be arbitrarily complex. A whole database transaction with business logic is one update. A blockchain is SMR in which the chain of blocks is the total order broadcast sequence and a smart contract is a deterministic .

Passive and active replication, leaders

The lecture’s leader-follower picture (06.01, Kleppmann slide 103): clients send transactions and to the leader replica . The two transactions are concurrent (, no causal path between the clients), yet the leader commits them in some order, say then , and the follower applies the committed changes in that commit order. The leader plays the role of the sequencer of Module 2: it decides the order of concurrent operations.

Definition 4.6 (Active and passive replication).
  • Active replication: every replica executes every update itself, in the total order. This is SMR as above, and it requires a deterministic .
  • Passive (primary-backup) replication: one replica, the leader or primary, executes each transaction and broadcasts the resulting state changes (commit records) in commit order; followers apply the changes without re-executing. This is total order broadcast of commit records.

Passive replication tolerates nondeterministic operations: the leader draws the random number once and ships the result. Active replication can do the same by having whoever orders the update fix the random value and include it in the log entry. Raft and Multi-Paxos are built the same way: a leader orders commands into a log. The lecture’s preview of consensus: each leader orders the transactions of its term, and terms are themselves ordered, so all transactions end up in one total order (Module 5).

What weaker broadcasts demand of the updates

Can we replicate with something cheaper than total order? Lecture 06.01 and Kleppmann slide 104 answer: yes, if the updates have extra algebraic properties. Two updates commute if for every state . For example, “add to the set” and “add to the set” commute; “add ” and “remove ” do not (Module 3).

broadcastdelivery guaranteeupdate functions must be
FIFO-total ordersame sequence everywheredeterministic (SMR)
causalcausal order; concurrent ones in any orderdeterministic, concurrent updates commute
reliableall delivered, any orderdeterministic, all updates commute
best-effortsome may be lost or repeateddeterministic, commutative, idempotent, tolerate loss

Each row moves work from the network to the application. We prove the causal row, the one whose proof is not obvious. The key fact is about orderings.

Lemma 4.7 (Linear extensions are connected by swaps).

Let be a finite strict partial order and let be two linear extensions of it (orderings of all of in which implies comes before ). Then can be transformed into by a finite sequence of swaps of adjacent, incomparable elements, each intermediate ordering being again a linear extension.

Theorem 4.8 (Causal broadcast with commuting concurrent updates converges).

Suppose replicas apply updates in the order delivered by a causal broadcast, every update is a deterministic function , and any two concurrent updates commute. If replicas and start in and have delivered the same set of updates (possibly in different orders), they are in the same state.

Corollary 4.9 (Reliable broadcast with commuting updates converges).

If replicas use reliable broadcast (any delivery order) and all pairs of updates commute, two replicas that have delivered the same set of updates are in the same state; by the agreement property of reliable broadcast, all correct replicas eventually deliver the same set.

For best-effort broadcast even the set of delivered updates differs between replicas, and retries deliver some twice, which is why updates must also be idempotent and the system needs anti-entropy to fill the gaps (Module 3). The lecturer’s observation from industry: most systems choose the first row, total order and deterministic updates, because designing commuting updates (the subject of CRDTs) is harder than getting a total order.

Exam trap: commutative is not enough for best-effort

Commutativity makes the order irrelevant, not the multiplicity. With best-effort broadcast a lost message is never applied and a retried one may be applied twice. “Increment by 1” commutes with everything, yet two replicas that received it once and twice differ. That is why the last row also asks for idempotence and tolerance of loss.

Consensus

Why the sequencer is not enough

Module 2 built total order broadcast with a sequencer: all messages go to one leader, which FIFO-broadcasts them in its order. It works until the leader crashes. Then nothing is ordered, and in the meantime some nodes may have received the leader’s last messages while others have not.

Try it: step through the run. The sequencer L orders two messages and then crashes; watch that no node can deliver A’s next message z, and ask which node should take over and how it would know what the old sequencer already sent.

A leader L B C m1 crash m2 never sequenced B, C wait: no leader
Figure 4.2. The sequencer of Module 2 is a single point of failure: after the leader crashes, A's next message is never ordered and B and C cannot deliver anything until a new leader is agreed on. Dots mark deliveries of m1.

Kleppmann (Section 6) describes the classical fix, manual failover: a human operator picks a new leader and reconfigures the nodes. It is used by many databases and is fine for planned maintenance, but for an unplanned crash a human takes minutes. Lecture 06.02 adds the scaling argument from Module 3: at scale some node is always failing, so failover must be automatic. Automatically choosing a new leader, so that all nodes agree on who it is, is an instance of the consensus problem.

The consensus problem

The lecture’s general form: some variable , and all replicas must agree on its value (who the next leader is, which message is delivered next, a single integer).

Definition 4.10 (Consensus).

Each node may call with a value ; a node decides by calling . An algorithm solves consensus if, in every execution of the system model:

  • Termination: every correct node eventually decides some value.
  • Validity: if a node decides , then was proposed by some node.
  • Integrity: every node decides at most once.
  • Agreement: no two nodes decide different values.

Agreement is stated for all nodes, including those that decide and then crash (uniform agreement). With crash-recovery, a decision must therefore survive a crash, which is why Raft and Paxos keep their state in stable storage.

The lecturer’s warning about cost: a consensus decision takes several rounds of messages among all nodes, roughly messages when every node talks to every other node, so systems avoid running it per message. A leader-based round costs about messages (two round trips from the leader to all), which is why the practical algorithms elect a leader once and then let it order many commands.

Consensus and total order broadcast are equivalent

Lecture 06.02 and Kleppmann state that the two problems are “formally equivalent” (2): an algorithm for either one can be turned into an algorithm for the other. We prove both directions in the crash-stop model with reliable links, assuming every correct node proposes (for consensus).

// (1) Consensus from total order broadcast.
decided := false
 
on propose(v):
    TO-broadcast(v)
 
on TO-deliver(v):
    if not decided:
        decided := true
        decide(v)                // the first delivered value, everywhere
// (2) Total order broadcast from repeated consensus (instances k = 1, 2, ...).
// Every correct node runs the loop; instance k decides batch number k.
received  := {}                  // messages received by reliable broadcast
delivered := []                  // TO-delivered sequence
k := 1
 
on TO-broadcast(m):
    m.id := (myId, mySeq); mySeq := mySeq + 1
    RB-broadcast(m)              // reliable broadcast (Module 2)
 
on RB-deliver(m):
    received := received + {m}
 
loop forever:
    pending := received minus delivered       // may be empty
    propose(k, pending)                       // instance k
    B := wait for decide(k)                   // same B at every node
    for m in (B minus delivered), sorted by m.id:
        delivered := delivered + [m]
        TO-deliver(m)
    k := k + 1
  • In (2) the batch of instance is a set; the deterministic sort by m.id turns it into the same sequence at every node.
  • Every correct node proposes in every instance, possibly an empty batch, so every instance has all correct nodes as participants. Real systems avoid the busy loop with a leader that starts an instance only when there is work.
Theorem 4.11 (Consensus is equivalent to total order broadcast).

In the crash-stop model with reliable links:

  1. Algorithm (1) solves consensus, given any total order broadcast (Definition 4.3).
  2. Algorithm (2) implements total order broadcast, given reliable broadcast and any consensus algorithm (Definition 4.10) that can be run as independent instances.
Remark 4.12 (FIFO comes for free).

If (2) uses FIFO broadcast instead of reliable broadcast, every node’s received set contains, with any message , all earlier messages of the same sender. So does every proposal, and every union of with a decided batch. Sorting a batch by id then delivers each sender’s messages in order: the construction yields FIFO-total order broadcast.

one decision consensus one sequence total order bcast one instance per slot decide first delivered
Figure 4.3. The two reductions of the equivalence theorem: repeated consensus builds total order broadcast, and taking the first delivered message of total order broadcast solves consensus.

Algorithms and the lecture’s taxonomy

Kleppmann’s list (slide 106): Paxos solves single-value consensus and Multi-Paxos generalises it to total order broadcast; Raft, Viewstamped Replication (3) and Zab (the protocol of ZooKeeper) provide FIFO-total order broadcast directly. The lecturer added history: Viewstamped Replication appeared at about the same time as Paxos and received little attention until Raft revived its ideas, and before blockchains most systems obtained consensus simply by running ZooKeeper.

Lecture 06.02 also sorts the algorithms into two families: leader-based (Raft, Viewstamped Replication), which spend effort once to elect a leader and then let it decide alone, and leaderless (Paxos), which coordinate for every decision. The lecturer prefers the leader-based design for efficiency and simplicity, and notes that researchers do not agree on whether the two are equivalent.

Lecture correction: Paxos is not leaderless in practice

Single-decree Paxos indeed lets any proposer start a ballot, with no fixed leader. But the practical protocol, Multi-Paxos, elects a distinguished proposer (a leader) that runs Phase 1 once for all future slots and then needs only Phase 2 per command, exactly the efficiency argument made for Raft. So both Multi-Paxos and Raft are leader-based. The real difference is which node may become leader: Raft only lets a candidate with an up-to-date log win, while a Multi-Paxos leader may be any node and learns the accepted values in Phase 1 (4). Modules 9 and 10 make this precise.

System models, safety and liveness

Timing models

Whether consensus is solvable depends on the system model (Kleppmann 2.3). The node model here is crash-stop or crash-recovery; the timing model is one of three.

Definition 4.13 (Timing models).
  • Synchronous: there are known bounds on message delay and on the relative speed of nodes, holding at all times.
  • Asynchronous: no bounds at all. A message may be delayed for any finite time, and a node may pause for any finite time; there are no useful clocks.
  • Partially synchronous (5): the system may behave asynchronously for a while, but there is an unknown time GST (global stabilization time) after which the bounds hold. (An equivalent variant: the bounds always hold but their values are unknown.)

The lecture’s description of partial synchrony: messages are usually delivered within some time; there are “blackout periods” when they are not; when a blackout ends, delivery is timely again. Paxos and Raft assume a partially synchronous, crash-recovery model with fair-loss links (Kleppmann slide 107).

Safety and liveness

Definition 4.14 (Safety and liveness properties).

A property is a set of (infinite) executions.

  • A safety property says “nothing bad ever happens”: if an execution violates it, some finite prefix already violates it, in the sense that no continuation of that prefix satisfies the property.
  • A liveness property says “something good eventually happens”: every finite prefix can be continued to an execution that satisfies it.
Proposition 4.15 (Which consensus properties are safety).

Agreement, validity and integrity are safety properties. Termination is a liveness property.

The exam take-aways the lecturer lists in lecture 06.03, recapping 06.02, are exactly the rest of this section: what consensus is, how it relates to total order broadcast, what safety is, what progress (liveness) is, what can be done in an asynchronous system, and why we need (partial) synchrony.

The FLP impossibility

Theorem 4.16 (FLP impossibility).

In the asynchronous model with reliable links, in which at most one node may crash (crash-stop), there is no deterministic algorithm that solves consensus, even for binary values . That is, every deterministic algorithm that satisfies agreement and validity has an execution, with at most one crash and every message eventually delivered, in which some correct node never decides (6).

The lecture skipped the proof (the paper is linked from the course schedule); here is its structure. A configuration is the state of all nodes plus the set of messages in transit. A step is node receiving message (or nothing) and reacting deterministically. A configuration is 0-valent if every execution from it decides 0, 1-valent if every one decides 1, and bivalent if both outcomes are still reachable. This is the lecturer’s “undecided state”: some nodes are leaning to 0, some to 1.

config C0 bivalent config C1 bivalent config C2 bivalent ... would decide 0 would decide 1 would decide 0 avoided
Figure 4.4. The FLP adversary: from every bivalent configuration some step would force a decision (dashed), but by delaying that step the adversary can always reach another bivalent configuration, forever.

Exam trap: what FLP does and does not say

FLP is about termination of deterministic algorithms in the asynchronous model. It does not say consensus is impossible in practice. It does not say safety must be violated: an algorithm can keep agreement and validity in every execution and give up only termination in some executions. And it does not apply to partially synchronous systems (where Paxos and Raft terminate after GST) or to randomized algorithms (which terminate with probability 1). A common wrong answer is “FLP shows that agreement can be violated when a node crashes”.

How practical algorithms live with FLP

The lecturer’s practical reading: Paxos, Raft and ZooKeeper all use timeouts, for example to suspect that a leader has crashed. A timeout only makes sense if, beyond some time, silence means a crash; in the asynchronous model a slow node can always look crashed, so timeouts are meaningful only under (partial) synchrony. Hence these algorithms assume partial synchrony.

Key point: safety never depends on timing

Practical consensus algorithms are designed so that agreement, validity and integrity hold in every execution, even fully asynchronous ones in which timeouts fire wrongly and two nodes both believe they are leader. Timing is used only for liveness: after GST, timeouts become accurate, one leader stays in charge long enough, and decisions are made. FLP is respected because before GST the algorithm may make no progress.

Remark 4.17 (Failure detectors).

Chandra and Toueg (2) package the timing assumption as a failure detector: a module that outputs suspected nodes. An eventually perfect detector may be wrong for a while but eventually suspects exactly the crashed nodes; partial synchrony implements it with timeouts that grow after each false suspicion. They showed that consensus with a majority of correct nodes is solvable with such detectors. Chandra, Hadzilacos and Toueg then showed that the weakest detector sufficient for consensus is one that eventually names the same correct leader at all correct nodes (7). Kleppmann summarises: consensus needs a failure detector, and a failure detector needs a clock.

Why a majority: n at least 2f + 1

The second constraint is about numbers: how many crashes can a consensus algorithm survive?

Theorem 4.18 (Consensus needs a correct majority).

In the partially synchronous model (hence also in the asynchronous one) with crash failures, no algorithm solves consensus with nodes of which up to may crash if . Equivalently, for , tolerating crashes requires .

The case is trivial and excluded: the single node decides its own input at once, which satisfies all four properties even if it may crash.

Remark 4.19 (Synchrony changes the number).

In the synchronous model with crash failures, consensus can be solved for any : run rounds in which every node forwards all values it has seen, then decide the minimum. With crashes some round has no crash, and after that round all surviving nodes know the same values. The partition argument above fails there because a timeout reliably distinguishes “crashed” from “slow”. That is exactly the assumption real networks do not give us.

Worked example: total order broadcast from three consensus instances

Three nodes A, B, C run algorithm (2) of Theorem 4.11. Message ids are (sender, sequence number), sorted by sender then number.

  1. A broadcasts , B broadcasts . Reliable broadcast reaches all nodes at different times: when instance 1 starts, A has received , B has , C has .
  2. Instance 1. Proposals: A proposes , B proposes , C proposes . Suppose consensus decides B’s proposal, (validity: it is a proposal). Every node delivers then (sorted by id). . Note that A delivers although it had not yet received it by reliable broadcast: it learned it from the decision.
  3. C broadcasts , then A broadcasts . At the start of instance 2: A has received only (plus old messages), B has , C has .
  4. Instance 2. Pending sets: A , B , C . Suppose A’s proposal is decided: . All deliver . . Message is still pending everywhere.
  5. Instance 3. Every pending set now contains (all nodes have received it, none has delivered it), so whichever proposal is decided contains . All deliver : . This is the validity argument of the proof in miniature.
  6. Consensus from this TOB. If A, B, C had each TO-broadcast a proposal for a separate consensus question using algorithm (1), all would decide the first message of the common sequence. In this run that is , at every node, even at C, which had received first.
  7. A crash. Suppose B crashes during instance 3 after proposing. A and C still finish instance 3 (consensus terminates with a majority of 2 out of 3 alive, by Theorem 4.18 this is the most crashes we can afford), and B’s proposal may even be the decided one; agreement only needs A and C to see the same .

Exam checklist from lecture 06.03

Be ready to answer in two or three sentences each: What is consensus (Definition 4.10)? How does it relate to total order broadcast (Theorem 4.11, both directions)? What is safety and what is progress (Definition 4.14)? What can we do in an asynchronous system (keep safety; give up guaranteed termination, Theorem 4.16)? Why do we need (partial) synchrony (timeouts for leader failure detection, liveness only)?

What breaks

  • Nondeterminism breaks SMR: a random number, the local clock, iteration order of a hash map, or an error that occurs on one replica only. Remedy: let the leader fix such values and put them in the log.
  • Crash-recovery without stable storage breaks consensus: a node that forgets its vote or its accepted value after a restart can help two conflicting decisions. Raft and Paxos persist their state before replying.
  • A minority partition cannot make progress (Theorem 4.18): with , the side with 2 nodes stops, by design.
  • Asynchrony before GST can stall any deterministic algorithm (Theorem 4.16). Duelling leaders (Paxos) and split votes (Raft) are the practical forms of this stall; randomized timeouts make them short in practice but cannot rule them out.
  • Byzantine nodes (lying, not just crashing) break all of the above; they need and different algorithms, used in blockchains (Kleppmann slide 107).

Why it matters

This module fixes the target for the rest of the notes: a fault-tolerant total order broadcast, which is the same as consensus, safe in every execution and live after GST, with majorities of nodes. Module 5 starts building it with terms and one-vote-per-term elections. Raft (Module 6, Module 7) is an SMR log whose safety proofs are invariants that never mention time. Paxos (Module 8) solves one consensus instance and Multi-Paxos (Module 9) is the slot-by-slot construction of Theorem 4.11.

Further reading

  • Kleppmann’s notes, Sections 5.3 and 6.1 (1).
  • Schneider’s tutorial on the state machine approach (8).
  • The equivalence of consensus and total order broadcast, and failure detectors (2,9).
  • Partial synchrony (5) and the FLP result (6).
  • Paxos versus Raft, and the leader question (4).

Homework

The problems for this module are in Homework 4.

1.
Kleppmann M. Distributed Systems: Lecture Notes [Internet]. University of Cambridge, Computer Science Tripos Part IB; 2021. Available from: https://www.cl.cam.ac.uk/teaching/2122/ConcDisSys/dist-sys-notes.pdf
2.
Chandra TD, Toueg S. Unreliable Failure Detectors for Reliable Distributed Systems. Journal of the ACM. 1996;43(2):225–67.
3.
Oki BM, Liskov BH. Viewstamped Replication: A New Primary Copy Method to Support Highly-Available Distributed Systems. In: Proceedings of the 7th ACM Symposium on Principles of Distributed Computing (PODC). 1988. p. 8–17.
4.
Howard H, Mortier R. Paxos vs Raft: Have We Reached Consensus on Distributed Consensus? In: Proceedings of the 7th Workshop on Principles and Practice of Consistency for Distributed Data (PaPoC). 2020.
5.
Dwork C, Lynch N, Stockmeyer L. Consensus in the Presence of Partial Synchrony. Journal of the ACM. 1988;35(2):288–323.
6.
Fischer MJ, Lynch NA, Paterson MS. Impossibility of Distributed Consensus with One Faulty Process. Journal of the ACM. 1985;32(2):374–82.
7.
Chandra TD, Hadzilacos V, Toueg S. The Weakest Failure Detector for Solving Consensus. Journal of the ACM. 1996;43(4):685–722.
8.
Schneider FB. Implementing Fault-Tolerant Services Using the State Machine Approach: A Tutorial. ACM Computing Surveys. 1990;22(4):299–319.
9.
Hadzilacos V, Toueg S. A Modular Approach to Fault-Tolerant Broadcasts and Related Problems. Cornell University, Technical Report TR94-1425. 1994;