SD System Design In Depth
0%
From-Scratch Build

Raft Leader Election & Quorum Log

Deterministic multi-node Raft consensus state machine implementing term monotonicity, RequestVote log-completeness safety, AppendEntries prevLogIndex/prevLogTerm consistency checks, and majority quorum commit advancement.

Interactive Build Lab 0/4 Steps Completed

Code & Verify in the Browser Workbench

Complete 4 progressive engineering steps in JavaScript, TypeScript, or C++20 (WebAssembly) against an in-browser Node.js v22, Bun v1.1 & Clang/WASI runtime (virtual filesystem, loopback TCP/HTTP, and automated unit tests) — zero local setup required.

1. Architectural Overview & The Raft Safety Invariants

Raft (Ongaro & Ousterhout, 2014) decomposes replicated state machine consensus into three cleanly separated subproblems: Leader Election, Log Replication, and Safety. Every cluster node is in one of three states at any instant: FOLLOWER, CANDIDATE, or LEADER.

flowchart LR Follower["FOLLOWER"] -->|"Election Timeout (term++)"| Candidate["CANDIDATE"] Candidate -->|"Receives Majority Votes (>= N/2 + 1)"| Leader["LEADER"] Candidate -->|"Discovers Higher Term / Leader"| Follower Leader -->|"Discovers Higher Term"| Follower

The 4 Non-Negotiable Raft Rules

  1. Monotonic Terms Act as Logical Clocks: Every RPC (RequestVote, AppendEntries) carries the sender's currentTerm. Any node observing rpc.term > currentTerm immediately updates currentTerm, clears votedFor, and steps down to FOLLOWER.
  2. Election Restriction (§5.4.1): A voter denies RequestVote if the candidate's log is less up-to-date than its own. Logs are compared by lastLogTerm first; if terms are equal, the longer lastLogIndex wins.
  3. Log Matching Property (prevLogIndex / prevLogTerm): AppendEntries is rejected unless the follower's log contains an entry at prevLogIndex whose term matches prevLogTerm. If a follower has conflicting uncommitted entries after prevLogIndex, they are truncated and overwritten.
  4. Current-Term Quorum Commit (§5.4.2): A leader marks index $N$ committed once a majority ($\lfloor C/2 \rfloor + 1$) of the cluster has replicated $N$ and log[N].term === currentTerm.

2. Verification & Running the Lab

bash
node demo.js
node test.js