Skip to main content

Concepts

Leader election and consensus

Intuition

Picture a group project where everyone can propose changes to a shared document at the same time — chaos, since two people might edit the same line differently at once. The fix is to agree on one person as the editor: everyone sends their proposed changes to that person, who applies them in order, and if that person disappears, the group quickly and clearly agrees on a replacement before work continues. Distributed systems face the same problem with data instead of a document, and need the same kind of agreement on exactly one leader at a time.

How it works

Raft elects a single leader per cluster, who is exclusively responsible for accepting client commands and replicating them to followers. Time is divided into terms — increasing integers acting as a logical clock — where each term has at most one leader, and comparing term numbers lets servers detect stale information, like an old leader that doesn't yet know it has been replaced. Election is triggered by a randomized timeout: if a follower hears nothing from a leader within that window, it becomes a candidate, increments its term, and requests votes from every other server via the RequestVote RPC; whichever candidate first collects votes from a majority of the cluster becomes leader for that term and starts sending heartbeats (empty AppendEntries RPCs) to suppress further elections. The randomization of the timeout (Raft suggests 150-300ms) is specifically there to make split votes — where multiple candidates start elections simultaneously in the same term and no one gets a majority — rare and self-correcting: if a split vote does happen, each candidate's timeout will expire again at a different random moment, and a new term's election runs until one candidate secures a majority. Only one leader can be elected per term because a server casts at most one vote per term, which is what makes "first to a majority" a safe, non-ambiguous rule.

In practice

This is the mechanism that lets etcd, Consul, CockroachDB, and TiKV agree on a single writer for their replicated state without a human or external coordinator involved. You'd choose leader-based consensus like this whenever you need a cluster to keep working correctly through server crashes and network hiccups while still guaranteeing every surviving replica agrees on the same sequence of operations — the trade-off is a brief unavailability window during an election, in exchange for strong consistency the rest of the time.

Use it in a design

Practice the cases that rely on this concept in the System Design school.