FullStack AI Hub
Studio
System Design · 05. Reliability
13 min
11 steps
Intermediate

Distributed Consensus

Elect leaders safely, commit replicated logs across majority quorums, and survive network partitions without split-brain using Raft.

System Design05. ReliabilityLesson 3 of 4
13 minIntermediate11 steps

Distributed Consensus

Elect leaders safely, commit replicated logs across majority quorums, and survive network partitions without split-brain using Raft.

NODES
2 (even!)
TIE-BREAKER
None
SPLIT-BRAIN
Critical
CMD RATE
1,200/s
partition?Control PlaneNode A (Claims L)74%thinks B deadNode B (Claims L)74%thinks A dead
AppendEntries / commit
heartbeat / vote RPC
client command
partition / minority drop
In This LessonStep 1 of 11
What You Will Master
  • ✓Understand why majority quorums (⌊N/2⌋ + 1) guarantee any two majorities overlap by at least one node
  • ✓Trace Raft terms, heartbeat timeouts, randomized election timers, and leader election without split votes
  • ✓Follow Raft two-phase log replication: append to followers, wait for majority ACK, then commit
  • ✓Prove how Raft prevents split-brain during network partitions and size clusters (3 vs 5 nodes) wisely

Architectural Trade-Off Comparison Matrix

PatternBest ForKey Trade-Off
3-Node Raft QuorumMetadata stores (etcd, Consul) tolerating 1 node crashLosing 2 nodes halts writes; maintenance + crash simultaneously fails
5-Node Raft QuorumProduction control planes surviving 1 planned reboot + 1 crashLeader replicates to 4 peers; slightly higher network fan-out
Randomized TimersBreaking split-vote ties rapidly (150–300 ms election timeout)Brief ~200–500 ms write pause while a new term leader elects
Lease / ReadIndexServing linearizable reads from the Leader without disk log writesMinority stale leader must confirm quorum heartbeat before answering

Step-by-Step Architectural Breakdown (11 Steps)

Full architectural walkthrough transcript and state transitions for Distributed Consensus.

STEP 01 · PROBLEMJump to step →

Why agreeing across flaky networks is so hard

Distributed locks, Kubernetes (`etcd`), and database failover coordinators all need **multiple servers to agree on a single truth**—like *"who is the active Leader right now?"*

Over a real network, you cannot tell the difference between a **crashed server** and a **slow network partition**. Without a formal consensus protocol, two nodes can both claim leadership and corrupt state.

watch:Never try to invent ad-hoc leader election with simple heartbeats and timers—proven consensus protocols like Raft and Paxos solve subtle edge cases.

Distributed ConsensusSplit-Brain RiskFLP Impossibility
STEP 02 · SOLUTIONJump to step →

Majority Quorum (⌊N/2⌋ + 1): why odd numbers win

Add a 3rd node so cluster size is odd (`N = 3`). Every decision—electing a leader or committing a log entry—requires a strict **Majority Quorum** of **`⌊N/2⌋ + 1 = 2` nodes**.

By the pigeonhole principle, **any two majorities MUST overlap by at least one node**. Therefore, it is mathematically impossible for two leaders to be elected in the same term!

good:Always deploy odd cluster sizes (3, 5, or 7): a 4-node cluster still needs 3 votes, so it tolerates only 1 failure—identical to 3 nodes at higher cost!

Majority QuorumOdd Cluster SizingQuorum Intersection
STEP 03 · TECHNIQUEJump to step →

Raft roles & monotonic Terms (logical clock)

Every Raft node is always in one of three states: **Leader** (handles all client writes), **Follower** (passive replica), or **Candidate** (asking for votes to become leader).

Time is divided into numbered **Terms** (`Term 1, Term 2, Term 3…`). Every RPC includes the sender’s current Term—if any server sees a higher Term number, it **immediately steps down to Follower**.

idea:Raft Terms act as a distributed logical clock—guaranteeing stale leaders recognize they were superseded the instant they talk to any peer.

Leader / Follower / CandidateRaft TermHeartbeat Timer
STEP 04 · TECHNIQUEJump to step →

Leader crashes → Candidate wins Term #2 election

Node **S1** loses power. **S2’s** election timer expires first: it increments to **Term #2**, flips to **Candidate**, votes for itself, and broadcasts `RequestVote(Term 2)` to peers.

Healthy followers verify S2’s log is at least as up-to-date as their own, grant their votes, and S2 hits **majority quorum**—becoming the new Leader in under 250 ms!

good:Election Safety: each server votes for at most ONE candidate per term, and only if the candidate’s log contains all previously committed entries.

RequestVote RPCLog Up-To-Date CheckSub-Second Election
STEP 05 · TECHNIQUEJump to step →

Randomized election timeouts break split votes

