Skip to main content
← PROBLEMS / ARCHITECTURE
An end-to-end domain learning journey

Raft Consensus &
Leader Election Safety.

Raft guarantees state-machine safety across crash and network partitions through five strict invariants—Election Safety, Leader Append-Only, Log Matching, Leader Completeness, and State Machine Safety—all of which break if term/commit rules are shortcut.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When a single bottleneck threatens end-to-end availability, never commit log entries from a previous term by counting replicas alone (Figure 8 bug); a leader may only advance `commitIndex` for entries from its `currentTerm`, and linearizable reads require `ReadIndex` quorum heartbeats.

TL;DR30-second simplified summary
▾

Core Mechanics: A 5-node metadata store (etcd/Consul-style) across 3 AZs (15 ms cross-AZ RTT) relies on Raft for linearizable consensus.

Visual & Structural Flow: Depicts Why Previous-Term Entries Cannot Commit by Replica Count Alone (S1 (Term 2) -> S2 & S3 -> S5 (Term 3 log)); Follower, Candidate, and Leader Safety Transitions (FOLLOWER -> CANDIDATE -> LEADER).

Trade-Offs & Production: Skipping fsync() on currentTerm, votedFor, and log[] before replying to RequestVote or AppendEntries allows a rebooted node to vote twice in the same term (two leaders in one term). Production Raft engines (etcd/tikv) enforce strict safety with bounded 150–300 ms randomized election timeouts and 50 ms heartbeats: Log Up-to-Date Election Restriction.

Failure Modes & Application: Raft is the standard consensus protocol for strongly consistent control planes and sharded storage: Kubernetes etcd & Consul: Stores cluster state, service discovery, and leader leases.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Split-Brain Prevention
Split-brain happens when a network partition splits a distributed cluster into isolated groups that both elect a primary and accept conflicting writes; preventing it requires strict majority quorums (N/2 + 1), time-bounded leases, and monotonic fencing tokens.
Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why subtle Raft bugs silently corrupt distributed locks and metadata.

Why this matters: The mechanism: understand how Why subtle Raft bugs silently corrupt distributed locks and metadata works from first principles.

Think of Why subtle Raft bugs silently corrupt distributed locks and metadata as the intuition layer for Raft Consensus & Leader Election Safety: The mechanism: understand how Why subtle Raft bugs silently corrupt distributed locks and metadata works from first principles.

A 5-node metadata store (etcd/Consul-style) across 3 AZs (15 ms cross-AZ RTT) relies on Raft for linearizable consensus. If a leader commits entries from a previous term merely by counting replicas, or serves reads without verifying it is still the active quorum leader, a crash or asymmetric partition causes split-brain and lost committed keys.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

The Raft Figure 8 anomaly and stale reads from deposed leaders.

Why this matters: The problem: see what breaks without The Raft Figure 8 anomaly and stale reads from deposed leaders under real concurrency or scale.

Two classic bugs break Raft State Machine Safety:

  1. Figure 8 Overwrite: Leader S1 (term 2) replicates entry k to {S1, S2, S3} and crashes before committing it. S5 (which missed k, but had a higher-term entry from term 3) wins election in term 4 and overwrites k—even if k was already on a majority!
  2. Deposed Leader Stale Reads: A partitioned old leader continues serving its local in-memory state machine before its heartbeat timeout fires.
Raft Figure 8 & ReadIndex

Why Previous-Term Entries Cannot Commit by Replica Count Alone

S1 (Term 2)S2 & S3S5 (Term 3 log)1. Replicates Term-2 entry (3/5)2. S1 crashes before Term-4 commit3. S5 wins Term 4 (higher logterm)4. Overwrites Term-2 entry!5. Fix: commit only currentTerm

A leader may only advance commitIndex for entries from its currentTerm; older-term entries commit only indirectly.

Engineering Decision Framework
Problem
How to implement Raft Consensus & Leader Election Safety without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When a single bottleneck threatens end-to-end availability, never commit log entries from a previous term by counting replicas alone (Figure 8 bug); a leader may only advance commitIndex for entries from its currentTerm, and linearizable reads require ReadIndex quorum heartbeats.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Raft Consensus & Leader Election Safety experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

Why async WAL writes and unverified leader reads break linearizability.

Why this matters: The problem: see what breaks without Why async WAL writes and unverified leader reads break linearizability under real concurrency or scale.

Think of Why async WAL writes and unverified leader reads break linearizability as the intuition layer for Raft Consensus & Leader Election Safety: The problem: see what breaks without Why async WAL writes and unverified leader reads break linearizability under real concurrency or scale.

Skipping fsync() on currentTerm, votedFor, and log[] before replying to RequestVote or AppendEntries allows a rebooted node to vote twice in the same term (two leaders in one term). Likewise, serving GET directly from the leader's in-memory map without a quorum check returns stale data during asymmetric partitions.

Design Trade-Off

Why async WAL writes and unverified leader reads break linearizability

Before · Async Primary / Split-Brain
  • Stale leader overwrites state
  • Clock skew breaks lease order
  • Full-table sync on reboot
After · Quorum + Monotonic Fencing
  • Majority quorum prevents split-brain
  • Fencing tokens reject zombies
  • Merkle/WAL catch-up in O(log N)
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise solution: Five Raft Invariants, currentTerm Commit, and ReadIndex.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Production Raft engines (etcd/tikv) enforce strict safety with bounded 150–300 ms randomized election timeouts and 50 ms heartbeats:

  • Log Up-to-Date Election Restriction: RequestVote rejects any candidate whose (lastLogTerm, lastLogIndex) is behind the voter's.
  • currentTerm Commit Rule: Leader advances commitIndex only when log[N].term == currentTerm and a majority (3/5) has persisted it (fsync 2–5 ms batched).
  • Linearizable ReadIndex (Zero Disk Writes): Leader records readIndex = commitIndex, sends a heartbeat round to confirm quorum, waits for lastApplied >= readIndex, and serves the read locally.
Raft Node Roles

Follower, Candidate, and Leader Safety Transitions

electionTimeout elapsed3/5 votes + up-to-date loghigher term observedFOLLOWERfsync term/vote/logCANDIDATE150-300ms rand timeoutLEADERReadIndex + currentTerm

Randomized 150-300ms election timeouts avoid split votes while ReadIndex guarantees linearizable reads without disk writes.

05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where Raft consensus powers critical infrastructure.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Raft is the standard consensus protocol for strongly consistent control planes and sharded storage:

  • Kubernetes etcd & Consul: Stores cluster state, service discovery, and leader leases.
  • Distributed Locks & Fencing Tokens: Generates monotonically increasing term + index fencing tokens.
  • TiKV / CockroachDB (Multi-Raft): Runs thousands of independent Raft groups per node for horizontal scale.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

How does Raft's `ReadIndex` protocol serve linearizable reads without writing a no-op entry to the disk WAL on every read?

Recommended Learning Flow