Leader election and consensus

Topic 6 of 9 in Week 5: Distributed systems and service communication11 min readAdvancedFree course

Overview

Many problems need a group of machines to agree: which node is the primary database, who holds a lock, what the current configuration is, in what order to apply writes. Agreeing is hard when nodes crash and messages get lost or delayed. Consensus algorithms such as Raft and Paxos solve it, and they sit underneath the coordination services and databases you’ll use.

What consensus provides

A consensus algorithm lets nodes agree on a sequence of values (a replicated log) so that:

  • every node that applies the log applies the same entries in the same order,
  • a committed entry is never lost or changed,
  • the system makes progress as long as a majority of nodes are running and can talk to each other.

Feed that log to identical state machines (a key-value store, a database) and you get a replicated, strongly consistent service.

Raft in plain terms

Leader election and log replication in Raft. A leader in term 7 sends AppendEntries messages for log entry 42, which also act as heartbeats, to four followers. Followers 1 and 2 acknowledge; followers 3 and 4 are slow. Entry 42 is committed once a majority, 3 of 5 including the leader, has it, and then it is applied. If followers stop hearing heartbeats, one becomes a candidate in term 8 and asks for votes; a majority vote makes it leader, and two leaders can’t win the same term. Use it via etcd, ZooKeeper or Consul for leader election, locks, configuration and service discovery.

  1. Terms. Time is divided into numbered terms; each term has at most one leader.
  2. Election. Followers expect regular heartbeats. If one hears nothing for a randomised timeout, it becomes a candidate, increments the term and asks the others for votes. Each node votes once per term, and only for a candidate whose log is at least as up to date as its own. A majority of votes makes it leader.
  3. Replication. Clients send writes to the leader. The leader appends them to its log and sends them to followers (AppendEntries, which double as heartbeats).
  4. Commit. Once a majority has stored an entry, the leader marks it committed, applies it and tells followers to apply it too.

Because any two majorities overlap, a new leader always has every committed entry. A leader cut off in a minority partition can’t commit anything new, so it can’t cause conflicting decisions.

Paxos (and Multi-Paxos) achieves the same with a different structure; it’s used in Google’s Chubby and Spanner. Raft was designed to be easier to understand and is used by etcd, Consul, CockroachDB, TiKV and Kafka’s KRaft mode.

Sizing a cluster

Nodes Majority Failures tolerated
3 2 1
5 3 2
7 4 3

Use odd numbers: 4 nodes tolerate only 1 failure, like 3. More nodes mean more fault tolerance but slower commits (more replies to wait for). Spreading nodes across three zones lets the cluster survive a zone outage.

Leader election for your own services

You rarely implement Raft. Instead, use a coordination service built on it:

  • etcd (Kubernetes’ brain), ZooKeeper and Consul offer leases, locks, watches and strongly consistent key-value storage.
  • The pattern: each instance tries to acquire a lease key with a time-to-live; the winner is leader and keeps renewing; others watch the key and take over if it expires.

Use cases: one active scheduler or cron runner, a single writer per shard, primary election for a database cluster, distributed locks for rare but critical operations.

Leases and fencing tokens

Leadership by lease has a trap. A leader may pause (long garbage collection, VM migration) past its lease, while a new leader is elected. When the old one wakes up, it still believes it’s leader and may write.

The fix is a fencing token: a number that increases every time leadership is granted (etcd revisions and ZooKeeper zxids work). The leader includes it with every write, and the storage rejects writes carrying a smaller token than it has already seen. The paused leader’s stale writes are refused.

When you need consensus, and when you don’t

You need it when exactly one winner matters: locks, leader election, unique allocation, ordering of critical writes, cluster membership and configuration.

You don’t need it for most application data paths: a primary-replica database already embeds a leader; caches, feeds and analytics can be eventually consistent. Consensus has a cost: every write waits for a majority, and a cluster that loses its majority stops accepting writes.

In an interview

If your design has a singleton (one scheduler, one primary per shard, a lock), say how it’s elected: “Workers hold a lease in etcd; the holder is the active scheduler, and every job write includes the lease revision as a fencing token.” For database failover, mention that managed databases use a consensus-based or witness-based mechanism to avoid split brain.

Recap

Consensus algorithms let a majority of nodes agree on one leader and one order of changes despite failures. Raft elects a leader per term, replicates log entries and commits them on a majority. Clusters of 3 or 5 nodes tolerate 1 or 2 failures. Use etcd, ZooKeeper or Consul for leader election and locks, pair leases with fencing tokens, and reserve consensus for the places where one winner truly matters.

Exercise

Run a job exactly once

Five instances of a billing service run in a cluster. Every night at 01:00 exactly one of them must generate invoices. (a) Why is 'the instance with the lowest IP address does it' a bad idea? (b) Design leader election using a coordination service like etcd or ZooKeeper. (c) The leader pauses for 40 seconds (a long garbage-collection pause), loses its lease, and a new leader starts generating invoices. Then the old one wakes up and continues. How do you stop it from writing duplicate invoices?

Text
(a)
(b)
(c)

Summary

  • Consensus lets a group of nodes agree on a value or a sequence of values despite failures, as long as a majority is up and connected.
  • Raft elects a leader per term by majority vote; the leader appends entries and commits them once a majority has them.
  • Clusters of 3 or 5 nodes tolerate 1 or 2 failures; a minority side of a partition can't make progress.
  • Leases give leadership for a limited time; fencing tokens stop a paused old leader from causing damage.
  • Rather than implementing consensus, use etcd, ZooKeeper or Consul, or a database built on Raft or Paxos.