Consensus: Paxos and Raft
Notes on consensus in distributed systems, explaining Paxos and Raft: why consensus is needed, precise definitions (safety, liveness, quorum), Paxos phases and safety proof, Raft design and algorithms (leader election, log replication), worked traces, common exam mistakes and quick checks.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Distributed systems often run on many independent machines that can fail or be slow. Consensus is the problem of getting a group of machines (servers) to agree on one value (for example: which command to append to a replicated log). Engineers use consensus to implement fault-tolerant services such as replicated state machines, distributed databases, configuration management, and leader election. Paxos and Raft are two practical consensus protocols used in production systems: Paxos is the classic academic solution; Raft is designed for understandability and easier implementation.
Key ideas
Start by defining terms and assumptions clearly.
Consensus problem: a set of processes (servers) must agree on a single value satisfying three properties:
- Termination (liveness): every non-faulty process eventually decides some value.
- Integrity (validity): any decided value must have been proposed by some process (or satisfy a predicate defined by the system).
- Agreement (safety): no two processes decide different values.
Failure model / assumptions: We assume processes may crash (stop) but do not behave Byzantine (no arbitrary/malicious behaviour). The network may lose, delay, or reorder messages. Because of the FLP impossibility result, deterministic consensus is impossible in a purely asynchronous system with even one crash; practical protocols (Paxos and Raft) assume partial synchrony (eventually messages are delivered within some bound) or make progress under leader stability.
Quorum: for N servers, a majority quorum is any set of at least
⌊N/2⌋ + 1servers. Property: any two majorities intersect (share at least one server). This intersection is crucial for safety proofs.
Paxos (basic Single-Decree Paxos) — roles and phases:
- Proposer: proposes values.
- Acceptor: votes (accepts) proposals; their state is persistent across crashes. Persist at least the highest promised proposal number (promise_n) and the last accepted proposal (accepted_n, accepted_value).
- Learner: learns which value was chosen (may be the same as acceptors). In practice, to build a replicated log, Multi-Paxos runs one Paxos instance per log index and, with a stable leader, amortizes Phase 1 so subsequent entries proceed with only Phase 2 until leadership changes.
Paxos protocol (two phases) — exact steps to draw and label for an exam diagram:
- Draw three columns labeled Proposer, Acceptors (A1,..,Ak horizontally or as a group), Learners.
- Arrow 1 (Prepare): Proposer -> Acceptors: message
Prepare(n)wherenis a unique increasing proposal number. - Arrow 2 (Promise): Acceptors -> Proposer:
Promise(n, accepted_n, accepted_value)where acceptor promises not to accept proposals < n and reports highest-numbered proposal it has already accepted (if any). - Arrow 3 (Accept Request): Proposer -> Acceptors:
Accept(n, v)wherevis chosen as the highest numbered accepted_value from promises if any, otherwise proposer picks its own v. - Arrow 4 (Accepted): Acceptors -> Learners:
Accepted(n, v)when acceptors accept. When a majority have acceptedvwith samen,vis chosen.
Definition: A value v is chosen if a majority of acceptors have accepted v under the same proposal number n.
Paxos safety (exact theorem statement and proof sketch to write in exams):
Theorem (Paxos safety): If a value v is chosen in some proposal, then no different value v' ≠ v can ever be chosen in a higher-numbered proposal. Assumptions: acceptors follow the promise rule and persist their accepted state; proposers follow the algorithm (choose previously accepted value when present), and quorums are majority sets.
Proof (standard exam derivation):
- Suppose
vis chosen by proposaln. Then a majorityQ1of acceptors accepted(n, v). - Consider any later proposal
n' > nwhose proposer sendsPrepare(n')and obtains promises from some majorityQ2. - By quorum intersection property,
Q1 ∩ Q2is non-empty; letabe an acceptor in the intersection. - When
apromised ton', it must reply with the highest-numbered proposal it has accepted. Sinceahad accepted(n, v), that reported proposal has proposal number ≥ n and valuev(ifalater accepted a higher-numbered proposal, it must also carry valuevdue to the proposer rule). - The proposer for
n'must, by the Paxos rule, choose the value with the highest accepted number from replies; therefore it will choosev(or another accepted with same value) rather than a differentv'. - Thus any accept requests with
n'will carryv; consequently no future proposal can get a majority to accept a different value. QED.
Raft — goals and key design choices:
- Raft aims to be easier to understand and implement while providing the same guarantees: safety (no two servers apply different commands at the same log index) and liveness (under stable leader and reasonable timing, progress occurs).
- Define term: a monotonically increasing epoch number used for leader election; persistent on disk.
- Each server keeps a replicated log: a sequence of entries
(term, command). The leader appends new entries and replicates them to followers. - Raft properties: Leader election, Log replication, Safety (a server only applies entries that are committed and entries are committed in log index order; a leader only declares entries from its current term committed via the majority rule), Membership changes handled with joint consensus.
Raft persistent state (must survive crashes): currentTerm, votedFor, log[]. Volatile state: commitIndex, lastApplied. Leader volatile: nextIndex[] and matchIndex[].
Leader election (draw and label diagram):
- Timeout: follower with no leader for election timeout becomes candidate, increments
currentTerm, votes for self, sendsRequestVote(term, lastLogIndex, lastLogTerm)to others. - Recipients reply
VoteGrantedif they have not voted in this term and candidate’s log is at least as up-to-date (compare last term then index). - Candidate becomes leader if it receives votes from majority.
Raft safety sketch (leader completeness): If a leader has decided (committed) a log entry at index i in term t, then any later leader for term t' > t must have that entry in its log at index i. This is enforced by the election restriction: a voter grants vote only to a candidate whose log is at least as up-to-date as the voter's; since the leader that committed the entry had replicated it to a majority, the new leader must have seen that majority (intersection) and therefore that entry. Moreover, Raft's log matching property states: if two logs contain an entry with the same index and term, then the logs are identical in all entries up through that index.
Formulas
quorum = ⌊N/2⌋ + 1 — N is number of servers; a majority quorum size. (No physical unit.)
Intersection(majority1, majority2) ≥ 1 — property of majority quorums; used in Paxos safety.
No SI units apply; these are counts.
Important RPC names / syntax to remember (Raft):
RequestVote(term, candidateId, lastLogIndex, lastLogTerm)RequestVoteResponse(term, voteGranted)AppendEntries(term, leaderId, prevLogIndex, prevLogTerm, entries[], leaderCommit)AppendEntriesResponse(term, success)
Worked examples
Example 1 — Single-Decree Paxos with 3 acceptors (A1,A2,A3):
Given: Acceptors initially have accepted nothing. Proposer P1 issues Prepare(1) and gets promises from A1,A2,A3 (all empty). P1 sends Accept(1, x) with value x.
Steps:
- P1 -> A1,A2,A3:
Prepare(1). - Each Ai replies
Promise(1, null, null)because none accepted before. - P1 chooses its value
xand sendsAccept(1, x)to all. - If A1 and A2 accept, they reply
Accepted(1,x)and majority accepted:xis chosen. - Later proposer P2 with number 2 wants to propose
y. P2 sendsPrepare(2)to majority (say A1,A2). A1 and A2 reply including their highest accepted(1,x); P2 must proposex(noty). So safety preserved. Final answer: x is chosen and cannot be replaced by y.
Example 2 — Raft leader election and log replication (5 servers S1..S5):
Initial: S1 is leader term 3, log index 5 committed. Leader S1 appends new entry E(term=3,cmd=SET 1) at index 6 and sends AppendEntries to all.
Steps:
- S1 -> S2,S3,S4,S5:
AppendEntries(term=3, prevLogIndex=5, prevLogTerm=3, entries=[E]). - Suppose S2 and S3 reply success; S1 sees matchIndex for majority (S1,S2,S3) >= 6, so sets commitIndex=6 and applies E locally; then notifies followers via future AppendEntries with leaderCommit=6.
- If S1 crashes before some followers replicate, a new election occurs. A candidate must be at least as up-to-date as a majority (compare lastLogTerm, then lastLogIndex); in this scenario that implies having the entry at index 6, term 3 to win; because majority had the entry, any candidate that gathers votes from a majority must either have the entry (or must not get enough votes). Thus committed entry remains in log of new leader and will be replicated. Final answer: committed entries are preserved across leader changes.
Example 3 — Raft split vote (short trace): 5 servers: election timeout randomization prevents frequent ties. If S1 and S2 time out simultaneously, each requests votes; suppose voting splits 2 vs 2 with one abstain -> no majority -> election times out again -> another round; eventually timeouts diverge and one gets majority.
Common mistakes
- Incorrect quorum formula: using
ceil(N/2)is wrong for even N; the correct majority is⌊N/2⌋ + 1(equivalentlyceil((N+1)/2)). - Forgetting persistence: acceptors (Paxos) and servers (Raft) must persist
acceptedandcurrentTerm/votedFor/logto stable storage before replying; forgetting this breaks safety after crashes. - For Raft, saying leader commits entry as soon as it is appended to one follower — must be majority.
- Not stating the election restriction in Raft: voters only grant vote if candidate's log is at least as up-to-date.
For your exam
Types of questions you'll see:
- Definitions: explain consensus, safety, liveness, quorum, proposer/acceptor/learner, term, leader.
- Short notes: compare Paxos vs Raft, explain FLP and why practical systems assume partial synchrony.
- Derivations / proofs: Paxos safety proof (give the intersection argument), Raft safety sketch (election restriction and majority intersection).
- Diagrams: draw Paxos two-phase message flow; draw Raft leader election and AppendEntries flow and label messages.
- Traces: step-by-step execution of Paxos with given acceptors and proposal numbers; Raft leader failure and recovery traces.
- Programming/implementation questions: list persistent state needed and RPC signatures for Raft.
What a full-marks answer includes:
- Clear statements of assumptions (failure model, synchrony assumptions).
- Exact protocol steps (message names, when states update, what is persisted before reply).
- A correct safety proof or sketch citing quorum intersection and acceptor promise rules (for Paxos) or election restriction and majority replication (for Raft).
- Correct diagrams labelled with messages and states.
- For traces, show every message and state update at each step.
Quick check
- What property of majority quorums ensures Paxos safety?
- In Raft, what three pieces of state must be persisted to stable storage?
- State the FLP impossibility result in one line.
Answers: 1) Any two majorities intersect (have at least one server in common). 2)
currentTerm,votedFor, andlog[]. 3) In an asynchronous system, deterministic consensus is impossible if even one process may fail by crashing.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?