Distributed Consensus: Raft, Multi-Paxos & Zab
Architect distributed state machines that agree on truth across node failures: Leader Election, Log Replication, Heartbeat timeouts, Split-Vote prevention with randomized timers, Multi-Paxos quorums, and how etcd/Consul power Kubernetes high availability.
What You Will Learn in This Lesson
- Why Distributed Consensus is required for Leader Election and Distributed Locks
- The 3 states of a Raft Node: Follower, Candidate, and Leader
- The Raft Log Replication consensus protocol: appending log entries, quorum matching (N/2 + 1), and Commit Index
- Handling network partitions (Split-Brain) and recovering with Term numbers
Introduction & Core Concept
Kubernetes (etcd), Apache Kafka (KRaft), CockroachDB, and HashiCorp Consul rely on Raft consensus to coordinate cluster state, execute leader elections, and guarantee zero split-brain data corruption.
Syntax & Structure
// Raft RequestVote RPCstruct RequestVoteArgs { term: int, candidateId: string, lastLogIndex: int, lastLogTerm: int}Simulating Raft Leader Election and Quorum Consensus in JavaScript
javascript1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768// Raft Consensus State Machine & Leader Election Simulationclass RaftNode {constructor(id, peers) {this.id = id;this.peers = peers; // Array of peer node IDsthis.currentTerm = 0;this.votedFor = null;this.state = 'FOLLOWER'; // FOLLOWER, CANDIDATE, LEADERthis.log = [];this.commitIndex = 0;this.votesReceived = 0;}startElection() {this.state = 'CANDIDATE';this.currentTerm += 1;this.votedFor = this.id;this.votesReceived = 1; // Vote for selfconsole.log(`[${this.id}] Timed out! Starting Election for Term ${this.currentTerm}...`);// Request votes from all peer nodesthis.peers.forEach(peer => {peer.handleRequestVote(this.id, this.currentTerm, this.log.length - 1);});}handleRequestVote(candidateId, candidateTerm, candidateLastLog) {// Reject if candidate term is olderif (candidateTerm > this.currentTerm) {this.currentTerm = candidateTerm;this.state = 'FOLLOWER';this.votedFor = null;}if (candidateTerm === this.currentTerm && (this.votedFor === null || this.votedFor === candidateId)) {this.votedFor = candidateId;console.log(`[${this.id}] Voted YES for Candidate ${candidateId} in Term ${candidateTerm}`);return true;}return false;}receiveVote() {this.votesReceived++;// Quorum condition: strictly greater than N / 2 votesconst majority = Math.floor((this.peers.length + 1) / 2) + 1;if (this.votesReceived >= majority && this.state === 'CANDIDATE') {this.state = 'LEADER';console.log(`👑 [${this.id}] Achieved Quorum (${this.votesReceived} votes)! Promoted to CLUSTER LEADER for Term ${this.currentTerm}.`);}}}// Instantiate 3-node Raft Clusterconst nodeA = new RaftNode("Node_A", []);const nodeB = new RaftNode("Node_B", []);const nodeC = new RaftNode("Node_C", []);nodeA.peers = [nodeB, nodeC];nodeB.peers = [nodeA, nodeC];nodeC.peers = [nodeA, nodeB];console.log("=== Distributed Raft Consensus Engine ===");nodeA.startElection();nodeA.receiveVote(); // From Node_BnodeA.receiveVote(); // From Node_Cconsole.log("✅ Raft cluster achieved consensus with guaranteed quorum safety!");
Line-by-Line Technical Breakdown
Try It Yourself (Interactive Editor)
Modify the code in real-time and click Run to test live browser output and console logs.
Common Mistakes & How to Avoid Them
#1: Configuring an even number of consensus nodes (e.g. 4 nodes or 6 nodes) in production etcd/ZooKeeper clusters.
Consensus requires majority `(N/2 + 1)`. A 4-node cluster requires 3 nodes for quorum (tolerating 1 failure). A 3-node cluster also requires 2 nodes for quorum (tolerating 1 failure). Always use odd cluster sizes (3, 5, 7).
cluster_nodes = 4 // Can tolerate only 1 failure (Quorum = 3), same as 3 nodes!cluster_nodes = 3 or 5 // 3 nodes tolerate 1 failure; 5 nodes tolerate 2 failuresIndustry Best Practices & Professional Standards
- Deploy 3 or 5 nodes across independent availability zones (AZs) for etcd clusters.
- Use SSD/NVMe drives with low fsync latency for consensus write-ahead logs.
- Rely on managed consensus stores (etcd, Consul) rather than attempting to write custom Raft implementations.
Lesson Summary & Core Takeaways
- Distributed consensus guarantees linearizable truth across crashing network nodes.
- Raft uses Leader Election, Randomized Timers, and Quorum Log Replication.
- Odd-numbered node clusters (3, 5) prevent split-brain partition failures.