Consensus, leader election and distributed locks

Lesson 4.6 · 11 min read · by Vinay C

We'll cover the following

Visual summary

Infographic summarizing Consensus, leader election and distributed locks: You run a database on three servers. One is the leader: it takes every write and copies it to the other two. At 3 a.m.…

Download imageFree to share, please link back to this lesson.

The problem: the leader dies, who is next?

You run a database on three servers. One is the leader: it takes every write and copies it to the other two. At 3 a.m. the leader's machine crashes. The two survivors must pick a new leader, and they must agree on which one, even though messages can be lost or delayed. If each picks itself, you now have two leaders accepting different writes and your data is corrupted.

Getting several nodes to agree on one value (who is leader, which write comes next, what the config is) despite crashes is called consensus. Algorithms for it include Paxos, Raft, and ZAB (used by ZooKeeper).

Why a majority solves it

The trick is a majority quorum: nothing is decided unless more than half of all nodes agree. Any two majorities share at least one node, so two sides can never both win. That is why a cluster cannot elect two leaders at once.

To survive f failures you need 2f + 1 nodes.

NodesMajority neededFailures tolerated
321
431
532
642
743

Look at the 4-node row: it tolerates only 1 failure, the same as 3 nodes, but costs more and adds one more machine that can fail. So use odd sizes, usually 3 or 5. Consensus systems are CP (see CAP): a side of a partition without a majority stops accepting writes.

Raft step by step

Raft is the consensus algorithm to know best. Every node is in one of three roles: follower (the default), candidate (asking for votes) or leader. Time is cut into numbered terms, like election years, and each term has at most one leader.

Election. The leader sends regular heartbeats (small "I am alive" messages). If a follower hears none within a randomized timeout (roughly 150 to 300 ms), it assumes the leader is gone, becomes a candidate, adds 1 to the term and asks for votes. The timeouts are random so that usually only one node times out first instead of all at once. Five nodes, A is leader:

term 4: A is leader, sends heartbeats to B, C, D, E

A crashes. Heartbeats stop.
C's random timeout fires first (say 210 ms).

C: becomes candidate, term 4 -> 5, votes for itself
C -> B, D, E: "vote for me in term 5?"
B, D, E: haven't voted in term 5, C's log is up to date -> yes
C has 4 votes (needs 3 of 5) -> C is leader of term 5
C: sends heartbeats, the others stay followers

A restarts later, sees term 5 > 4, steps down to follower

Two safety rules make this correct. A node votes once per term, so two candidates cannot both reach a majority. And a node votes only for a candidate whose log is at least as up to date as its own, so a new leader always has every committed entry.

Replication. The leader takes all writes, appends each to its log and sends it to followers. An entry is committed (safe, will never be lost) once a majority of nodes have it. Only then is it applied and acknowledged to the client.

client: write x = 7
C (leader): appends entry #12 to its own log          (1 of 5)
C -> B, D, E: "append #12"
B: stored, replies ok                                  (2 of 5)
D: stored, replies ok                                  (3 of 5) = majority
C: entry #12 is COMMITTED -> applies x = 7, replies 200 to the client
E is slow: it gets #12 a bit later and catches up. That is fine.

Even if C crashes right after, any new leader must have #12, because a majority stored it and a candidate needs a majority of votes from nodes with up-to-date logs.

The partition case: 3 against 2

A network failure splits the 5 nodes into a group of 3 and a group of 2. The 3-node side has a majority, so it can elect a leader and commit writes. The 2-node side cannot reach 3 votes. If the old leader was on that side, it cannot commit anything, and it steps down once it sees a higher term. The minority side is unavailable for writes, which is the CP choice. Reads from minority nodes may also be stale unless they go through the leader.

You use consensus, you do not build it

Consensus is subtle and easy to get wrong. In practice you use it through a system that already has it.

SystemConsensus used for
etcdRaft; stores all Kubernetes cluster state
ConsulRaft; service discovery and config
ZooKeeperZAB (a Paxos-like protocol); coordination for older Kafka, Hadoop, HBase
Kafka KRaftRaft for cluster metadata, replacing ZooKeeper
Spanner, CockroachDBPaxos / Raft per data range, for strongly consistent distributed SQL

Leader election in practice

Your own services often need "exactly one of us does this job". Candidates race to create an ephemeral node (ZooKeeper, which vanishes when the creator's session dies) or to acquire a lease with a TTL (etcd, a claim that expires unless renewed). The winner is leader and keeps renewing. If it dies, the session or lease expires and another candidate wins.

  • Typical uses: one active scheduler or cron runner, primary database failover, the Kafka controller, the owner of a partition.
  • For small systems a row in the database you already run (SELECT ... FOR UPDATE) can be enough, as long as you accept that database as a single point of failure.

Distributed locks and the fencing token trap

A lock with a TTL (Redis SET lock:job id NX PX 30000) has a trap. The holder pauses (a long GC pause, a network stall) for longer than the TTL. The lock expires, a second client gets it, and then the first wakes up still believing it holds the lock. Both write.

A: acquires lock -> token 33 ... stalls (GC pause) ... lock expires
B: acquires lock -> token 34, writes to storage with token 34
A: wakes up, writes with token 33 -> storage rejects it (33 < 34)

The fix is a fencing token: the lock service hands out an increasing number with each grant, and the resource being protected (the database or storage) rejects any write carrying a lower number than the highest it has seen. The check happens at the resource, so even a confused old holder cannot do damage.

Which lock do you need?

  • Efficiency lock: the lock only saves work, and running a job twice is harmless. A single-node Redis lock is fine.
  • Correctness lock: two holders would corrupt data. Use a consensus-based service (etcd, ZooKeeper) with fencing tokens. The multi-node Redis "Redlock" scheme is debated, so do not lean on it for correctness.
  • Often better: avoid the lock. Make the operation idempotent, or use a unique constraint or an optimistic version check in the database.

Split brain

Split brain means two nodes both think they are the leader after a network partition, and both accept writes. Prevent it with quorum (a minority cannot act) and fencing (a stale leader's writes are rejected).

Check yourselfA 5-node etcd cluster is split by a partition into 3 and 2 nodes. Which side accepts writes, and what happens to a leader on the 2-node side?

Only the 3-node side has a majority, so it elects a leader and commits writes. The 2-node side cannot reach quorum: its old leader cannot commit and steps down once it sees a higher term. Reads served by minority nodes may be stale unless they go through the leader.

Check yourselfWhy do clusters use 3 or 5 nodes, not 4 or 6?

A majority of 4 is 3, so 4 nodes still tolerate only 1 failure, the same as 3, while costing more and adding another node that can fail. Odd sizes give the most fault tolerance per node.

Summary: say it in the interview

  • "I would not build consensus. I would use etcd or ZooKeeper for leader election and locks, with lease TTLs and fencing tokens so a paused old leader cannot corrupt data."