Module 5 · Distributed systemsLesson 48 of 888 minAdvanced

Consensus algorithms

Consensus lets a group of machines agree on a value, or an order of events, even when some of them crash.

Try it

Watch writes get committed once 3 of 5 nodes have them. Crash one follower, then another: writes still work. Crash a third and see them stop.

Many things in a distributed system need everyone to agree: who is the leader, what order writes happened in, whether a lock is held. Consensus algorithms make that possible despite crashes and lost messages.

The core idea: majorities

A decision counts only when a majority of nodes has accepted it. Any two majorities share at least one node. So if one majority has accepted "x = 1", no other majority can accept a conflicting "x = 2" without that shared node noticing.

That gives a simple rule for size:

NodesMajorityFailures survived
321
532
743

Even numbers don't help: 4 nodes need 3 for a majority and still survive only 1 failure.

Raft, in brief

Raft is the easiest consensus algorithm to understand, and it's used in etcd, Consul and CockroachDB:

  1. One node is the leader. All writes go to it.
  2. The leader appends each write to its log and sends it to followers.
  3. When a majority has it, the entry is committed and applied.
  4. If the leader dies, a new one is elected (next lesson).

Where you meet consensus

You rarely implement it yourself. You use systems built on it:

  • etcd and ZooKeeper: configuration, service discovery, leader election and locks.
  • Kubernetes: stores all cluster state in etcd.
  • Distributed SQL (Spanner, CockroachDB): each shard is replicated by consensus.
  • Kafka (KRaft): keeps cluster metadata in a Raft log.

The cost

Every write waits for a majority round trip. Across data centres that's real latency, and if a majority is unreachable, the system stops accepting writes. That's the CP side of CAP, chosen on purpose.

Quick check

How many nodes can fail in a 5-node Raft cluster while it still accepts writes?