Skip to main content

Consensus & Raft

Learning objectives
  • Explain what problem consensus solves and why it underpins leader election, locks and linearizable storage
  • Walk through Raft's leader election, terms, log replication, commit index and safety rules, including the minority-leader case
  • Compare Raft and Paxos at the level an interviewer expects
  • Size and place a consensus cluster (3 vs 5 nodes, AZ layout) and estimate its latency cost

TL;DR​

  • Consensus lets a group of nodes agree on a single sequence of decisions even when some nodes crash or messages are delayed. It is the core of any system that must have exactly one leader, lock holder, or committed history.
  • Raft splits the problem into leader election, log replication and safety. One leader per term; an entry is committed when the leader has stored it on a majority; committed entries are never lost.
  • Elections use randomized timeouts, and a node only votes for a candidate whose log is at least as up to date as its own — that rule is what guarantees a new leader already has every committed entry.
  • A cluster of 2f + 1 nodes tolerates f failures. 3 nodes tolerate 1, 5 tolerate 2; even sizes add cost without adding tolerance.
  • Every write costs at least one round trip from leader to a majority plus a durable disk write. Consensus is ideal for metadata and coordination, and acceptable for the data path when you partition the data into many independent groups (CockroachDB, TiKV, Spanner).
  • Paxos solves the same problem; Multi-Paxos with a stable leader looks a lot like Raft. Raft's selling point is understandability.

Why it matters​

Banks and e-commerce platforms have many "there must be exactly one" requirements:

  • Exactly one node runs the end-of-day settlement batch or the interest accrual job.
  • Exactly one primary accepts writes for a ledger shard at a time.
  • A virtual account number, voucher code, or seat is allocated to exactly one customer.
  • Kubernetes must agree on what is deployed; Kafka must agree on which broker leads each partition.

Every one of these reduces to consensus. If you implement them with "a flag in Redis" or "the node with the lowest IP wins", you will eventually get two leaders during a partition or a GC pause — two settlement runs, two primaries, two customers holding the same reference. Consensus algorithms are the tested way to get this right, and knowing how they behave under failure (especially the minority leader case) is a standard System Architect interview topic.

Core concepts​

What consensus guarantees​

Formally, nodes propose values and must decide such that:

  • Agreement: no two correct nodes decide differently.
  • Validity: the decided value was proposed by someone.
  • Termination: every non-crashed node eventually decides.

Running consensus repeatedly over a log gives a replicated state machine: every node applies the same commands in the same order and ends up in the same state.

The FLP result (Fischer, Lynch, Paterson, 1985) proves that in a fully asynchronous system, no deterministic algorithm can guarantee termination if even one node may crash. Practical algorithms therefore guarantee safety always and liveness only when the network behaves "well enough" — timeouts eventually work. That is why a Raft cluster under heavy packet loss may stop making progress, but never commits conflicting values.

Raft roles and terms​

Each node is a follower, candidate or leader. Time is divided into terms, numbered with a monotonically increasing integer. Each term has at most one leader. Any message carrying a higher term makes the receiver update its term and step down to follower.

Leader election​

  1. A follower that hears no heartbeat (empty AppendEntries) within its election timeout increments its term, becomes a candidate, votes for itself and sends RequestVote to all peers.
  2. 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: compare the term of the last log entry first, then the log length.
  3. A candidate with votes from a majority becomes leader and immediately sends heartbeats.
  4. If the vote splits, candidates time out and retry in a new term. Timeouts are randomized (the paper suggests 150–300 ms) so one candidate usually starts first and wins.

Production systems use longer values: etcd defaults to a 100 ms heartbeat and a 1000 ms election timeout. Timeouts must be well above network RTT plus disk latency, or you get spurious elections.

