Consensus
How a group of machines agrees on a single answer — even when some of them crash or fall out of touch.
Consensus in 30 seconds
- What: get several machines to agree on one value/order of events, despite crashes and network trouble.
- Why: so a cluster can pick a leader, agree on config, and keep replicas in the same order.
- How: a majority (quorum) must agree before anything counts; algorithms like Raft and Paxos make this safe.
- Raft intuition: elect one leader, the leader orders all writes, followers copy them, commit once a majority has it.
- Cost: needs a majority alive (an odd number of nodes helps), and the coordination adds latency.
- You rarely build it — you use systems that implement it (etcd, ZooKeeper, Consul).
Three friends and a flaky group chat
Picture three friends deciding on a restaurant, but they can only text in a group chat where messages sometimes arrive late, out of order, or not at all — and occasionally someone's phone dies mid-conversation. They must all show up at the same place. If each just picks their favorite and leaves, they scatter to three different restaurants. What they need is a rule for reaching one shared decision that still works when a message is lost or a phone goes dark. The obvious fix — 'let's all do whatever Dana says' — works beautifully until Dana's phone dies, and now nobody knows whether Dana already decided.
That messy little problem is consensus, and it turns out to be the hardest, most fundamental problem in distributed systems. Everything below is about how real clusters solve it without a single friend they can always trust.
The problem, told simply
You have several machines that each hold a copy of some state. They need to agree on one value — or, more commonly, one order of events — so that every copy ends up identical. The catch is that machines crash at random moments and the network between them silently drops, delays, or reorders messages. Consensus is any protocol that still lets the group settle on a single, agreed answer under those conditions.
Where you actually need it
- Leader election — the cluster must agree on exactly one leader (two leaders = split-brain = corruption).
- Replicated logs — every replica must apply the same writes in the same order.
- Shared configuration — all nodes must read the same settings, locks, and membership list.
- Distributed locks done right — the lock service itself relies on consensus underneath.
The gap a simple 'just vote' can't fill
The naive idea is: everyone broadcasts their choice, and the majority wins. It almost works — but two things wreck it. First, votes can be lost or delayed, so different nodes tally different results and disagree about who won. Second, a node can vote, crash, and come back with no memory of having voted — then vote again for someone else. Consensus algorithms exist precisely to close these holes: they pin decisions to numbered rounds (terms), make each node durably remember its vote, and require a strict majority so two conflicting winners are mathematically impossible. 'Just vote' is the intuition; the algorithm is what makes it survive crashes and lost messages.
How Raft gets everyone to agree
Raft is the algorithm most people learn because it was designed to be understandable. The story goes like this:
- Elect a leader. Nodes vote; whoever gets a majority becomes leader for a term. One leader, no arguments.
- Leader takes all writes. Clients talk to the leader, which appends each change to its log.
- Replicate. The leader streams the log to followers.
- Commit on majority. Once more than half the nodes have a change, it's committed — safe even if a minority later fails.
- Heal automatically. If the leader dies, its missed heartbeats trigger a new election, and the cluster carries on.
on election_timeout(): # no heartbeat from a leader in time
current_term = current_term + 1
votes = 1 # a candidate always votes for itself
for peer in cluster:
reply = peer.request_vote(term=current_term, candidate=self.id)
if reply.granted:
votes = votes + 1
# A majority is what prevents TWO leaders in the same term.
if votes > len(cluster) / 2:
become_leader()
else:
become_follower() # someone else won, or split vote -> retryWhy terms stop a zombie leader
Each election bumps a term number — think of it as 'election #7, election #8.' Every message carries its term, and nodes obey one simple rule: ignore anything from an older term. So if an old leader was partitioned off, a new one got elected in a higher term, and then the old leader reconnects still believing it's in charge — its messages carry the stale term number and everyone politely ignores them. The old leader is forced to step down. Terms are how Raft makes 'the past can't override the present' into a hard guarantee.
on receive(msg):
if msg.term < current_term:
return reject(current_term) # 'you're behind — I've moved on'
if msg.term > current_term:
current_term = msg.term # someone newer exists
become_follower() # step down if I thought I was leader
# ... only now process the message as current ...
# A reconnecting old leader (lower term) gets rejected, learns the new
# term from the reply, and quietly demotes itself. No split-brain.Replicating the log safely
Once there's a leader, writes flow through it as an ordered log, and nothing counts as 'real' until a majority has durably stored it. That majority rule is doing quiet, crucial work: because any two majorities of the same cluster must share at least one node, a committed entry can never be lost to a future election — whoever wins next is guaranteed to already have it.
on client_write(entry): # only the leader runs this
log.append(entry) # tentative -- not yet committed
acks = 1 # the leader counts as one copy
for follower in followers:
if follower.append_entries(term, entry).ok:
acks = acks + 1
# The entry is safe once MORE THAN HALF the nodes hold it,
# because any future majority must overlap this one.
if acks > len(cluster) / 2:
commit(entry) # now apply to the state machine + ack client
# Otherwise: retry replication until a majority is reached.The failure it exists to prevent: split-brain
Everything above is in service of one nightmare: split-brain, where a partition leaves two nodes each convinced they're the leader, both accepting writes. The two halves diverge — each has 'the truth' — and when the network heals you're left with two contradictory histories and no clean way to merge them. The majority rule makes this impossible: a leader can only commit with a majority behind it, and a split can give a majority to at most one side. The minority side simply can't make progress, which feels like downtime but is actually the system protecting you from corruption.
The trade-off to say out loud
Consensus buys you correctness, but it isn't free. Every committed decision needs a round trip to a majority, which adds latency. And the system only makes progress while a majority is alive — lose too many nodes and it stops accepting writes on purpose, choosing consistency over availability. That's the CAP trade-off (see CAP & PACELC) showing up at the lowest level of your cluster.
| Cluster size | Majority needed | Failures tolerated | Note |
|---|---|---|---|
| 3 nodes | 2 | 1 | The common minimum for real redundancy |
| 5 nodes | 3 | 2 | Survives two failures; more coordination cost |
| 4 nodes (even) | 3 | 1 | No better than 3 — avoid even counts |
| 1 node | 1 | 0 | Not consensus at all — a single point of failure |
Choosing: you adopt it, you don't build it
| You need to... | Reach for | Why |
|---|---|---|
| Store config, do leader election, service discovery | etcd or Consul | Purpose-built consensus stores with simple APIs |
| Coordinate locks, membership, watches | ZooKeeper | Battle-tested coordination primitives |
| Build a strongly-consistent database | A store that embeds Raft/Paxos | e.g. CockroachDB, Spanner — don't hand-roll it |
| Agree on one fact across a few nodes | A library implementing Raft | Reuse a proven implementation, never write your own |
Consensus feels academic until you notice it's the bedrock under half the infrastructure you already trust — it's the mechanism by which a group of machines gets to have one shared truth instead of several conflicting opinions.
Why it matters
- It's the difference between a cluster that elects one leader and a cluster that tears itself apart with two.
- It guarantees every replica applies the same changes in the same order, which is what makes a distributed store believable.
- It's the hidden engine inside the coordination tools (etcd, ZooKeeper, Consul) that so many other systems quietly depend on.
If ignored
- Split-brain: two nodes each think they're the leader and both accept writes, corrupting state in ways that are brutal to untangle.
- Replicas drift out of order and start disagreeing about what the 'current' value even is.
- A configuration or membership change half-applies, leaving the cluster in a state no single node can describe.
Where it fits
- Sits in the control plane — leader election, membership, and config — rather than on the hot path of every request.
- Lives inside coordination services you adopt, not code you usually write by hand.
- Shows up the moment a system needs several nodes to agree on one fact and survive failures doing it.
Related topics
- Replication: consensus is how replicas agree on the order of writes
- Distributed locking: a correct lock service leans on consensus underneath
- CAP & PACELC: losing quorum is consensus choosing consistency over availability
- Availability & reliability: the odd-node, majority rule is what lets it tolerate failures
Interview lens
Questions it unlocks
- How does a cluster agree on a single leader?
- Why do consensus systems prefer an odd number of nodes?
- What happens to writes during a network partition?
60-second answer
Consensus is how a set of nodes agrees on one value or order of events despite crashes and lost messages. The core mechanism is a majority quorum: a change commits only once more than half the nodes have it, which makes two conflicting decisions impossible even during a split. Raft makes this understandable — elect one leader, route all writes through it, replicate to followers, commit on majority, and re-elect automatically if the leader dies, using term numbers so a reconnecting old leader steps down. I'd note the trade-off: it adds latency and stops accepting writes if it loses quorum, choosing consistency over availability, and I'd use etcd or ZooKeeper rather than build it myself.
Common traps
- Allowing two leaders (split-brain) by not requiring a majority.
- Running an even number of nodes and risking tie votes.
- Forgetting consensus sacrifices availability when it loses quorum.