Distributed Consensus (Raft & Paxos)
1. What It Is & Why It Exists
The Core Problem: Agreement Across Unreliable Networks
In a distributed system, physical servers must coordinate state changes over an asynchronous, unreliable network subject to packet loss, arbitrary latency spikes, network partitions, and unannounced node crashes without Byzantine malice.
Coordinating state across such an environment without a single point of failure introduces the Distributed Consensus Problem: how can a cluster of independent machines agree on a single, deterministic sequence of values or state transitions?
The FLP Impossibility Theorem (Fischer, Lynch, Paterson, 1985)
The foundational theorem of distributed computing proves that in a purely asynchronous network, no deterministic consensus protocol can guarantee both Safety and Liveness in the presence of even a single unannounced fail-stop crash:
- Safety: Nothing bad happens (the cluster never commits two conflicting states or elects two active leaders).
- Liveness: Something good eventually happens (the cluster never deadlocks and always makes progress).
The Breakdown: Asynchronous Replication vs. 2PC vs. Quorum Consensus
Concrete Proof: The Split-Brain Blackout vs. Quorum Safety
Consider a 5-node cluster experiencing an asymmetric network partition dividing the cluster into two segments: a minority partition of 2 nodes () and a majority partition of 3 nodes ():
| Consensus Architecture | Behavior in Network Partition ( Split) | Safety Guarantee | Liveness Guarantee | Worst-Case Failure Mode |
|---|---|---|---|---|
| Primary-Backup (Async Replication) | Both partitions elect a primary. Both accept client writes. | π¨ Zero Safety: State permanently diverges (Split-Brain). | β High (Both sides accept writes) | Permanent data corruption requiring manual reconciliation. |
| Two-Phase Commit (2PC) | Coordinator cannot reach all 5 nodes; aborts all incoming transactions. | β Safe (No split-brain) | π¨ Zero Liveness: Cluster completely freezes if 1 node drops. | Total availability collapse under any single-node failure. |
| Quorum Consensus (Raft / Paxos) | Minority partition () rejects writes; Majority partition () continues processing. | π‘οΈ Linearizable Safety: Only 1 leader can secure a majority quorum. | π‘οΈ Continuous Liveness: Survives node failures. | Minority partition blocks writes until network heals. |
The First-Principles Solution: Quorum-Based Replicated State Machines
Practical consensus protocols (Raft, Multi-Paxos, Zab) circumvent the FLP Impossibility Theorem by introducing partial synchrony (randomized timers and heartbeat timeouts):
- Absolute Safety: Safety is mathematically guaranteed under all asynchronous conditions, regardless of network delays or packet reordering.
- Conditional Liveness: Liveness is guaranteed as long as a strict mathematical majority quorum of nodes () can communicate.
- Replicated State Machine (RSM) Model: If identical deterministic state machines on multiple servers process an identical, ordered sequence of inputs from a consensus log, they will produce an identical, consistent state across all nodes.
Interactive Architecture DiagramSynthesizing vector architecture diagram...
2. Core Mechanics & Algorithmic Architecture
The Raft Algorithm: 3 Decomposed Sub-Mechanisms
Raft decomposes the consensus problem into three strictly formalized sub-problems: Leader Election, Log Replication, and Safety.
Interactive Architecture DiagramSynthesizing vector architecture diagram...
1. Leader Election & Mathematical Quorum
- Nodes start as Followers. If a follower receives no heartbeat within a randomized
electionTimeout(), it transitions to Candidate, increments itscurrentTerm, votes for itself, and broadcastsRequestVoteRPCs. - A Candidate becomes Leader only after securing votes from a strict mathematical quorum:
- For , (tolerates node failure).
- For , (tolerates node failures).
- An even-numbered cluster () requires votes, providing the exact same fault tolerance () as while increasing network overhead. Always deploy odd-numbered clusters ().
2. Log Replication & The Log Matching Property
- The Leader receives commands from clients, appends them to its local Write-Ahead Log, and broadcasts
AppendEntriesRPCs. - An entry is Committed once it is safely written on a majority of nodes ().
- Log Matching Invariant: If two distinct logs contain an entry with the same index and term, they are guaranteed to store identical commands in all entries up through that index.
3. Linearizable Reads (Avoiding Stale Reads on Partitioned Leaders)
If a Leader is partitioned off, it might respond to read queries with stale data before discovering its isolation. Raft guarantees linearizable reads via two protocols:
- ReadIndex Protocol: The Leader records its current
commitIndex, broadcasts a heartbeat to confirm it still commands a majority quorum, and serves the read once ACKs arrive. - LeaseRead Protocol: The Leader relies on a physical time-bounded lease. As long as , it serves reads locally with zero network hops.
Step-by-Step Deterministic Write & Replication Pipeline
Interactive Architecture DiagramSynthesizing vector architecture diagram...
In-Memory & Distributed State Structures
Every Raft node maintains three distinct classes of state in memory and on disk:
| State Category | Variable Name | Type / Storage Medium | Purpose |
|---|---|---|---|
| Persistent on All Nodes | currentTerm | int64 (WAL on NVMe) | Latest term server has seen; monotonically increases |
| Persistent on All Nodes | votedFor | node_id (WAL on NVMe) | Candidate that received vote in current term (null if none) |
| Persistent on All Nodes | log[] | Array of entries (WAL) | Log entries containing command, index, and term |
| Volatile on All Nodes | commitIndex | int64 (RAM) | Index of highest log entry known to be committed |
| Volatile on All Nodes | lastApplied | int64 (RAM) | Index of highest log entry applied to state machine |
| Volatile on Leader Only | nextIndex[] | Array of int64 (RAM) | For each peer, index of next log entry to send |
| Volatile on Leader Only | matchIndex[] | Array of int64 (RAM) | For each peer, index of highest log entry known replicated |
Consensus Scenario & Quorum State Matrix
Under a 5-node cluster () with quorum requirement , and initial Term 2 Leader :
| Step # | Event / Input | In-Memory / Distributed State | Evaluation & Transition | Outcome / Cluster State |
|---|---|---|---|---|
| 1 | Client write to Leader SET balance = 500 | 5 nodes active, Term 2; Quorum threshold | writes Index 10, broadcasts AppendEntries;reply ACK ( slow, down). Total ACKs: 3 | Commit Succeeded () entry committed; applies to state machine and returns 200 OK |
| 2 | Asymmetric network partition isolates from | Minority (2 nodes); Majority (3 nodes) | Client sends write to ; can only get 2 ACKs () blocked. election timeout trips (180ms); starts Term 3 election | Split-Brain Prevented freezes uncommitted writes; secures 3/3 votes and becomes legitimate Term 3 Leader |
| 3 | Network partition heals; all 5 nodes re-establish TCP | at Term 2 (stale uncommitted entry); at Term 3 (authoritative leader) | sends heartbeat to ; rejects with higher term (Term 3 > Term 2).steps down to Follower; syncs authoritative log | Authoritative Log Overwrite and overwrite uncommitted Term 2 entries with Term 3; cluster unified |
3. Data Migration, Anti-Entropy & Consistency Protocols
1. Log Compaction & Snapshotting
Because an append-only log grows indefinitely, servers would eventually run out of disk space and take hours to replay logs upon reboot. Raft handles this via Memory Snapshotting:
- An application periodically takes a point-in-time snapshot of its state machine (e.g., at Index 10,000).
- All log entries up through Index 10,000 are deleted from disk.
- The
InstallSnapshotRPC: If a lagging follower or newly added node is so far behind that its missing entries have already been compacted, the Leader streams its latest snapshot file directly to the follower over the network.
Interactive Architecture DiagramSynthesizing vector architecture diagram...
2. Dynamic Cluster Membership Changes (Joint Consensus)
Adding or removing nodes cannot be done via static configuration changes on all machines, as two independent majorities could vote at the same time during the rollout window.
- Raft Joint Consensus: The cluster transitions through an intermediate phase () where decisions require independent majorities from both the old configuration and the new configuration:
- Once is committed, the leader commits the final configuration .
3. Accelerated Log Conflict Resolution & Graceful Draining
- Accelerated Log Backtracking: In naive Raft, if a follower's log diverges across 1,000 entries, the leader decrements
nextIndexby 1 per rejectedAppendEntriesRPC (costing 1,000 network round-trips). In the optimized protocol, the follower returns the conflicting entry's term (conflictTerm) and the earliest index of that term (conflictIndex). The leader skipsnextIndexpast the entire conflicting term in a single RPC, accelerating log synchronization after network partition healing. - Graceful Leader Step-Down & Node Draining: When an active leader node is selected for host maintenance or rolling restarts:
- Operator triggers
etcdctl move-leader <target_follower_id>(or issues RaftTimeoutNowRPC). - The leader halts client writes, synchronizes uncommitted log entries to the target follower, and commands the follower to initiate an immediate election without waiting for election timeout.
- The target follower wins the election immediately with zero downtime.
- The retiring node drains client gRPC connections and shuts down gracefully without triggering cluster-wide election storms.
- Operator triggers
Unlock Complete Architecture & Production Runbooks
You have explored the free architectural preview (~46%). Spend 1 Coin to unlock the remaining 7 production deep-dive sections for a full 24 hours.