Consensus & Raft

Getting nodes to agree despite failures — the consensus problem, quorums, replicated state machines, and Raft in detail (leader election, log replication, safety, membership changes), plus Paxos and where consensus is used.

Advanced 6 min readLesson 5 of 9 Interview Q&A

Consensus is the problem of getting several nodes to agree on a value (or a sequence of values) even when some of them crash and the network misbehaves. It's the foundation for anything that must be both fault-tolerant and strongly consistent: leader election, distributed locks, configuration stores, and replicated databases.

The problem

A correct consensus algorithm guarantees:

  • Agreement: no two nodes decide different values.
  • Validity: the decided value was proposed by some node.
  • Termination: every non-failed node eventually decides (when the network is well-behaved — FLP shows it can't be guaranteed in a fully asynchronous system).

With 2f + 1 nodes, consensus tolerates f crashed nodes, because any two majorities (quorums of f + 1) overlap in at least one node — that node carries knowledge from one decision to the next.

Cluster sizeMajorityFailures tolerated
321
532
743

Even sizes add cost without extra tolerance (4 nodes tolerate only 1 failure, like 3).

Replicated state machines

The practical pattern: agree on an ordered log of commands. Every node applies the same commands in the same order to a deterministic state machine (a key-value store, a database), so all nodes end in the same state.

commandAppendEntriesAppendEntriesClientLeaderlog: set x=1, set y=2Followersame logFollowersame log

Raft

Raft (Ongaro & Ousterhout, 2014) was designed to be understandable, splitting consensus into three sub-problems: leader election, log replication and safety. It's used in etcd (Kubernetes' brain), Consul, CockroachDB, TiKV, MongoDB's replication protocol, Kafka's KRaft and many more.

Roles and terms

Each node is a follower, candidate or leader. Time is divided into terms, numbered consecutively; each term has at most one leader. Terms act as a logical clock: any message with a higher term makes the receiver update its term and step down to follower.

election timeoutwins majoritysees higher termsees higher termFollowerCandidateLeader

1. Leader election

  1. The leader sends periodic heartbeats (empty AppendEntries). Followers that hear nothing for a randomised election timeout (e.g. 150–300 ms) become candidates.
  2. A candidate increments its term, votes for itself, and sends RequestVote to all nodes.
  3. Each node grants at most one vote per term, first come first served — and only if the candidate's log is at least as up to date as its own (higher last term, or same last term and at least as long).
  4. A candidate with votes from a majority becomes leader and starts heartbeating. If the vote splits, timeouts expire and a new election starts; randomised timeouts make repeated splits unlikely.

2. Log replication

ClientLeaderFollower 1Follower 2set x = 5append to own log (index 7, term 3)AppendEntries(prevIndex 6, prevTerm 3, entry 7)AppendEntries(…)successmajority (2 of 3) → entry 7 COMMITTED, applyoknext heartbeat carries commitIndex = 7
  • An entry is committed once stored on a majority; then it's applied to the state machine and the client gets a reply. Committed entries are never lost.
  • The consistency check: each AppendEntries includes the index and term of the preceding entry. A follower rejects it if its log doesn't match there; the leader then backs up and resends earlier entries, overwriting the follower's conflicting uncommitted entries. This Log Matching Property keeps logs identical up to any matching point.

3. Safety

  • Election restriction: a candidate can only win if its log contains all committed entries (voters refuse candidates with less up-to-date logs). So every new leader already has every committed entry — leaders never overwrite their own log.
  • A leader only counts replicas to commit entries from its current term; older entries become committed indirectly. (This subtle rule prevents a committed entry from being overwritten in certain failure sequences.)

Practical concerns

  • Linearizable reads: a leader must confirm it's still leader before serving a read (a heartbeat round, or a time-bounded lease), or it might serve stale data after being deposed in a partition.
  • Log compaction: logs grow forever, so nodes periodically take snapshots of the state machine and discard the log prefix; slow followers receive snapshots.
  • Membership changes: adding or removing nodes safely uses joint consensus or single-server changes so two majorities can never form.
  • Performance: each write needs a round trip to a majority, often across zones; batching and pipelining help. Leaders are a throughput bottleneck, which is why large systems run many Raft groups (one per shard — "multi-Raft").

Paxos

Paxos (Lamport, 1989/1998) was the first practical consensus algorithm and is provably correct, but notoriously hard to understand and to extend into a complete system. Basic Paxos agrees on a single value in two phases:

  1. Prepare/Promise: a proposer picks a proposal number n and asks acceptors to promise to ignore lower numbers; acceptors reply with any value they've already accepted.
  2. Accept/Accepted: the proposer sends a value (the highest-numbered previously accepted value, if any; otherwise its own) with number n; once a majority accept, the value is chosen.

Multi-Paxos runs this repeatedly for a log, with a stable leader skipping phase 1 — which ends up much like Raft. Used in Chubby, Spanner, and (variants) in many Google and AWS systems. Zab (ZooKeeper) and Viewstamped Replication are close relatives.

Where consensus is used

UseExamples
Coordination services (config, service discovery, locks, leader election)etcd, ZooKeeper, Consul
Replicated databasesCockroachDB, TiDB, YugabyteDB, Spanner
Message logsKafka (KRaft), Redpanda
Cluster managersKubernetes (via etcd), Nomad

Don't implement consensus yourself for production use — use a proven library or service. See Leader election & coordination.

Key takeaways
  • Consensus gets nodes to agree on values despite crashes; 2f + 1 nodes tolerate f failures via overlapping majorities.
  • Replicated state machines agree on an ordered command log and apply it deterministically.
  • Raft: terms, randomised election timeouts, majority votes with an up-to-date-log restriction.
  • Entries commit once on a majority; the consistency check repairs follower logs.
  • Practical needs: leader leases or read checks, snapshots, safe membership changes, multi-Raft for scale.
  • Paxos is the older, equivalent foundation; use etcd/ZooKeeper rather than rolling your own.
Interview questions
QHow does Raft elect a leader and why can't there be two leaders in the same term?hard

Followers that miss heartbeats for a randomised timeout become candidates, increment the term, vote for themselves and request votes. Each node votes for at most one candidate per term, and only for candidates whose log is at least as up to date as its own. Winning requires a majority, and two majorities in the same cluster always overlap, so the shared node could only have voted for one candidate — hence at most one leader per term. A stale leader from an older term steps down when it sees a higher term.

QWhy do consensus clusters have an odd number of nodes?easy

Tolerance depends on keeping a majority alive. A cluster of 2f+1 tolerates f failures; adding one more node (2f+2) raises the majority size without tolerating more failures, while adding latency and failure points. So 3, 5 or 7 nodes are typical.