Consensus, Leader Election and Coordination

Understand why distributed nodes need consensus, how Raft elects a leader and replicates a log, and how ZooKeeper and etcd are used for coordination.

Advanced · about 4 hours · difficulty 4/5

Learn first: Consistency Models, CAP and PACELC

Many systems need several machines to agree on something: who the leader is, which config is current, whether a transaction committed. Agreement is hard when messages are delayed and nodes crash. Consensus algorithms solve it.

The core problems

  • Clocks drift, so you cannot order events by wall time alone. Logical clocks (Lamport timestamps) and vector clocks capture "happened before".
  • Failure detection is guesswork. A node that does not reply might be dead or just slow.
  • Split brain: two nodes both believe they are the leader and accept conflicting writes.

Raft in brief

  • Nodes are followers, candidates or a leader. A follower that hears no heartbeat starts an election for a new term.
  • A candidate needs votes from a majority (a quorum). With 5 nodes, 3 must agree, so the cluster survives 2 failures.
  • The leader appends commands to its log and replicates them; an entry is committed once a majority has it.
  • Because any two majorities overlap, a new leader always has every committed entry.

Paxos solves the same problem; Raft was designed to be easier to understand.

Where you use it

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

  • etcd (Kubernetes' brain), ZooKeeper (older Kafka, HBase), Consul.
  • Uses: leader election, distributed locks with fencing tokens, service discovery, cluster membership, configuration.
  • Databases like CockroachDB, TiDB and Kafka's KRaft mode use Raft internally.

Pitfalls

  • Running consensus clusters with an even number of nodes (4 tolerates no more failures than 3).
  • Putting high-volume data in ZooKeeper or etcd; they are for small, critical metadata.
  • Using wall clock timestamps to decide which write wins across machines.

You are ready to move on when you can explain why a 5-node Raft cluster tolerates 2 failures and how it avoids two leaders in the same term.

Key concepts

  • Why consensus is needed
  • Quorums and majorities
  • Raft leader election and log replication
  • Lamport and vector clocks
  • Split brain and fencing tokens
  • etcd and ZooKeeper
  • Paxos

Mini project

Run a 3-node etcd cluster in Docker. Use it to elect a leader among three worker processes, kill the leader, and log how long failover takes. Then partition one node and show it cannot accept writes.

Check yourself

Why does a cluster of 4 consensus nodes tolerate the same number of failures as a cluster of 3?

Free resources