Log replication​

  • The leader appends the command to its log and sends AppendEntries containing the new entries plus prevLogIndex and prevLogTerm — the index and term of the entry just before them.
  • A follower accepts only if its log has an entry at prevLogIndex with term prevLogTerm. If not, it rejects, and the leader backs up (decrements that follower's nextIndex) until they find the point where logs match, then overwrites the follower's conflicting suffix.
  • This consistency check gives the Log Matching property: if two logs have an entry with the same index and term, the logs are identical up to that point.

Commit index and the current-term rule​

An entry is committed once the leader has replicated it to a majority. The leader tracks the highest committed index (commitIndex) and tells followers in subsequent messages; each node applies committed entries to its state machine in order.

There is one subtle rule: a leader only counts replicas to commit entries from its own current term. Entries from earlier terms become committed indirectly, when a later current-term entry after them is committed. Without this rule, an entry replicated to a majority by an old leader could still be overwritten by a different new leader (the scenario in Figure 8 of the Raft paper). This is also why new leaders commit a no-op entry at the start of their term: it promptly commits everything before it.

Safety properties​

Raft guarantees, at all times:

  • Election safety: at most one leader per term.
  • Leader append-only: a leader never overwrites or deletes its own entries.
  • Log matching: same index and term implies identical prefixes.
  • Leader completeness: a committed entry is present in the logs of all future leaders (guaranteed by the voting rule plus the majority overlap).
  • State machine safety: no two nodes apply different commands at the same index.

The key insight is quorum intersection: the majority that committed an entry and the majority that elects any future leader must share at least one node, and that node will refuse to vote for a candidate missing the entry.

The minority-leader case​

The most common interview probe: the leader is partitioned into a minority.

  • The old leader keeps believing it is leader for a while, accepts client writes, appends them, but cannot commit them — it cannot reach a majority. Clients time out.
  • The majority side elects a new leader in a higher term and keeps committing.
  • When the partition heals, the old leader sees the higher term, steps down, and its uncommitted entries are overwritten.
  • Reads are the trap. If the old leader serves reads from its local state, they are stale. Linearizable reads therefore need either ReadIndex (the leader confirms with a heartbeat round to a majority that it is still leader before answering) or leader leases (the leader answers locally only within a lease period that followers promise not to elect someone else in — which relies on bounded clock drift).

Other parts of a real Raft implementation​

  • Log compaction: state machines take snapshots; the log before the snapshot is discarded; slow followers receive InstallSnapshot.
  • Membership changes: adding or removing nodes safely uses joint consensus or one-server-at-a-time changes, so old and new configurations can never form disjoint majorities.
  • Pre-vote and CheckQuorum (from Ongaro's thesis, implemented in etcd's raft library): a rejoining node first checks whether it could win before bumping the term, and a leader steps down if it cannot hear from a majority. These prevent a flaky node from repeatedly disrupting a healthy cluster.

Paxos at a glance​

Lamport's Paxos (published 1998, re-explained in "Paxos Made Simple", 2001) has proposers, acceptors and learners, and decides a single value in two phases:

  1. Prepare / promise: a proposer picks a unique proposal number n and asks a majority of acceptors to promise to ignore proposals numbered below n. Acceptors reply with any value they have already accepted.
  2. Accept / accepted: the proposer sends accept(n, v) where v is the highest-numbered value already accepted (if any), otherwise its own. If a majority accepts, v is chosen.

Multi-Paxos runs this for each log slot, and with a stable leader it skips phase 1 for subsequent slots — at which point it resembles Raft. Differences that matter in practice:

AspectRaftMulti-Paxos
LeaderRequired; strong leader handles all writesOptional optimization; any proposer can drive a slot
LogContiguous; no holesSlots can be decided out of order
Who can become leaderOnly a node with an up-to-date logAny node; it catches up during phase 1
SpecificationFull algorithm incl. membership and compactionCore is small; practical systems add a lot of unspecified engineering
Used byetcd, Consul, CockroachDB, TiKV, KRaftChubby, Spanner, many Google systems; DynamoDB uses Multi-Paxos per partition

Variants worth naming: ZAB (ZooKeeper's atomic broadcast, similar in spirit), EPaxos (leaderless, commutative commands), Flexible Paxos (phase-1 and phase-2 quorums only need to intersect each other, not be majorities).

Quorum math​

Cluster sizeMajorityFailures tolerated
110
220
321
431
532
743
  • Even sizes buy nothing: 4 nodes tolerate the same single failure as 3, but need one more ack per write.
  • Bigger clusters are slower: more replicas to replicate to, and the commit waits on the median node's latency.
  • Placement: 3 nodes across 3 AZs survives one AZ loss. 5 nodes as 2-2-1 across 3 AZs survives one AZ loss plus one more node. With only 2 AZs, one AZ always holds a majority, and losing it stops the cluster.

Trade-offs​

OptionStrengthsWeaknessesChoose when
3-node Raft groupLowest write latency; survives one failureA second failure (or one failure during maintenance) stops writesMost coordination services, per-range groups in distributed SQL
5-node Raft groupSurvives two failures; safe rolling upgradesMore replication traffic; slightly higher latencyCritical control planes (Kafka KRaft, core etcd for large Kubernetes)
Cross-region groupSurvives region loss with no data lossEvery write pays inter-region RTTLedgers that require RPO = 0 across regions and can tolerate the latency
Consensus for metadata onlyHot data path stays fast; consensus decides who leadsData path needs its own replication and fencingMost architectures: etcd or ZooKeeper electing primaries
Leader-lease readsLocal reads, low latencyCorrectness depends on bounded clock driftRead-heavy, latency-sensitive linearizable reads
ReadIndex readsNo clock assumptionsOne heartbeat round per read (batched)Default for correctness-first reads

In practice​

Where you will meet consensus:

  • etcd — Raft; stores all Kubernetes state; provides leases, transactions, watches, and the election/lock recipes in its concurrency package. Keep the data small: the default backend quota is ≈ 2 GB.
  • Consul — Raft among server nodes for the catalog and KV store; sessions provide locks and leader election.
  • ZooKeeper — ZAB; ephemeral and sequential znodes for locks and election.
  • Kafka KRaft — a Raft-based controller quorum that stores cluster metadata (topics, partition leaders, ACLs), replacing ZooKeeper; Kafka 4.0 removed ZooKeeper mode entirely.
  • CockroachDB / TiKV / YugabyteDB — data is split into ranges or tablets, each with its own Raft group ("multi-Raft"), so throughput scales with the number of groups, not one leader.
  • Spanner — Paxos groups per split, plus TrueTime for global ordering.
  • Message brokers — RabbitMQ quorum queues, NATS JetStream and Redpanda use Raft for replicated queues and logs.

Singleton job with etcd — run the settlement batch on exactly one instance, and stop the moment leadership is lost:

package settlement

import (
"context"
"fmt"

clientv3 "go.etcd.io/etcd/client/v3"
"go.etcd.io/etcd/client/v3/concurrency"
)

// RunAsLeader blocks until this instance is elected, then runs work with a
// context that is cancelled if the etcd lease (and so leadership) is lost.
func RunAsLeader(ctx context.Context, cli *clientv3.Client, id string,
work func(ctx context.Context, fencingToken int64) error) error {

sess, err := concurrency.NewSession(cli, concurrency.WithTTL(10))
if err != nil {
return fmt.Errorf("new session: %w", err)
}
defer sess.Close()

election := concurrency.NewElection(sess, "/jobs/settlement/leader")
if err := election.Campaign(ctx, id); err != nil {
return fmt.Errorf("campaign: %w", err)
}
defer election.Resign(context.WithoutCancel(ctx))

ctx, cancel := context.WithCancel(ctx)
defer cancel()
go func() {
select {
case <-sess.Done(): // lease expired or revoked
cancel()
case <-ctx.Done():
}
}()

// The election key's revision increases with every new leader:
// pass it to downstream writes as a fencing token.
return work(ctx, election.Rev())
}

Cancellation alone is not enough — a paused process may still issue a write after losing leadership. Downstream storage should reject writes carrying an older fencing token (see Distributed Locks & Leases).

Cost of consensus (rough, illustrative):

  • Commit latency ≈ leader's network RTT to the fastest majority + one fsync. In one AZ, low single-digit milliseconds; across three AZs, a few milliseconds; across regions, the inter-region RTT (tens to 100+ ms).
  • Throughput is limited by the leader: batching and pipelining AppendEntries matter more than CPU.
  • Disk latency is on the critical path. etcd's operations guidance stresses fast SSDs and monitoring WAL fsync duration; slow disks show up as missed heartbeats and leader churn.
  • Operational cost: quorum loss is a full write outage; recovering from losing a majority usually means manual, risky surgery from a snapshot.

Common pitfalls​

  • Even-sized or two-AZ clusters. Symptom: an AZ outage takes the control plane down even though "half the nodes are fine".
  • Election timeouts too close to RTT or disk latency. Symptom: frequent leader changes, latency spikes, leader changed errors under load or during noisy-neighbor disk I/O.
  • Serving reads from a possibly deposed leader. Symptom: rare stale reads after a network blip — e.g., a lock appears free when it isn't. Use ReadIndex or properly bounded leases.
  • Treating etcd as a database. Large values and high write rates blow the backend quota and make snapshots slow. Store coordination metadata there; store data elsewhere.
  • Assuming cancellation stops side effects. A leader that loses its lease mid-write may still complete the write. Fence downstream.
  • Building your own consensus. Home-grown "leader election" with heartbeats in a database table almost always lacks the voting rule or fencing. Use etcd, ZooKeeper, Consul, or a well-tested library such as etcd's raft or HashiCorp raft.

Interview angle​

  • Typical questions: "How does Raft elect a leader?" "What happens if the leader is in the minority partition?" "Why 5 nodes and not 4?" "How do you guarantee only one instance of a cron job runs?" "Why is CockroachDB write latency higher than single-node PostgreSQL?"
  • Strong answer for the minority leader: it can't commit, clients time out; the majority elects a new leader with a higher term; the old leader steps down on rejoin and its uncommitted entries are overwritten; reads need ReadIndex or leases to avoid staleness.
  • Strong answer for sizing: 2f + 1; 3 nodes across 3 AZs for most; 5 when you need to survive maintenance plus a failure; never 2 AZs.
  • Show you know the cost: majority round trip + fsync per write; use consensus for metadata and per-shard leadership rather than for every request unless you chose distributed SQL deliberately.
  • Red flags: "use Redis with a TTL for leader election" for a money-moving job without fencing; "4 nodes for more fault tolerance"; not knowing what a term is.

Self-check​

1. What rule in Raft's voting guarantees that a new leader has every committed entry?

A node votes for a candidate 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). Committed entries exist on a majority, any electing majority overlaps it, and that overlapping node refuses to vote for a candidate missing the entry. So only candidates holding all committed entries can win.

2. When is an entry committed in Raft, and why must the leader only count replicas for current-term entries?

When the leader has stored it on a majority — but the leader only directly commits entries from its own term. An older-term entry on a majority can still be overwritten if a different node wins a later election with a log that has a newer last term. Committing a current-term entry after it makes the older entry safe; hence the no-op at the start of each term.

3. A leader is partitioned with one follower out of five. Describe what happens to writes and reads on both sides.

The old leader and its follower are a minority (2 of 5): writes are appended but never committed, so clients time out. The three-node majority elects a new leader in a higher term and continues committing. Reads served locally by the old leader would be stale; with ReadIndex it cannot confirm leadership and refuses. On healing, the old leader sees the higher term, steps down, and its uncommitted entries are replaced.

4. Why are randomized election timeouts needed?

If all followers time out simultaneously they all become candidates, vote for themselves and split the vote, possibly forever. Randomizing the timeout makes it likely one node starts first, collects a majority, and sends heartbeats before others time out.

5. Compare Raft and Multi-Paxos in three points.

Raft requires a strong leader that handles all writes, Paxos treats a leader as an optimization. Raft logs are contiguous and only up-to-date nodes can be elected; Paxos can decide slots out of order and any node can lead after catching up in phase 1. Raft specifies membership changes and compaction; Paxos implementations add much of that as unspecified engineering. With a stable leader, both cost one majority round trip per write.

6. Scenario: you must run a nightly interest-accrual job exactly once across six instances. Design it.

Use etcd (or ZooKeeper/Consul) leader election with a session lease; only the elected instance runs the job and it cancels work when the session ends. Pass the election revision as a fencing token on every write, and make the job idempotent per business date (e.g., a unique (account_id, accrual_date) constraint), so a duplicate run or a late write from a deposed leader is rejected.

7. Why does a 4-node cluster not improve fault tolerance over 3 nodes?

Majority of 4 is 3, so it tolerates one failure — the same as 3 nodes (majority 2). It adds a replica to every write and another node that can fail, and in a 2-2 split neither side has a majority.

🧠 Flashcards0/10 learned · 0 retries

Exercise​

Explore Raft behavior hands-on:

  1. Run a 3-node etcd cluster (Docker Compose). Write a Go client that does a Put every 50 ms and logs latency and errors.
  2. Kill the leader (docker stop). Measure the write gap until a new leader is elected and compare it to the configured election timeout.
  3. Partition the leader with docker network disconnect instead of killing it. Observe that writes to it fail, that etcdctl endpoint status shows a new leader on the other side, and what happens on reconnect.
  4. Implement the RunAsLeader singleton above, start three instances, and kill the leader to observe takeover. Log the fencing token each leader receives.
  5. Alternatively, work through the labs of MIT 6.5840 (formerly 6.824) to implement Raft yourself.

Done when: you can draw the timeline of step 3 with terms and commit indices, and explain why no committed write was lost.

Further reading​

  • Diego Ongaro & John Ousterhout, "In Search of an Understandable Consensus Algorithm" (USENIX ATC 2014) — the Raft paper.
  • Diego Ongaro, "Consensus: Bridging Theory and Practice" (PhD thesis, 2014) — membership changes, pre-vote, leases.
  • The Raft website — paper, visualization and implementations.
  • Leslie Lamport, "Paxos Made Simple" (2001).
  • Fischer, Lynch & Paterson, "Impossibility of Distributed Consensus with One Faulty Process" (1985).
  • Heidi Howard et al., "Flexible Paxos: Quorum Intersection Revisited" (2016).
  • Martin Kleppmann, Designing Data-Intensive Applications, ch. 9.
  • etcd documentation: "Tuning" and "Hardware recommendations".
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).