Sub topic 12
Quorum and leader election
This chapter assumes you know how synchronous and asynchronous replication work, what a heartbeat and a health check are, and that nodes talk over a network that can delay or drop messages. Earlier chapters covered how replicas copy data. This chapter covers how a group of replicas agrees on who is in charge, and why a majority is the rule most systems use.
Why a group needs a leader
Replicated systems that accept writes need an order for those writes. The simplest way to get one is to pick a single node, the leader (also called primary or master), to accept writes and send them to followers. Followers apply the same writes in the same order.
A leader gives you a simple model, but it creates a question. When the leader fails, who replaces it? If one operator or script chooses, you have a new single point of failure. If every node chooses for itself, two nodes may each decide they are the leader. The answer is a protocol in which the nodes vote, and a decision counts only when enough of them agree.
Quorum: the majority rule
A quorum is the minimum number of nodes that must agree before a decision is valid. In most systems the quorum is a strict majority: more than half of all configured nodes.
For a cluster of N nodes, the quorum is floor(N / 2) + 1.
The key property is that any two majorities share at least one node. Two groups that each hold more than half of the nodes cannot be disjoint. So two separate groups cannot both reach a quorum on conflicting decisions, because the overlapping node would have to vote for both.
def quorum(n):
return n // 2 + 1
def tolerated_failures(n):
return n - quorum(n)
for n in range(1, 8):
print(n, quorum(n), tolerated_failures(n))| Cluster size | Quorum | Failures tolerated |
|---|---|---|
| 1 | 1 | 0 |
| 2 | 2 | 0 |
| 3 | 2 | 1 |
| 4 | 3 | 1 |
| 5 | 3 | 2 |
| 6 | 4 | 2 |
| 7 | 4 | 3 |
Two patterns in the table matter for design:
- Going from 3 nodes to 4 adds no fault tolerance. Both tolerate one failure. The fourth node adds cost and one more vote to collect.
- Two nodes are worse than one in one respect. Losing either node loses the quorum, so the cluster is twice as likely to be unavailable.
For this reason, clusters that use majority voting normally have an odd number of nodes: 3, 5, or 7. Larger clusters are rare because every write must reach a majority, so more nodes mean more messages and more latency.
Quorum and network partitions
A network partition is a failure of the network that splits the nodes into groups that cannot talk to each other, while every node is still running. From inside a group, the nodes on the other side look dead. A node cannot tell the difference between "that peer crashed" and "that peer is unreachable".
Quorum resolves this without needing to tell the difference. Each group asks one question: do I contain a majority of the configured cluster? Counting is against the configured size, not the number of nodes currently visible.
- The majority side (3 of 5) can elect a leader and keep accepting writes.
- The minority side (2 of 5) cannot. It stops accepting writes, or serves reads only if the system allows stale reads.
This trades availability for consistency. During a partition, the minority side is unavailable for writes so that the cluster never accepts conflicting writes in two places. This is the practical meaning of choosing consistency over availability in a partition.
If the partition splits a cluster so that no group has a majority, such as 2, 2, and 1 in a five-node cluster, no side can accept writes. The cluster is down until the network heals.
Leader election
Leader election is the process by which nodes choose one node to act as leader. Many systems use a Raft-style design. The details differ between systems, but the common parts are these.
- Terms. Time is divided into numbered terms (also called epochs or generations). Each term has at most one leader. The term number only goes up.
- Follower state. Each node starts as a follower. It expects regular heartbeats from the leader.
- Election timeout. If a follower hears no heartbeat before its timeout expires, it assumes the leader is gone. It increments its term, becomes a candidate, votes for itself, and asks the others for votes.
- Voting. A node grants at most one vote per term. It also refuses to vote for a candidate whose log is less up to date than its own, so a node that missed committed writes cannot become leader.
- Winning. A candidate that collects votes from a majority becomes leader and starts sending heartbeats.
- Stepping down. Any node that sees a higher term than its own immediately reverts to follower.
Randomized timeouts
If all followers time out at the same moment, they all become candidates, each votes for itself, and nobody gets a majority. This is a split vote. The election fails and repeats.
To avoid this, each node picks its election timeout at random from a range, for example 150 to 300 ms. One node usually times out first, wins the votes, and sends heartbeats before the others time out.
Tuning the timeout
The election timeout has the same speed-versus-false-positives trade-off you saw with health checks.
- A short timeout detects a dead leader quickly, which lowers recovery time. It also triggers elections when the leader is only slow, for example during a garbage collection pause or a brief network delay. Needless elections interrupt writes.
- A long timeout avoids needless elections, but the cluster is without a leader for longer after a real crash.
The timeout should be several times larger than the typical heartbeat round trip, and well above the worst pauses you see in production.
A small simulation
The following code models the voting rule: one vote per term, a majority required, and a partitioned minority that cannot win.
class Node:
def __init__(self, name):
self.name = name
self.term = 0
self.voted_for = {} # term -> candidate name
def request_vote(self, term, candidate):
if term < self.term:
return False
self.term = max(self.term, term)
if term in self.voted_for and self.voted_for[term] != candidate:
return False
self.voted_for[term] = candidate
return True
def run_election(candidate, reachable, cluster_size):
candidate.term += 1
term = candidate.term
votes = 1 # the candidate votes for itself
candidate.voted_for[term] = candidate.name
for peer in reachable:
if peer.request_vote(term, candidate.name):
votes += 1
needed = cluster_size // 2 + 1
return votes >= needed, votes, needed
nodes = [Node(c) for c in "ABCDE"]
a, b, c, d, e = nodes
# Partition: {A, B, C} can talk, {D, E} can talk.
won, votes, needed = run_election(a, [b, c], 5)
print("A wins:", won, votes, "of", needed)
won, votes, needed = run_election(d, [e], 5)
print("D wins:", won, votes, "of", needed)Node A gets 3 votes and wins. Node D gets 2 votes against a requirement of 3 and does not. The needed count uses the configured cluster size of 5, not the 2 nodes D can see.
Leaders can be stale
Winning an election does not guarantee that a node knows it has lost leadership later. Suppose a leader is paused for 30 seconds by a long garbage collection or a virtual machine freeze. The other nodes elect a new leader in a higher term. When the old leader wakes, it still believes it is the leader until it hears a message with a higher term.
Quorum prevents the old leader from committing writes, because it cannot gather a majority in its stale term. But if the old leader also writes to a resource outside the voting group, such as a shared disk or an object store, nothing in the vote stops it. Terms and tokens must be carried through to those resources. The next chapter covers this problem and the fencing technique that solves it.
Where you meet this in practice
You rarely write an election protocol yourself. You use a system that has one.
- Coordination services such as ZooKeeper and etcd run a consensus protocol (ZAB and Raft respectively) across 3 or 5 nodes. Other systems use them to elect their own leaders through locks or leases.
- Databases such as PostgreSQL managed by Patroni, MongoDB replica sets, and CockroachDB elect a primary through a consensus group or a majority vote.
- Managed services hide the voting but still apply the rule. Check the documentation for how many nodes the service needs and how it places them.
Common mistakes
- Running an even number of voters. A four-node cluster tolerates the same failures as three. A common version of this is two nodes, which cannot lose either one.
- Placing voters in one fault domain. Three voters in the same rack or zone are lost together, and the quorum with them. Spread voters across fault domains, using three zones for a three-node group.
- Splitting evenly across two sites. With three nodes in one site and two in another, losing the first site loses the quorum. With two sites, one site always holds the majority. Put a third voter, even a small one, in a third location.
- Ignoring clock and pause assumptions. Leases and timeouts depend on timing. Pauses longer than the lease can make a node act on stale authority.
- Treating the voter count as changeable on the fly. Adding or removing voters changes what a majority is. Use the system's membership change procedure, and change one node at a time.
Summary of the working model
- Quorum is a strict majority of the configured nodes,
N // 2 + 1. - Any two majorities overlap, so two groups cannot both decide conflicting things.
- A partitioned minority stops accepting writes. This protects consistency and costs availability.
- Elections use numbered terms, one vote per node per term, and randomized timeouts to avoid split votes.
- A former leader can still act until it learns of a higher term, so external resources need extra protection.
Exercise
A team runs a database cluster with four nodes, two in zone 1 and two in zone 2. They believe this lets them survive the loss of a whole zone. Is that true? What would you change?
Show answer
No. The quorum for four nodes is 3. Losing a zone removes two nodes and leaves two, which is below the quorum, so the cluster stops accepting writes. A partition between the zones is also fatal, because each side has only 2 of 4 votes. Change the layout to three nodes in three zones (quorum 2, tolerates the loss of any one zone), or add a fifth voter in a third zone. Four nodes tolerate only one failure, the same as three.
Exercise
A five-node cluster is partitioned into groups of 3 and 2 nodes. A client connected to the group of 2 sends a write. What should happen, and why?
Show answer
The group of 2 holds 2 of 5 votes and the quorum is 3, so it cannot elect a leader or commit the write. The client should receive an error or a timeout, or retry against the group of 3. The group of 3 holds a majority and can continue. Refusing the write on the minority side prevents two conflicting versions of the data.
Exercise
Why do Raft-style systems use a random election timeout for each node instead of the same fixed value?
Show answer
With a fixed value, all followers would time out at the same moment, become candidates together, and each vote for themselves. No candidate would reach a majority, and the split vote would repeat. Random timeouts make one node time out first, so it can collect votes and become leader before the others start campaigning.