Consensus and Leader Election
How a group of machines agrees on one value or one leader, even when some of them crash or the network misbehaves.
What is it?
Many systems need several machines to agree on something: who the current leader is, which config is live, or the order of writes in a log. Agreeing sounds easy until you remember that machines crash, messages get delayed or lost, and nobody can tell a dead machine from a slow one.
Consensus is the problem of getting a group of nodes to decide on a single value so that:
- Agreement: every node that decides, decides the same value.
- Validity: the decided value was actually proposed by someone.
- Termination: every node that doesn't crash eventually decides.
The first two are safety properties (nothing bad happens). The third is liveness (something good eventually happens).
Why it's hard. The FLP result (Fischer, Lynch and Paterson, 1985) proves that in a fully asynchronous network, where messages can take arbitrarily long, no deterministic algorithm can guarantee consensus if even one node might crash. The intuition: when a node goes quiet, you can never be sure whether it crashed or is just slow, so you can always get stuck waiting or decide too early.
Real systems sidestep FLP by assuming the network is usually timely (partial synchrony). Algorithms like Raft and Paxos never break safety, even during chaos, and use timeouts to make progress once the network calms down. They give up guaranteed liveness, not correctness.
The workhorse idea behind all of them is the majority quorum. With N = 2f + 1 nodes, any two majorities (f + 1 nodes each) overlap in at least one node, so two conflicting decisions can't both win. That's why clusters have odd sizes: 3 nodes tolerate 1 failure, 5 tolerate 2, and 4 still tolerates only 1.
Explain like I'm 10
Picture five friends picking a restaurant by text message, where some phones die and texts arrive late. They agree that a choice only counts once at least three of them confirm it. Since any two groups of three share at least one person, two different restaurants can never both get three confirmations.
Examples
Majority quorum math
// A cluster of n voting members needs a strict majority to decide anything.
function quorumSize(clusterSize: number): number {
return Math.floor(clusterSize / 2) + 1;
}
function toleratedFailures(clusterSize: number): number {
return clusterSize - quorumSize(clusterSize);
}
quorumSize(3); // 2
toleratedFailures(3); // 1
quorumSize(4); // 3
toleratedFailures(4); // 1 (no better than 3 nodes, and more to coordinate)
quorumSize(5); // 3
toleratedFailures(5); // 2Adding a fourth node raises the quorum without raising fault tolerance, which is why consensus clusters run 3 or 5 voters.
Raft's two core RPCs (simplified)
// Candidate asks for votes. A node grants at most one vote per term,
// and only if the candidate's log is at least as up to date as its own.
interface RequestVote {
term: number;
candidateId: string;
lastLogIndex: number;
lastLogTerm: number;
}
// Leader replicates entries (an empty entries array is a heartbeat).
interface AppendEntries {
term: number;
leaderId: string;
prevLogIndex: number; // follower must already have this entry...
prevLogTerm: number; // ...with this term, or it rejects the call
entries: { term: number; command: string }[];
leaderCommit: number; // highest index the leader knows is committed
}
function onRequestVote(node: NodeState, request: RequestVote): boolean {
if (request.term < node.currentTerm) return false;
if (request.term > node.currentTerm) node.stepDownTo(request.term);
const alreadyVotedForSomeoneElse =
node.votedFor !== null && node.votedFor !== request.candidateId;
const candidateLogIsUpToDate =
request.lastLogTerm > node.lastLogTerm ||
(request.lastLogTerm === node.lastLogTerm &&
request.lastLogIndex >= node.lastLogIndex);
if (alreadyVotedForSomeoneElse || !candidateLogIsUpToDate) return false;
node.votedFor = request.candidateId; // persisted to disk before replying
return true;
}The 'up to date' check is what guarantees a newly elected leader already holds every committed entry.
How it works
Raft (Ongaro and Ousterhout, 2014) was designed to be easier to understand than Paxos. It splits consensus into three parts.
1. Terms and roles. Time is divided into numbered terms. Each node is a follower, candidate or leader. A term has at most one leader. Any message carrying a higher term makes the receiver update its term and step down to follower, so stale leaders get demoted automatically.
2. Leader election. Followers expect regular heartbeats from the leader. If a follower hears nothing for its election timeout (randomized, e.g. 150 to 300 ms in the paper), it increments its term, becomes a candidate, votes for itself and sends RequestVote to everyone. It wins with votes from a majority. Randomized timeouts make it unlikely that two candidates split the vote over and over.
3. Log replication. Clients send commands to the leader. The leader appends each command to its log and sends AppendEntries to followers. Each AppendEntries includes the index and term of the previous entry; a follower rejects it if its log doesn't match there, and the leader backs up until the logs agree, then overwrites the follower's conflicting suffix. Once an entry from the leader's current term is stored on a majority, the leader advances its commit index. Committed entries (and everything before them) are applied to the state machine on every node, in the same order. This is state machine replication.
Paxos (Lamport) reaches the same guarantee with different framing. Single-decree Paxos has proposers, acceptors and learners in two phases:
- Prepare/Promise: a proposer picks a proposal number n and asks acceptors to promise to ignore anything numbered below n. They reply with any value they've already accepted. - Accept/Accepted: if a majority promised, the proposer sends accept(n, v), where v must be the highest-numbered value already accepted by those acceptors, or its own if there is none.
Running Paxos once per log slot, with a stable leader skipping phase 1, is Multi-Paxos, which is roughly what Raft is in practice.
Split brain is two nodes both believing they're leader and both accepting writes. Quorums prevent two leaders in the same term, but an old leader cut off by a partition may not know it has been replaced. It can't commit anything (it can't reach a majority), yet it may still serve stale reads or act on external systems. Fixes: reads go through the quorum (Raft's ReadIndex) or rely on leader leases with bounded clock drift, and side effects carry fencing tokens such as the term.
In practice, few teams implement consensus themselves. They use a coordination service built on it:
- etcd (Raft): Kubernetes stores all cluster state there. - ZooKeeper (ZAB, a Paxos-like atomic broadcast): used by HBase, older Kafka and many Hadoop-era systems. - Consul (Raft), and Raft inside databases such as CockroachDB and TiKV, and in Kafka's KRaft mode.
Raft roles and transitions
timeout, start election
┌──────────┐ ─────────────────────────► ┌───────────┐
│ Follower │ │ Candidate │──┐ timeout:
└──────────┘ ◄───────────────────────── └───────────┘◄─┘ new election
▲ sees current leader or │
│ higher term │ wins majority of votes
│ ▼
│ sees higher term ┌──────────┐
└──────────────────────────────── │ Leader │
└──────────┘
Log replication (5 nodes, majority = 3)
Leader [1:x][1:y][2:z] ← entry 3 stored on 3 of 5 → committed
F1 [1:x][1:y][2:z]
F2 [1:x][1:y][2:z]
F3 [1:x][1:y] (lagging, will catch up)
F4 [1:x] (lagging, will catch up)Why does it exist?
Replication alone doesn't tell replicas what order to apply writes in or who's in charge after a crash. Without consensus you get two leaders, diverging replicas and lost acknowledged writes. Consensus gives you a single, fault-tolerant source of truth for the small but critical facts everything else depends on: leadership, membership, configuration, locks and the order of a replicated log.
When to use it
- Electing a single leader or primary among replicas. - Storing cluster metadata and configuration that must never diverge (service registry, shard maps, feature flags that gate correctness). - Building a strongly consistent (linearizable) replicated store or log. - Coordination primitives: distributed locks, leases, barriers.
Almost always via etcd, ZooKeeper, Consul or a database that embeds Raft or Paxos, not a hand-written implementation.
When not to use it
- High-volume data paths where every write needn't go through a single ordered log. Consensus costs at least one majority round trip per write, and the leader is a throughput ceiling. - Data that tolerates eventual consistency (counters, likes, caches): leaderless replication or CRDTs scale further and stay available during partitions. - Across distant regions for every request, unless you accept the cross-region round trip on every commit. - Don't put large blobs or hot application data in etcd/ZooKeeper; they are built for small, critical metadata.
Common mistakes
Running an even number of voters (2 or 4). It raises the quorum size without adding fault tolerance, and a 2-node cluster can't survive any failure.
Reading from a Raft follower or a possibly deposed leader and assuming the result is linearizable. Use quorum reads (ReadIndex) or a leader lease if you need the latest value.
Treating 'I am leader' as a permanent fact. A paused or partitioned leader can be replaced at any moment, so external side effects need fencing tokens.
Committing an entry from an earlier term just because it's on a majority. Raft only commits by counting replicas for entries from the leader's current term; older entries commit indirectly.
Writing your own consensus algorithm instead of using a proven library or service. The edge cases (log divergence, membership changes, disk fsync) are where real bugs live.
Practice exercises
- Easy:
A 5-node etcd cluster loses 2 nodes. Can it still accept writes? What about after losing a third? Explain using quorum sizes.
- Medium:
Walk through a Raft election where two followers time out at almost the same moment. Explain how split votes happen and why randomized election timeouts make them rare.
- Hard:
A leader in a 5-node Raft cluster is partitioned with one follower while the other three elect a new leader. Describe what each side can and can't do, what happens to writes the old leader accepted, and how the logs reconcile when the partition heals.
Interview questions
What is the consensus problem?
Getting a group of nodes to agree on a single value (or a sequence of values) so that all deciding nodes choose the same value, the value was actually proposed, and non-faulty nodes eventually decide, despite crashes and message delays.
Why do consensus clusters usually have an odd number of nodes?
A decision needs a strict majority. N = 2f + 1 nodes tolerate f failures; adding one more node to make it even raises the quorum by one but tolerates no extra failure, so it only adds cost and latency.
What does the FLP result say, and why do Raft and Paxos still work?
FLP proves no deterministic algorithm can guarantee consensus in a fully asynchronous system if even one process can crash. Raft and Paxos always keep safety and rely on timeouts for liveness, so they make progress whenever the network is timely enough, but can stall during sustained instability.
What is a term in Raft?
A monotonically increasing logical epoch. Each term has at most one leader. Nodes reject messages with older terms and step down when they see a newer one, which demotes stale leaders.
When is a Raft log entry committed?
When the leader has replicated an entry from its current term to a majority of nodes. That entry and all earlier ones are then committed and can be applied to the state machine.
How does Raft ensure a new leader doesn't lose committed entries?
Voters only grant a vote to a candidate whose log is at least as up to date (higher last term, or same last term and at least as long). Since a committed entry is on a majority and a winner needs a majority of votes, at least one voter holds the entry and blocks any candidate missing it.
What is split brain, and how do you prevent it?
Two nodes acting as leader at once, typically after a partition. Majority quorums prevent two leaders from committing in the same term. To stop a stale leader's side effects you route reads through the quorum or use leases with bounded clock drift, and attach fencing tokens (like the term) to writes in external systems.
How do Paxos and Raft relate?
Both are majority-quorum consensus protocols with the same fault tolerance. Basic Paxos decides one value via prepare/promise and accept/accepted phases; Multi-Paxos with a stable leader decides a log. Raft is essentially a leader-based Multi-Paxos with a stricter structure (strong leader, log-matching rules, explicit elections) designed for understandability.
How would you serve linearizable reads from a Raft cluster without writing to the log?
ReadIndex: the leader records its commit index, confirms it's still leader with a heartbeat round to a majority, waits until that index is applied, then serves the read. Alternatively, a leader lease skips the round trip but depends on bounded clock drift, trading safety assumptions for latency.
Why is changing cluster membership tricky, and how does Raft handle it?
If nodes switch from the old to the new configuration at different times, the old and new majorities might not overlap, allowing two leaders. Raft uses joint consensus (decisions need majorities of both configurations) or adds/removes one server at a time, which guarantees overlap.