Skip to main content
Primitives/Primitive #09
PRIMITIVE #09Core Distributed Systems Component

Distributed Consensus (Raft & Paxos)

AWS Production Mapping:DynamoDBS3AuroraECS

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 (S1,S2S_1, S_2) and a majority partition of 3 nodes (S3,S4,S5S_3, S_4, S_5):

Consensus ArchitectureBehavior in Network Partition (2∣32 \mid 3 Split)Safety GuaranteeLiveness GuaranteeWorst-Case Failure Mode
Primary-Backup (Async Replication)Both partitions elect a primary. Both accept client writes.🚨 Zero Safety: State permanently diverges ().βœ… High (Both sides accept writes)Permanent data corruption requiring manual reconciliation.
()Coordinator cannot reach all 5 nodes; aborts all incoming transactions.βœ… Safe (No )🚨 Zero Liveness: Cluster completely freezes if 1 node drops.Total availability collapse under any single-node failure.
(Raft / Paxos)Minority partition (2/52/5) rejects writes; Majority partition (3/53/5) continues processing.πŸ›‘οΈ Linearizable Safety: Only 1 leader can secure a majority .πŸ›‘οΈ Continuous Liveness: Survives ⌊(Nβˆ’1)/2βŒ‹\lfloor(N-1)/2\rfloor 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):

  1. Absolute Safety: Safety is mathematically guaranteed under all asynchronous conditions, regardless of network delays or packet reordering.
  2. Conditional Liveness: Liveness is guaranteed as long as a strict mathematical majority of nodes (Q=⌊N/2βŒ‹+1Q = \lfloor N/2 \rfloor + 1) can communicate.
  3. 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 Diagram
Synthesizing 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 Diagram
Synthesizing vector architecture diagram...

1. Leader Election & Mathematical Quorum

  • Nodes start as Followers. If a follower receives no heartbeat within a randomized electionTimeout (150–300Β ms150\text{--}300\text{ ms}), it transitions to Candidate, increments its currentTerm, votes for itself, and broadcasts RequestVote RPCs.
  • A Candidate becomes Leader only after securing votes from a strict mathematical :

Q=⌊N2βŒ‹+1Q = \left\lfloor \frac{N}{2} \right\rfloor + 1

FaultΒ ToleranceΒ BoundΒ (F)=⌊Nβˆ’12βŒ‹\text{Fault Tolerance Bound } (F) = \left\lfloor \frac{N - 1}{2} \right\rfloor

  • For N=3N = 3, Q=2Q = 2 (tolerates 11 node failure).
  • For N=5N = 5, Q=3Q = 3 (tolerates 22 node failures).
  • An even-numbered cluster (N=4N = 4) requires Q=3Q = 3 votes, providing the exact same fault tolerance (F=1F = 1) as N=3N = 3 while increasing network overhead. Always deploy odd-numbered clusters (N=3,5,7N=3, 5, 7).

2. Log Replication & The Log Matching Property

  • The Leader receives commands from clients, appends them to its local , and broadcasts AppendEntries RPCs.
  • An entry is Committed once it is safely written on a majority of nodes (QQ).
  • 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:

  1. ReadIndex Protocol: The Leader records its current commitIndex, broadcasts a heartbeat to confirm it still commands a majority , and serves the read once ACKs arrive.
  2. LeaseRead Protocol: The Leader relies on a physical time-bounded lease. As long as tnow<tlast_majority_ack+Tleaset_{\text{now}} < t_{\text{last\_majority\_ack}} + T_{\text{lease}}, it serves reads locally with zero network hops.

Step-by-Step Deterministic Write & Replication Pipeline

Interactive Architecture Diagram
Synthesizing vector architecture diagram...

In-Memory & Distributed State Structures

Every Raft node maintains three distinct classes of state in memory and on disk:

