Consensus and Leader Election
How a group of machines agrees on one leader or one value, how majorities, leases and fencing tokens work, and what interviewers ask about them.
On this page
Consensus is the problem of getting a group of machines to agree on a single answer, such as which of them is the leader or what the next entry in a log is, even when some of the machines are slow, crashed or cut off from the network. Protocols such as Raft and Paxos solve it, and in practice most systems use them through a coordination service such as ZooKeeper or etcd. Leader election is the most common use: the group agrees on exactly one machine that owns a job, a shard or the right to write.
Without consensus, two machines can each decide that they are the leader. Suppose a billing job runs on two schedulers so that one can take over when the other dies, and each takes over after missing five heartbeats from the other. If the network between them breaks for ten seconds, both stop hearing the other, both conclude the other has died, and both run the job. This situation is called split brain, and here it means every customer is charged twice.
Where consensus sits in a system
The coordination service is a small cluster that runs a consensus protocol internally. The rest of the system asks it who the leader is, or asks it to hold a small piece of shared state such as a lock, and trusts the answer.
Why agreeing is hard
When a machine stops answering, the other machines cannot tell whether it has crashed, is overloaded, is paused by garbage collection, or is running normally but unreachable. A timeout turns that uncertainty into a guess, and the guess can be wrong. Messages can also arrive late or never, and clocks drift apart.
Two machines cannot solve this with a heartbeat rule. If each waits for the other before acting, one failure stops everything, and if each acts alone once the other goes silent, a partition gives you two leaders. Consensus protocols therefore always keep the data safe, so two leaders never both commit conflicting writes, but they make progress only while enough machines can talk to each other. During a bad partition they stop answering instead of risking a wrong answer, which is the choice described in CAP and consistency.
Majority quorums
A quorum is the number of nodes that must take part in a decision, and consensus systems use a majority: more than half of all nodes. Any two majorities of the same group share at least one node, and that node will not support two conflicting decisions, so two conflicting decisions can never both win. A group cut off from the rest that holds only a minority cannot decide anything.
A cluster of 2f + 1 nodes keeps working while f nodes are down. Three nodes tolerate one failure, and five nodes tolerate two. Four nodes tolerate only one failure, because a majority of four is three, so an even number of nodes costs more without surviving more. Clusters therefore have an odd size, almost always three or five.
Leader-based consensus with Raft
Raft is the protocol interviewers most often expect you to outline. It has three parts: terms, a replicated log and elections.
Terms and the leader
Time is divided into numbered terms. A node becomes the leader of a term only if a majority of nodes vote for it, and each node votes for at most one candidate per term. Every message carries the sender's term, and a node that sees a higher term than its own steps down and follows it, which is how an old leader learns that it has been replaced.
The replicated log and commit
Every change goes to the leader, which appends it to its log and sends it to the followers. An entry is committed once a majority of nodes, counting the leader, have stored it. Only then does the leader apply the change and answer the client. Every write waits for a round trip to a majority, which is slow when the nodes are far apart.
Leader election
A follower that hears no heartbeat for a randomised timeout, usually a few hundred milliseconds, becomes a candidate. It increases its term, votes for itself and asks the others for votes. The timeout is random so that nodes rarely become candidates together and split the vote, and if a vote does split, the nodes retry with new random timeouts. A node votes only for a candidate whose log is at least as complete as its own. A committed entry is on a majority, and the majority that elects a new leader shares a node with it, so the winner always holds every committed entry.
- term
- 3
- entry 7 copies
- 1
1Node 1 leads term 3. A client writes
owner = A, and the leader appends it as entry 7 and sends it to both followers.- term
- 3
- entry 7 copies
- 2
2Node 2 stores the entry. Two of three nodes hold it, a majority, so entry 7 is committed even though Node 3 is slow.
- term
- 3
- entry 7 copies
- 2
3The leader applies the entry and tells the client that the write succeeded.
- term
- 3
- leader
- none
4Node 1 crashes, so the heartbeats stop.
- term
- 4
- votes for 2
- 1
5Node 2's timeout fires first. It starts term 4, votes for itself and asks Node 3.
- term
- 4
- votes for 2
- 2
6Node 3 votes yes, so Node 2 leads term 4. It holds entry 7, because the majority that committed it overlaps the one that elected Node 2.
- term
- 4
- leader
- Node 2
7The client retries against Node 2.
- term
- 4
- leader
- Node 2
8Node 1 restarts still believing it leads term 3. The first message it sees carries term 4, so it steps down.
Leader election with leases and fencing tokens
Application teams almost never implement Raft; they ask a coordination service for leadership, using a lease, and make the lease safe with a fencing token.
Leases
A lease is a lock that expires on its own. A node asks the coordination service for leadership and receives it for a fixed period, for example ten seconds, and it must renew the lease before the period ends. If the leader crashes or is cut off, it stops renewing, the lease expires and another node can take it.
A lease alone does not prevent two leaders. The leader checks its own clock to decide that it still holds the lease, and its process can be paused by garbage collection or a virtual machine freeze for longer than the lease lasts. It then wakes up, still believes it leads, and writes, although the lease now belongs to someone else.
Fencing tokens
A fencing token is a number that increases with every lease the service grants. The leader sends its token with every write, and the resource being written remembers the highest token it has seen and rejects any write with a lower one. The check must happen in the resource itself, because only the resource sees all the writes.
- store's highest token
- 0
1Scheduler A acquires a ten-second lease and receives token 33.
- store's highest token
- 33
2A writes with token 33, and the store records 33 as the highest token seen.
- store's highest token
- 33
3A pauses for 15 seconds for garbage collection and does not know that time has passed.
- store's highest token
- 33
4The lease expires and goes to Scheduler B with token 34.
- store's highest token
- 34
5B writes with token 34, and the store accepts it and records 34.
- store's highest token
- 34
6A wakes up and writes with token 33. The store has seen 34, so it rejects the write.
Options for getting a single leader
A lease from a coordination service
Your nodes ask ZooKeeper, etcd or a similar service for a lease. The consensus is done for you, the code on your side is small, and the service can hand out increasing numbers for tokens. The costs are one more cluster to run, and a rule your code must follow: a leader that cannot reach the service must stop acting once its lease would have expired. Use it for schedulers, single-writer workers and shard owners. It is the right default in an interview.
A datastore with consensus built in
Many databases run Raft or Paxos between their replicas, so each partition has an automatically elected leader and a commit means a majority has the data. A failover does not lose committed writes, but every write pays a round trip to a majority. Choose it when the data itself needs failover without lost commits, and see Replication for how it compares with asynchronous replicas.
A lock row in an existing database
A table with one row holds the current owner and an expiry time, and a node takes leadership by updating the row only if it is free or expired. It needs no new system, but it is only as available as that database, the expiry must be judged by the database's clock, and you must add the fencing counter yourself. Avoid it when the database replicates asynchronously, because a failover can lose the latest lock update and grant the lock twice.
What a coordination service stores
A coordination service holds small pieces of state that many machines must agree on: the current leader, locks (the same lease mechanism, held by whoever is doing a task), configuration that every node must see consistently, and membership, the list of live nodes, which works because a crashed node's session expires and its entry disappears. Keep the data small and the write rate low, because every write goes through a majority, and keep bulk data in an ordinary database.
Problems interviewers probe
A partition splits the cluster
The side with a majority keeps a leader and continues to commit writes. The minority side cannot elect a leader or commit, so it refuses writes, which gives up availability there to stay consistent. A leader stranded on the minority side must stop acting once it cannot reach a majority, and the fencing token protects the resource if it does not stop in time.
A stale leader serves old reads
An isolated leader can still believe it leads and answer a read with data that a newer leader has since changed. Systems that promise fresh reads make the leader confirm with a majority first, or let it serve reads only while it holds a time-based lease. Reads that may be slightly old can come from any node.
In the interview
Bring up consensus when something must have exactly one owner, such as a leader, a lock or a shard map, or when you promise that failover will not lose acknowledged writes. Say that you would use an existing coordination service and name what you store there, for example the current leader and the shard assignments. Do not design the protocol unless the interviewer asks.
Questions to expect:
- "Why not use two nodes and heartbeats?" During a partition each node sees the other as dead and both become leader. With three nodes and a majority rule only the side with two nodes can proceed.
- "How many nodes would you run?" Three or five, because a cluster of 2f + 1 nodes survives f failures. An even count adds cost without more tolerance, and more than five makes every write wait for more nodes.
- "What if the leader pauses and wakes up after a new leader was elected?" It still thinks it leads and tries to write. Each lease carries a fencing token, and the storage rejects any write with a lower token than the highest it has seen.
- "What happens during a network partition?" The side with a majority elects a leader and keeps working. The minority side cannot commit and refuses writes, so the system chooses consistency over availability.
- "Would you store user data in ZooKeeper or etcd?" No, because each write goes through a majority and the data set is kept small. They hold leaders, locks, configuration and membership, and user data belongs in a database built for that load.
- "What is the difference between Raft and Paxos?" Both use majorities and tolerate the same failures. Raft is built around one strong leader and a replicated log and was designed to be easy to understand, while Paxos is described as agreement on a single value that real systems extend into a log.
- "Is a lock from a coordination service enough to guarantee that only one process works at a time?" No, because the holder can be paused and keep acting after its lease expires. The lock is safe only when the resource being protected checks a fencing token, or when the work is idempotent so that a duplicate run does no harm.
How do you make sure only one scheduler runs the billing job?
The schedulers take a lease from a three-node coordination service, which keeps working if one node fails. The lease lasts ten seconds and the holder renews it every three, and only the holder runs the job.
What if the holder freezes and wakes up after the lease has moved to another scheduler?
It would write as if it were still the leader. To stop that, each lease carries a fencing token, and the billing store rejects any write whose token is lower than the highest it has seen. I would also make each charge idempotent per customer and month, so that even a duplicate run cannot bill anyone twice.
How many node failures can a 5-node majority cluster survive and still commit writes?
A storage service has already seen fencing token 52. A write arrives with token 51. What should it do?
What to practise next
Read Unique IDs to see how machine numbers are assigned with the help of a coordination service, and Design a Job Scheduler for a full design that uses a lease-based leader.