What if two followers time out on the **exact same millisecond**, both become Candidates, and split the votes evenly? Nobody reaches a majority—a **Split Vote**!

Raft’s brilliantly simple fix: every node picks a **random election timeout between 150 ms and 300 ms**. On the next round, one candidate wakes up first, collects majority votes cleanly, and stabilizes the cluster.

idea:Randomizing timers breaks symmetry without any extra coordination protocol—resolving split votes in a single round almost every time.

Split VoteRandomized Election TimeoutSymmetry Breaking
STEP 06 · TECHNIQUEJump to step →

Two-phase log replication: append, quorum ACK, commit

When a client writes `SET lock = worker_7`, the Leader appends the entry **uncommitted** to its local log and sends `AppendEntries` in parallel to all followers.

The exact instant a **majority (3 of 5)** persist the entry on disk and ACK, the Leader marks the entry **COMMITTED**, applies it to its state machine, replies **200 OK** to the client, and notifies followers on the next heartbeat.

good:Notice Raft only waits for the FASTEST majority—a single sluggish or offline follower never slows down client commits!

AppendEntries RPCMajority Commit IndexState Machine Replication
STEP 07 · PROBLEMJump to step →

Network Partition: minority stalls, majority keeps moving

A router switch cuts a **5-node Raft cluster** into two halves: **Minority Side (Old Leader S1 + S2 = 2 nodes)** and **Majority Side (S3, S4, S5 = 3 nodes)**.

On the Minority side, Old Leader S1 can only get **2 / 5 ACKs**—not a quorum (`need 3`)—so it **refuses to commit** any client writes! Meanwhile, the 3-node Majority safely elects **S3 (Term #2)** and keeps committing cleanly.

good:This is CP (Consistency + Partition Tolerance) in action: sacrificing availability on the isolated minority guarantees ZERO split-brain corruption.

Network Partition (Netsplit)Minority FreezeCP Consistency
STEP 08 · SOLUTIONJump to step →

Partition heals: Old Leader steps down & overwrites uncommitted log

When the network cable is plugged back in, **Old Leader (Term 5)** receives an `AppendEntries(Term 6)` heartbeat from the **New Leader**. Seeing `6 > 5`, Old Leader immediately **steps down to Follower**.

Any uncommitted entries sitting in Old Leader’s local log are **safely truncated and overwritten** with the authoritative Term #6 committed log—bringing all 5 nodes back into bit-for-bit identical agreement!

good:Raft’s Log Matching Property guarantees that uncommitted minority entries are discarded cleanly and NEVER leak to clients.

Leader Step-DownLog Truncation & Catch-UpLog Matching Property
STEP 09 · TECHNIQUEJump to step →

Serving fast Linearizable Reads with ReadIndex

If a client sends a read directly to an isolated Old Leader that hasn’t realized it lost leadership yet, it could return **stale data**! Writing every read to the Raft log would be safe, but way too slow.

Instead, Raft uses **ReadIndex (or Leader Leases)**: the Leader records its current commit index, fires one lightweight **heartbeat round** to confirm it is still Leader, and serves the linearizable read straight from RAM—zero disk write!

idea:ReadIndex gives strict linearizability at 10× the speed of log-appended reads—used directly by etcd and TiKV.

Linearizable ReadReadIndex HeartbeatLeader Lease
STEP 10 · TRADE-OFFJump to step →

Sizing Raft clusters: why 5 beats 3 and 7 is rarely worth it

A **3-node cluster** tolerates 1 failure—meaning if you take 1 node down for an OS patch and a 2nd node crashes, **your entire cluster halts**! A **5-node cluster** tolerates **2 failures** (1 planned reboot + 1 unexpected crash).

Why not 15 nodes? Every write must replicate from the single Leader to `N − 1` followers—past **5–7 nodes**, write fan-out and network latency degrade rapidly with little extra reliability gain.

good:Rule of thumb: use 3 nodes for dev/staging, 5 nodes for production control planes (etcd/ZooKeeper/Consul), and shard into multiple small Raft groups (Multi-Raft) when scaling data!

3 vs 5 Node SizingPlanned Maintenance WindowMulti-Raft Sharding
STEP 11 · RECAPJump to step →

Distributed Consensus mental model recap

Consensus protocols like **Raft** power every reliable distributed lock, service registry, and database metadata store: **odd majority quorums**, **monotonic Terms**, **randomized election timers**, **two-phase quorum commits**, and **Multi-Raft sharding** when scaling out.

Kill two nodes below in the 5-node Raft cluster to confirm quorum survival end-to-end.

good:Use proven 5-node Raft stores (etcd/Consul/CockroachDB) for coordination state—never roll your own leader election over raw heartbeats.

Raft BlueprintQuorum SafetyCP Coordination Store

Related Production Deep-Dives & Simulators

Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.