Consensus (Raft)

In one sentence

A cluster agrees on one ordered log of commands despite crashes: a leader replicates each entry and commits it once a majority stores it, so 2f+1 nodes survive f failures.

Analogy: A committee records a decision in the minutes only once more than half the members have signed it. Any two majorities share a member, so two contradictory decisions can never both pass.

A write costs one round trip to the fastest majority plus an fsync; the slow follower doesn't delay the commit.

How it works

  • Leader election: a follower missing heartbeats past a randomized timeout becomes a candidate; a majority vote makes it leader.
  • Any two majorities overlap, so every new leader already holds all committed entries.
  • A 4th node adds cost, not tolerance: 3 nodes tolerate 1 failure, 5 tolerate 2.
  • A minority partition can't commit: Raft picks consistency over availability.
  • You consume consensus through etcd, Consul, ZooKeeper or Kafka KRaft; you almost never write it.

Check yourself

Answer to mark it learned; your answers aren't scored.

Your etcd cluster has 3 members: 2 in zone A, 1 in zone B. Zone A goes down. What happens to writes, and what would have prevented the outage?

Go deeper

Full explanation

Consensus lets a group of machines agree on one sequence of values — a replicated log — so every replica applies the same commands in the same order despite crashes and partitions. Apply that log to a state machine to get a fault-tolerant database, lock service or config store.

Raft (2014) breaks it into three parts:

  1. Leader election. Time is split into numbered terms. A follower that hears no heartbeat within a randomized timeout (150–300 ms) becomes a candidate and asks for votes; a majority makes it leader. Each node votes once per term, and only for a candidate whose log is at least as up to date as its own.
  2. Log replication. Clients write to the leader, which appends the command and sends AppendEntries to followers. Once a majority has persisted it, the entry is committed, applied and acknowledged.
  3. Safety. Any two majorities overlap, so every new leader already holds all committed entries.

2f+1 nodes survive f failures: 3 tolerate 1, 5 tolerate 2; a 4th node adds cost, not tolerance. A minority partition cannot commit: Raft chooses consistency over availability (CAP & PACELC).

Paxos (Lamport) solves the same problem and underpins Chubby and Spanner. Raft runs etcd (Kubernetes' brain), Consul, CockroachDB and Kafka KRaft; ZooKeeper uses the similar ZAB. You consume consensus through these systems; you almost never write it.

Code Leader election on etcd with a fencing token
goLeader election on etcd with a fencing token
package main

import (
	"context"
	"log"
	"os"

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

func main() {
	cli, err := clientv3.New(clientv3.Config{Endpoints: []string{"etcd-0:2379", "etcd-1:2379", "etcd-2:2379"}})
	if err != nil {
		log.Fatal(err)
	}
	defer cli.Close()

	// Session = a lease kept alive by heartbeats: if this pod dies,
	// the lease expires after 10 s and leadership is released.
	sess, err := concurrency.NewSession(cli, concurrency.WithTTL(10))
	if err != nil {
		log.Fatal(err)
	}
	defer sess.Close()

	e := concurrency.NewElection(sess, "/index-builder/leader")
	host, _ := os.Hostname()
	if err := e.Campaign(context.Background(), host); err != nil { // blocks until we win
		log.Fatal(err)
	}
	// Fencing token: the revision only grows, so storage can reject a stale leader.
	runIndexBuilds(sess.Done(), e.Rev()) // stop as soon as the lease is lost
}
Real example

Your RAG platform rebuilds the vector index nightly from a 3-pod scheduler; two concurrent builders would race and could publish a half-built index. Each pod campaigns on an etcd key with a 10 s lease. Pod A wins and starts the build, then freezes in a 15 s GC pause; the lease expires and pod B takes over with fencing token 845. Pod A wakes, still believing it is leader, and tries to swap the index alias with token 812. The alias service rejects it because 812 < 845. The election itself is a Raft write across 3 etcd members: a few milliseconds in one region.

Trade-offs +3 · −3

+ You gain

  • Linearizable writes with automatic failover: no human picks the new primary.
  • Committed entries survive f failures out of 2f+1 nodes with no data loss.
  • Mature, heavily tested implementations: etcd, ZooKeeper, Consul and embeddable Raft libraries.

− You pay

  • Every write pays a majority round trip plus fsync; cross-region quorums cost tens to hundreds of ms.
  • One leader bottlenecks writes; adding members makes writes slower, not faster.
  • The minority side of a partition can't write, and failover leaves a gap of at least one election timeout.

Use it when

Small, critical state where disagreement is a bug: leader election, locks, membership, configuration, metadata, ID allocation. Consume it via etcd, ZooKeeper, Consul or a database built on it.

Avoid it when

High-volume data paths or anything that tolerates eventual consistency (caches, metrics, logs, counters). Don't store large blobs in etcd, and don't implement Raft yourself to avoid a dependency.

Numbers to know 5
  • 2f+1 nodes tolerate f failures: 3→1, 5→2, 7→3. Even sizes add cost, not tolerance.
  • Rule of thumb: a commit costs one round trip to a majority plus an fsync, ~1–5 ms in one region and 50–200 ms across continents.
  • etcd defaults: 100 ms heartbeat, 1,000 ms election timeout, 2 GB storage quota.
  • Raft paper: randomized election timeouts of 150–300 ms keep split votes rare.
  • Kafka 4.0 (2025) removed ZooKeeper; cluster metadata now lives in a KRaft (Raft) quorum.
Common pitfalls 4
  • Running 2 or 4 members: an even count adds failure points without raising tolerance.
  • Placing a 3-node quorum in 2 zones: losing the zone with 2 nodes loses quorum. Use 3 zones.
  • Trusting a lock or lease without fencing tokens: a paused ex-leader wakes up and still writes.
  • Reading from a follower and assuming it's current; use linearizable reads (etcd's default) when it matters.
Interview questions 3

Answer out loud first, then reveal.

Why do consensus clusters have 3 or 5 nodes, not 4 or 9?Show answer

Because commits need a majority, and majorities must overlap. With 2f+1 nodes I survive f failures: 3 tolerate 1, 5 tolerate 2. Four nodes still tolerate only 1, since the quorum becomes 3, so the extra node is pure cost. Going big hurts too: every write waits for more acknowledgments. I'd run 3 members across 3 zones for most control planes, and 5 when I must tolerate a failure while another member is down for maintenance.

Would you implement Raft to elect a leader for your job scheduler?Show answer

No. The algorithm fits in a paper, but the production bugs live in membership changes, snapshots, fsync semantics and clock assumptions; Jepsen keeps finding them in mature systems. I'd use an etcd lease, a Kubernetes Lease object or a ZooKeeper ephemeral node. Two things I'd still design: fencing tokens, because a paused ex-leader can wake up and write; and the failover gap, because lease TTL plus election takes seconds, so the workload must tolerate a short period with no leader.

What happens to a 5-node Raft cluster when the network splits 3–2?Show answer

The side with 3 keeps or elects a leader and keeps committing. If the old leader is on the side with 2, it may still accept writes, but it can never reach a majority, so nothing commits and clients time out. When the partition heals, it sees a higher term, steps down, and its uncommitted entries are overwritten by the majority's log. No committed write is lost; the cost is unavailability on the minority side.