State CategoryVariable NameType / Storage MediumPurpose
Persistent on All NodescurrentTermint64 ( on NVMe)Latest term server has seen; monotonically increases
Persistent on All NodesvotedFornode_id ( on NVMe)Candidate that received vote in current term (null if none)
Persistent on All Nodeslog[]Array of entries ()Log entries containing command, index, and term
Volatile on All NodescommitIndexint64 (RAM)Index of highest log entry known to be committed
Volatile on All NodeslastAppliedint64 (RAM)Index of highest log entry applied to state machine
Volatile on Leader OnlynextIndex[]Array of int64 (RAM)For each peer, index of next log entry to send
Volatile on Leader OnlymatchIndex[]Array of int64 (RAM)For each peer, index of highest log entry known replicated

Consensus Scenario & Quorum State Matrix

Under a 5-node cluster (S1,S2,S3,S4,S5S_1, S_2, S_3, S_4, S_5) with requirement Q=⌊5/2βŒ‹+1=3Q = \lfloor 5/2 \rfloor + 1 = 3, and initial Term 2 Leader S1S_1:

Step #Event / InputIn-Memory / Distributed StateEvaluation & TransitionOutcome / Cluster State
1Client write to Leader S1S_1
SET balance = 500
5 nodes active, Term 2;
Quorum threshold Q=3Q = 3
S1S_1 writes Index 10, broadcasts AppendEntries;
S2,S3S_2, S_3 reply ACK (S4S_4 slow, S5S_5 down). Total ACKs: 3
Commit Succeeded (1.2Β ms1.2\text{ ms})
3β‰₯Qβ€…β€ŠβŸΉβ€…β€Š3 \ge Q \implies entry committed; S1S_1 applies to state machine and returns 200 OK
2Asymmetric network partition
isolates {S1,S2}\{S_1, S_2\} from {S3,S4,S5}\{S_3, S_4, S_5\}
Minority {S1,S2}\{S_1, S_2\} (2 nodes);
Majority {S3,S4,S5}\{S_3, S_4, S_5\} (3 nodes)
Client sends write to S1S_1; S1S_1 can only get 2 ACKs (<3< 3) β†’\to blocked.
S3S_3 election timeout trips (180ms); starts Term 3 election
Prevented
S1S_1 freezes uncommitted writes; S3S_3 secures 3/3 votes and becomes legitimate Term 3 Leader
3Network partition heals;
all 5 nodes re-establish TCP
S1S_1 at Term 2 (stale uncommitted entry);
S3S_3 at Term 3 (authoritative leader)
S1S_1 sends heartbeat to S3S_3; S3S_3 rejects with higher term (Term 3 > Term 2).
S1S_1 steps down to Follower; S3S_3 syncs authoritative log
Authoritative Log Overwrite
S1S_1 and S2S_2 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 InstallSnapshot RPC: 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 Diagram
Synthesizing 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 (Cold,newC_{\text{old}, \text{new}}) where decisions require independent majorities from both the old configuration and the new configuration: QuorumJoint=Majority(Cold)∧Majority(Cnew)\text{Quorum}_{\text{Joint}} = \text{Majority}(C_{\text{old}}) \land \text{Majority}(C_{\text{new}})
  • Once Cold,newC_{\text{old}, \text{new}} is committed, the leader commits the final configuration CnewC_{\text{new}}.

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 nextIndex by 1 per rejected AppendEntries RPC (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 skips nextIndex past 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:
    1. Operator triggers etcdctl move-leader <target_follower_id> (or issues Raft TimeoutNow RPC).
    2. 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.
    3. The target follower wins the election immediately with zero downtime.
    4. The retiring node drains client connections and shuts down gracefully without triggering cluster-wide election storms.

Part 2: Production Deep-Dive Locked1 Coin = 24 Hours

Unlock Complete Architecture & Production Runbooks

Your Balance:40 Coins

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.

Sections Included in This 24-Hour Pass:
4. Client-Side vs. Proxy-Mediated Routing Topologies
5. Real-World Distributed Engine Comparison
6. Critical Edge Cases & Distributed Failure Modes
7. Production Pitfalls & Anti-Patterns (The "Gotchas")
8. AWS Cloud Service Implementation & Production Patterns
9. Production Sizing Matrix & Operational Runbook
10. Production Diagnostics: Telemetry Signatures & Incident Response Playbook
Keeps page unlocked for exactly 24 hoursSpend coins to fund LLM & compute infrastructure