Track 2: Consensus Protocols
Consensus is the most critical topic in distributed systems. Master this track to ace Staff+ interviews at top companies.Modules: 5
Key Topics: FLP Impossibility, Paxos, Raft, Viewstamped Replication, ZAB
Module 6: The Consensus Problem
What is Consensus?
Consensus is getting multiple nodes to agree on a single value, despite failures. The dinner reservation analogy: Imagine five friends trying to agree on a restaurant via a group chat where messages can be delayed, arrive out of order, or never arrive at all — and some friends might close the app mid-conversation. That is the consensus problem. It sounds trivial until you realize that “just pick the first suggestion” breaks when two people suggest simultaneously, and “wait for everyone to respond” breaks when someone goes offline. Every consensus protocol is fundamentally a clever answer to the question: “How do we make a group decision when we can’t even hold a reliable meeting?”Use Cases for Consensus
Leader Election
- Database primary selection
- Kafka partition leader
- Kubernetes control plane
Distributed Locking
- Zookeeper locks
- Redis Redlock
- etcd leases
Configuration Management
- Cluster membership
- Feature flags
- Service discovery
State Machine Replication
- Replicated databases
- Distributed logs
- Blockchain
FLP Impossibility Theorem
Safety vs Liveness
Module 7: Paxos Protocol
The Original Consensus Algorithm
Paxos was invented by Leslie Lamport in 1989 (published in 1998 after being rejected for being “too whimsical” in its original Greek parliament metaphor). Despite being notoriously difficult to understand — Lamport himself said “The Paxos algorithm, when presented in plain English, is very simple” and the community collectively disagreed — it’s the foundation of modern consensus.Basic Paxos Step by Step
- Phase 1: Prepare
- Phase 1b: Promise
- Phase 2: Accept
- Phase 2b: Decided
n and sends Prepare(n) to all acceptors.Prepare(n):Paxos with Failures
This is where Paxos shines - handling failures:Why Paxos is Safe
Multi-Paxos
Basic Paxos decides ONE value. Multi-Paxos decides a SEQUENCE:Module 8: Raft Consensus (Deep Dive)
Why Raft?
Raft State Machine
Raft Terms
Leader Election
- Election Trigger
- RequestVote RPC
- Election Process
Log Replication
The shared notebook analogy: Log replication is like a team that must keep identical lab notebooks. The leader writes an entry in their notebook and sends a copy to every team member. Each team member writes the entry in their own notebook, but only after checking that their previous entries match the leader’s — if there is a discrepancy, the leader walks them back until they find where their notebooks agree, then replays everything from that point forward. An entry is “committed” (permanent) only when a majority of team members have it in their notebooks. This ensures that even if some notebooks are destroyed, the committed entries survive. The core of Raft - replicating commands across nodes:AppendEntries RPC
Log Matching Property
Safety: Leader Completeness
Handling Cluster Membership Changes
Log Compaction (Snapshots)
Module 9: Viewstamped Replication
An alternative consensus protocol that predates Paxos:Module 10: ZAB (Zookeeper Atomic Broadcast)
ZAB Protocol
Zookeeper Guarantees
Comparison: Paxos vs Raft vs ZAB
Advanced: EPaxos (Egalitarian Paxos)
EPaxos Protocol Flow
When to Consider EPaxos
Advanced: Pipelining & Batching Optimizations
Production consensus systems use several optimizations to achieve high throughput despite the fundamental requirement of disk I/O and network round-trips.1. Request Pipelining
Instead of waiting for each request to commit before starting the next, leaders can process multiple requests concurrently.2. Batching Log Entries
Instead of one network round-trip per entry, batch multiple entries into a singleAppendEntries RPC.
- Low load: Send immediately (minimize latency)
- High load: Batch aggressively (maximize throughput)
3. Parallel Disk I/O
The leader can write to its own log while simultaneously sendingAppendEntries to followers.
4. Group Commit (fsync Batching)
fsync() is expensive (~10ms on HDD, ~0.1ms on NVMe). Instead of fsync per entry, batch multiple entries into one fsync.
5. Flow Control & Backpressure
Prevent slow followers from causing unbounded memory growth on the leader.Performance Numbers (etcd Benchmarks)
Practical Implementation Guide
Building a Production Consensus System
Start with Raft (Not Paxos)
Test Adversarially
Performance Tuning
Production Checklist
Common Implementation Bugs
Module 11: Quorum Loss & Disaster Recovery
A critical “Principal Level” operational reality: What happens when you lose a majority of your nodes forever? (e.g., a region outage or physical data corruption).The Quorum Loss Problem
Consensus protocols (Paxos/Raft) are designed to block when a majority is lost. This is Safe but leads to Permanent Unavailability.- In a 3-node cluster, if 2 nodes are destroyed, the remaining node cannot reach consensus.
- You cannot simply “add new nodes” because adding nodes requires a consensus vote, which you can’t get.
Recovery Strategies
1. Forced Reconfiguration (The “God Mode” fix)
Most production implementations (etcd, Consul, Zookeeper) provide a tool to manually override the configuration.- Process:
- Stop the remaining node.
- Use a tool to rewrite the
conffile or metadata on disk to say: “The cluster now only consists of ME.” - Restart the node. It now has a majority (1/1) and can process writes.
- Gradually add new nodes to rebuild the cluster to or .
2. Seed-based Recovery
In systems like Cassandra or FoundationDB, you can bootstrap a new cluster from a snapshot of the surviving node’s data and “re-seed” the consensus state.3. The “Stale Read” Escape Hatch
If you only need to recover data (not resume writes), you can often perform Stale Reads from the remaining nodes by bypassing the consensus layer and reading directly from the state machine (SSTables/RocksDB). Staff Tip: Disaster recovery is the only time you should ever touch the internal state of a consensus engine. Mention the “etcd disaster recovery” guide in interviews to show you understand that safety isn’t just about code, but about operational survival.Key Interview Questions
Q: Walk me through a Raft leader election
Q: Walk me through a Raft leader election
- Follower times out (no heartbeat from leader)
- Converts to candidate, increments term
- Votes for itself, sends RequestVote to all
- Other nodes vote (if haven’t voted, log is up-to-date)
- If majority votes → becomes leader, sends heartbeats
- If receives AppendEntries from valid leader → becomes follower
- If timeout again → new election with higher term
- Randomized timeouts prevent split votes
- Log up-to-date check ensures safety
- At most one leader per term
Q: What happens if the Raft leader fails during commit?
Q: What happens if the Raft leader fails during commit?
- Followers detect leader failure (timeout)
- New election starts
- Only nodes with the entry CAN become leader (election restriction)
- New leader has the entry, completes replication
- Entry gets committed when new-term entry is committed
Q: How does Paxos handle competing proposers?
Q: How does Paxos handle competing proposers?
- Each proposer picks unique proposal number (higher wins)
- Acceptor promises to reject lower numbers
- If proposer’s Prepare rejected → retry with higher number
- In Accept phase, use highest accepted value from promises
- System makes progress when one proposer “wins”
Q: Why can't consensus be achieved in asynchronous systems?
Q: Why can't consensus be achieved in asynchronous systems?
- Can’t distinguish slow from dead
- Adversarial schedule can always prevent decision
- Must choose: safety OR guaranteed termination
Q: Design a distributed lock using consensus
Q: Design a distributed lock using consensus
Hands-On Project: Implement Raft
Raft Implementation Lab
- Implement RequestVote RPC
- Handle election timeouts
- State transitions (follower → candidate → leader)
- Implement AppendEntries RPC
- Log matching checks
- Commit index tracking
- Persist term, votedFor, log
- Recovery after restart
- Implement log compaction
- InstallSnapshot RPC
- MIT 6.824 Labs
- Raft visualization: raft.github.io
- etcd/raft source code
Next Steps
Continue to Track 3: Replication Strategies
Interview Deep-Dive
In a Raft cluster, what exactly happens during a leader election when the network partitions into two groups of unequal size? Walk me through the sequence of events on both sides.
In a Raft cluster, what exactly happens during a leader election when the network partitions into two groups of unequal size? Walk me through the sequence of events on both sides.
- Assume a 5-node cluster (A, B, C, D, E) where A is the current leader. The partition splits into (minority) and (majority).
- On the minority side: A continues sending heartbeats to B, and B responds. A also tries to send heartbeats to C, D, E but gets no response. If A tries to commit a new write, it needs 3 acknowledgments (majority of 5). It can only get 2 (A itself and B), so A cannot commit any new entries. A remains the leader of term T on its side, but it is operationally frozen — it can accept client requests but cannot commit them. Eventually, depending on the implementation, A may step down or reject client writes directly.
- On the majority side: C, D, and E stop receiving heartbeats from A. After a randomized election timeout (e.g., 150-300ms), one of them — say C — times out first, increments the term to T+1, votes for itself, and sends RequestVote to D and E. Both grant votes (since they have not voted in term T+1 and C’s log is at least as up-to-date). C becomes the leader of term T+1 with a majority quorum of . This side can now accept and commit new writes.
- When the partition heals: A sends a heartbeat to C with term T. C responds with term T+1. A sees a higher term, immediately steps down to follower, and adopts term T+1. Any uncommitted entries in A’s log (entries accepted during the partition but not committed) may be overwritten by C’s log during the next AppendEntries exchange. This is safe because those entries were never committed — no client received a success response for them.
Compare Raft and Multi-Paxos. In what scenarios would you choose Multi-Paxos over Raft?
Compare Raft and Multi-Paxos. In what scenarios would you choose Multi-Paxos over Raft?
- Raft and Multi-Paxos solve the same fundamental problem — replicated state machines — but with different design philosophies. Raft prioritizes understandability by decomposing the problem into leader election, log replication, and safety as separate subproblems. Multi-Paxos prioritizes flexibility by defining consensus on individual log slots independently.
- The key structural difference: Raft requires a strong leader. All writes go through the leader, and the leader’s log is always the authoritative truth. Multi-Paxos can operate with a “distinguished proposer” (de facto leader) for performance, but any node can propose for any log slot. This means Multi-Paxos can continue making progress even if the leader is temporarily slow (another node proposes for that slot), while Raft must wait for a leader election.
- I would choose Multi-Paxos (or variants like EPaxos) in geo-distributed deployments where leader-based protocols create latency hotspots. If you have 5 data centers across continents, Raft forces all writes through one leader, adding cross-continent latency. EPaxos (an extension of Paxos) allows any node to propose, and non-conflicting commands can be committed in a single round trip to the nearest quorum. This can cut write latency in half for geo-distributed workloads.
- I would choose Raft for everything else. The implementation is more straightforward, the debugging is simpler (one leader means one source of truth), and the ecosystem is mature (etcd, Consul, TiKV, CockroachDB all use Raft).
A junior engineer asks you: 'If consensus needs a majority quorum, does that mean we can never have an even number of nodes?' What do you tell them?
A junior engineer asks you: 'If consensus needs a majority quorum, does that mean we can never have an even number of nodes?' What do you tell them?
- You can absolutely have an even number of nodes, but it is almost never a good idea. Consider a 4-node Raft cluster: the majority quorum is 3 (more than half of 4). You can tolerate exactly 1 failure. Now consider a 3-node cluster: the majority quorum is 2, and you can also tolerate exactly 1 failure. So going from 3 to 4 nodes gives you zero additional fault tolerance while increasing the number of nodes that must acknowledge each write (from 2 to 3), which increases latency.
- This is why consensus clusters almost always use odd numbers: 3 (tolerates 1 failure), 5 (tolerates 2), 7 (tolerates 3). Each additional pair of nodes increases fault tolerance by exactly one.
- There is an edge case where even numbers appear: Flexible Paxos allows asymmetric quorums where the write quorum and read quorum can differ, as long as their sum exceeds N. In that model, a 4-node cluster with write quorum 3 and read quorum 2 could be useful if reads are much more frequent than writes. But this is an advanced configuration that most systems do not support out of the box.
Explain what safety and liveness mean in the context of consensus protocols. Can Raft violate either one?
Explain what safety and liveness mean in the context of consensus protocols. Can Raft violate either one?
- Safety means “nothing bad ever happens.” For Raft, safety means: (1) at most one leader per term, (2) a committed entry is never lost or overwritten, (3) if two logs contain an entry with the same index and term, they are identical and all preceding entries are identical. Safety properties must hold under all circumstances — crashes, partitions, message delays, any adversarial schedule of events.
- Liveness means “something good eventually happens.” For Raft, liveness means: the system eventually elects a leader and makes progress (commits entries). Liveness requires timing assumptions — specifically, that the broadcast time is much less than the election timeout, which is much less than the mean time between failures. If the network is completely asynchronous (unbounded delays), Raft’s liveness is not guaranteed (per FLP impossibility).
- Raft never violates safety. Even under the worst network conditions, two different leaders cannot commit conflicting entries for the same log index. This is ensured by the election restriction (candidates must have an up-to-date log) and the log matching property (AppendEntries checks prevLogIndex/prevLogTerm).
- Raft can violate liveness. If the election timeout is too short relative to network latency, the cluster can enter a cycle of perpetual elections where no candidate wins a majority before the next timeout fires. This is mitigated by randomized election timeouts, but it is theoretically possible (though statistically improbable) for this to continue indefinitely. In practice, poor timeout tuning is the most common cause of Raft liveness issues.