System design concepts · When Machines Disagree

Consensus, Leader Election and Distributed Locks (Raft, ZooKeeper)

Getting several machines to agree on one value, even when some crash and messages get lost, is the foundation under every reliable database, scheduler and lock service.

What you'll be able to explain
  • Explain what consensus provides and why majorities matter
  • Walk through Raft's leader election and log replication
  • Use etcd/ZooKeeper for election, config and membership
  • Implement a distributed lock safely with leases and fencing tokens
  • Know when you don't need consensus at all

What consensus gives you

Consensus lets a group of nodes agree on a sequence of values (a replicated log) such that:

  • every node applies the same commands in the same order;
  • once a value is committed, it's never lost or changed;
  • the system makes progress as long as a majority (quorum) is up and talking.

With 5 nodes, a majority is 3, so the cluster tolerates 2 failures. With 3 nodes it tolerates 1. Even numbers don't help: 4 nodes still tolerate only 1.

Analogy

A committee that can only pass a motion with a majority vote. Any two majorities overlap in at least one member, so two contradictory motions can never both pass, even if some members are absent.

Raft in one picture

Node ANode BNode C1election timeout → becomes candidate (term 7)2RequestVote(term 7)3RequestVote(term 7)4vote granted5majority (2/3) → leader for term 76AppendEntries(x=5)7AppendEntries(x=5)8ok9majority stored → commit, reply to client
Raft: leader election, then replicating an entry to a majority before committing.

Key ideas:

  • Terms are logical epochs; a node that sees a higher term steps down.
  • Randomised election timeouts prevent endless split votes.
  • A candidate wins only if its log is at least as up to date as the voters', so committed entries are never lost.
  • Writes go through the leader and commit once a majority has them.

Raft powers etcd, Consul, CockroachDB, TiKV and Kafka's KRaft. Paxos solves the same problem (Spanner, Chubby); Raft was designed to be easier to understand.

Coordination services

You rarely implement Raft. You use a coordination service built on it (etcd, ZooKeeper, Consul) for small, critical data:

  • Leader election: candidates race to create a key with a lease; the winner is leader until its lease expires.
  • Configuration and feature flags with watches (push on change).
  • Service discovery and membership with ephemeral registrations.
  • Distributed locks and barriers.
Common trap

Using a coordination service as a general database. It's designed for kilobytes of critical metadata with modest write rates, not millions of user records.