TExcelTAD
Home › System Design › Consensus and Leader Election

Consensus and Leader Election

Many problems in distributed systems boil down to getting several machines to agree on one value, even when some of them crash or messages are delayed: which node is the leader, which write came first, whether a lock is held, what the cluster configuration is. This is the consensus problem. The algorithms that solve it, Paxos and the easier-to-understand Raft, power etcd (Kubernetes' brain), Consul, ZooKeeper (ZAB, a close relative), CockroachDB, TiKV and Kafka's KRaft mode.

Majorities (quorums)

Consensus algorithms rely on majorities. A decision needs votes from more than half of the nodes. Any two majorities overlap in at least one node, so two conflicting decisions can never both win. The cost: a cluster of n nodes survives only (n - 1) // 2 failures.

python · try it yourself
for n in range(1, 8):
    majority = n // 2 + 1
    print(f"{n} nodes: majority {majority}, tolerates {n - majority} failure(s)")
1 nodes: majority 1, tolerates 0 failure(s)
2 nodes: majority 2, tolerates 0 failure(s)
3 nodes: majority 2, tolerates 1 failure(s)
4 nodes: majority 3, tolerates 1 failure(s)
5 nodes: majority 3, tolerates 2 failure(s)
6 nodes: majority 4, tolerates 2 failure(s)
7 nodes: majority 4, tolerates 3 failure(s)

Four nodes tolerate no more failures than three, and six no more than five. Even sizes add cost without adding fault tolerance, which is why clusters have 3, 5 or 7 members.

Raft in a nutshell

Each Raft node is a follower, a candidate or the leader. Time is divided into numbered terms; each term has at most one leader.

text
           timeout, start election               receives votes from a majority
follower ---------------------------> candidate ----------------------------------> leader
   ^                                     |                                              |
   |   discovers a higher term / leader  |                                              |
   +-------------------------------------+---------------------------------------------+
  1. Leader election. Followers expect regular heartbeats from the leader. If a follower hears nothing for its election timeout (randomised, e.g. 150-300 ms), it increments the term, votes for itself and asks the others for votes. Each node votes at most 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.
  2. Log replication. Clients send commands to the leader, which appends them to its log and sends them to followers. Once a majority has stored an entry, it is committed and can be applied to the state machine.
  3. Safety. Because a candidate needs a majority and voters reject candidates with older logs, a new leader always has every committed entry.

Randomised timeouts are what make elections usually finish in one round: the node whose timer fires first typically collects all votes before anyone else even becomes a candidate.

Simulating an election

The model below uses seeded random timeouts and a simulated clock in milliseconds. Node n1 is the leader of term 1 until it crashes at t=100.

python · try it yourself
import random

rng = random.Random(42)
nodes = ["n1", "n2", "n3", "n4", "n5"]
alive = {n: True for n in nodes}
term = {n: 1 for n in nodes}
voted_for = {n: None for n in nodes}
leader = "n1"
last_heartbeat = 100                              # n1's last heartbeat, then it crashes
alive["n1"] = False
print("t=100 leader n1 crashes")

timeouts = {n: rng.randint(150, 300) for n in nodes if alive[n]}
print("election timeouts (ms):", timeouts)

# The follower whose timer fires first becomes a candidate
candidate = min(timeouts, key=timeouts.get)
t = last_heartbeat + timeouts[candidate]
term[candidate] += 1
voted_for[candidate] = candidate
votes = 1
print(f"t={t} {candidate} times out, starts election for term {term[candidate]}")

for n in nodes:
    if n == candidate:
        continue
    if not alive[n]:
        print(f"      {n} is down, no reply")
        continue
    if term[candidate] > term[n]:                 # newer term: update and reset vote
        term[n], voted_for[n] = term[candidate], None
    if voted_for[n] is None:
        voted_for[n] = candidate
        votes += 1
        print(f"      {n} votes for {candidate}")

majority = len(nodes) // 2 + 1
if votes >= majority:
    leader = candidate
    print(f"{candidate} wins with {votes}/{len(nodes)} votes and leads term {term[candidate]}")
t=100 leader n1 crashes
election timeouts (ms): {'n2': 178, 'n3': 156, 'n4': 220, 'n5': 212}
t=256 n3 times out, starts election for term 2
      n1 is down, no reply
      n2 votes for n3
      n4 votes for n3
      n5 votes for n3
n3 wins with 4/5 votes and leads term 2

The cluster has a new leader 156 ms after the crash, with no human involved. With only two of five nodes alive, the candidate could never reach 3 votes and the cluster would stop accepting writes rather than risk two leaders: Raft is a CP system.

Log replication and commit

A leader can only commit an entry once a majority stores it. Followers that are slow or down simply catch up later:

python · try it yourself
followers_up = {"n3": True, "n4": True, "n5": False}   # n5 is down
leader_log, follower_logs = [], {n: [] for n in followers_up}
commit_index = 0
cluster_size = 1 + len(followers_up)

def replicate(command):
    global commit_index
    leader_log.append(command)
    acks = 1                                       # the leader itself
    for f, up in followers_up.items():
        if up:
            follower_logs[f] = list(leader_log)    # leader sends missing entries
            acks += 1
    if acks > cluster_size // 2:
        commit_index = len(leader_log)
    return acks

for cmd in ["SET x=1", "SET y=2"]:
    acks = replicate(cmd)
    print(f"{cmd}: stored on {acks}/{cluster_size} -> committed up to entry {commit_index}")

followers_up["n4"] = False                         # now two followers are down
acks = replicate("SET z=3")
print(f"SET z=3: stored on {acks}/{cluster_size} -> committed up to entry {commit_index} (not committed!)")

followers_up.update({"n4": True, "n5": True})      # nodes come back
acks = replicate("SET w=4")
print(f"SET w=4: stored on {acks}/{cluster_size} -> committed up to entry {commit_index}")
print("n5's log after catching up:", follower_logs["n5"])
SET x=1: stored on 3/4 -> committed up to entry 1
SET y=2: stored on 3/4 -> committed up to entry 2
SET z=3: stored on 2/4 -> committed up to entry 2 (not committed!)
SET w=4: stored on 4/4 -> committed up to entry 4
n5's log after catching up: ['SET x=1', 'SET y=2', 'SET z=3', 'SET w=4']

In this 4-node model, two acknowledgements out of four is not a majority, so SET z=3 waits. As soon as enough followers are back, the leader commits it together with the next entry, and the returning node n5 receives the entire log.

Using consensus in a design

You will rarely implement Raft yourself. Instead you use a system built on it:

Need Typical tool
Leader election for your service's workers etcd / ZooKeeper / Consul lease or lock
Strongly consistent configuration, service discovery etcd, Consul
Distributed lock with fencing tokens etcd revision numbers, ZooKeeper zxid
A strongly consistent replicated database CockroachDB, TiDB, YugabyteDB, Spanner (Paxos)

Note: A lock or lease alone isn't safe: a paused process may still believe it holds an expired lease. Pass a fencing token (a number that increases with every new lease) to the protected resource, which rejects requests carrying an older token.

Test yourself

How many node failures can a 5-node Raft cluster tolerate while staying available?

  1. 1
  2. 2
  3. 3
  4. 4

Why are Raft election timeouts randomised?

  1. To save battery
  2. So that usually one node times out first and wins before others start competing elections
  3. To encrypt votes
  4. Because clocks are unreliable

When is a Raft log entry committed?

  1. When the leader writes it to its own disk
  2. When a majority of nodes have stored it
  3. When every node has stored it
  4. When the client reads it