Sub topic 1
Leader Election and Consensus with Raft
Prerequisites
This chapter assumes you understand nodes, remote procedure calls (RPCs), network partitions, and append-only logs. You should also be comfortable reading short Python functions.
Why consensus: replicated state machines
A replicated state machine runs the same commands on several servers. Each server keeps a log of commands and applies them in the same order. Replication lets the service continue when one server fails, but only if all healthy servers agree on that order.
Consensus is the process of reaching that agreement despite delayed, lost, or duplicated messages. Raft separates consensus into leader election, log replication, and safety rules. A leader proposes the next log entry, while followers check and store the proposal.
Crashes, partitions, and majority quorums
A crash stops a server. A network partition prevents groups of servers from communicating, even though the servers may still be running. Raft uses a majority quorum: more than half of the cluster.
In a three-server cluster, two servers form a majority. In a five-server cluster, three are required. Two majorities always overlap in at least one server, so two different decisions cannot both be confirmed safely.
| Cluster size | Majority | Failures tolerated |
|---|---|---|
| 3 | 2 | 1 |
| 5 | 3 | 2 |
Followers, candidates, leaders, and terms
A follower accepts messages from a leader. If it hears nothing for its election timeout, it becomes a candidate and starts a new term. A term is a monotonically increasing election period. A candidate requests votes, and a leader sends heartbeats and log entries.
A server grants at most one vote in a term. A server that sees a higher term updates its term and becomes a follower. These rules prevent two leaders from being valid in the same term.
Electing a leader with RequestVote
A candidate includes its term and the last entry in its log in a RequestVote RPC. A follower votes only once per term and only for a candidate whose log is at least as current as its own. The candidate becomes leader after receiving votes from a majority.
Randomized election timeouts make simultaneous candidacies less likely.
import random
def new_election_timeout():
return random.uniform(0.150, 0.300)Exercise
Why can a minority partition not safely commit an entry in a three-server cluster?
Show answer
It has at most one server, but committing requires confirmation from two servers.