Consensus and Raft
Raft lets a small group of servers agree on one list of changes, even when some of them fail. Learn how it works and what it costs.
Updated since you finished it. We changed this lesson after you marked it done. Your progress is kept.
What broke
A payouts service runs on two servers. Only the active one may send money to sellers each night. Every second, it writes "I am alive" to a shared table. If the standby sees no update for 10 seconds, it takes over.
One night the active server freezes for 15 seconds in a long garbage collection pause. The standby takes over and starts sending payouts.
Then the old server wakes up. Nothing tells it that it lost its job, so it carries on. About 300 sellers get paid twice. Each server decided "I am in charge" on its own. This is a split-brain.
This story is made up, but the pattern is common. A better timeout will not fix it. The servers need to agree, by majority, on who is in charge. That is consensus. The old server must also check that it is still in charge before it acts.
It happens for real
GitHub · 21 Oct 2018GitHub outage: a 43-second network cut caused a day of troubleFor about 24 hours, GitHub showed stale or wrong data, and webhooks and Pages builds were delayed. Roblox · 28 Oct 2021Roblox outage: 73 hours down after Consul brokeRoblox was fully down for most of 73 hours, and players came back in steps only on the fourth day. All incidents tagged “database”The idea in simple words
Many systems need one agreed answer: who is the leader now, or which config is current. A consensus algorithm gives it. It lets a group of machines act as one, even if some of them fail. 1 Once the group decides something, the decision is final. 2
The usual shape is a replicated state machine. Each server keeps a log of commands, and every log holds the same commands in the same order. Each server runs them on the same deterministic code, so all end up with the same state. 1
Raft is a consensus algorithm built to be easy to understand. It is equal to Paxos in fault tolerance and speed. 2
The key idea. One leader decides the order. A change counts only when a majority of servers has stored it. Any two majorities share at least one server, so the group can never decide two different things.
How it works
Roles and terms
Each Raft server is in one of three states: leader, follower or candidate. In normal work there is exactly one leader and the others are followers. Followers only answer the leader and candidates. The leader handles all client requests. 1
Raft splits time into numbered Raft terms. Each term starts with an election. If a candidate wins, it is the leader for the rest of that term. There is at most one leader per term. 1
Terms work like a clock that every server can read. Servers send their term in every message. A server that sees a bigger term takes that number, and a leader or candidate goes back to being a follower at once. A request with an old term is rejected. 1 This is how an old leader that wakes up learns that it lost its job.
The basic algorithm needs only two kinds of messages. RequestVote is sent by candidates. AppendEntries is sent by the leader to copy log entries. An AppendEntries with no entries is a heartbeat. 1
Elections
The leader sends heartbeats to every follower. If a follower hears nothing for one election timeout, it assumes there is no leader. It moves to the next term, becomes a candidate, votes for itself, and sends RequestVote to all other servers. 1
A candidate wins if a majority of the full cluster votes for it in that term. Each server votes for at most one candidate per term, first come, first served. So two candidates cannot both win the same term. The winner sends heartbeats at once to stop new elections. 1
What if two followers time out together and split the votes? Nobody wins, and they try again in a new term. To make this rare, Raft picks each election timeout at random from a fixed range. The paper uses 150–300 ms as an example. Usually one server times out first, wins and sends heartbeats before the others time out. 1
Step through an election.
- Server 1 is the leader in term 1. All three logs hold x=1. Then server 1 stops, so its heartbeats stop too.
- Each follower waits a random time. Server 2's election timeout runs out first. It moves to term 2, becomes a candidate and votes for itself.
- Server 2 asks the others for a vote. The request says its term and its last log entry. Server 1 is down and does not answer.
- Server 3 has not voted in term 2, and server 2's log is not behind its own. So it says yes. Two votes out of three is a majority: server 2 is the new leader.
- The new leader sends heartbeats at once, so no one else starts an election. A client writes y=2. It is stored on 2 of 3 servers, so it is committed.
- Server 1 restarts as a follower. It sees term 2 in the leader's message and accepts it. The leader sends the missing entry, and server 1's log catches up.
Now stop the leader yourself and watch a follower take over.
Try it: stop the leader and watch the cluster elect a new one
Copying the log
A client sends a command to the leader. The leader adds it to its log, then sends AppendEntries to all followers at the same time. Each log entry stores the command, its position (the index) and the term in which the leader got it. 1
An entry is committed once the leader that created it has stored it on a majority of servers. Then it is safe to run on the state machines. The leader sends its commit index, the highest committed index, in every AppendEntries, so followers learn which entries they may apply. 1
Each AppendEntries also carries the index and term of the entry just before the new ones. If the follower does not have that exact entry, it refuses. The leader then steps back one entry and tries again, until the two logs match. The follower deletes anything after that point and takes the leader's entries. 1
This check gives the Log Matching rule: if two logs share an entry with the same index and term, they match up to that point. 1
The safety rule
What stops a server with an old log from becoming leader and deleting committed entries? The vote itself. RequestVote includes the candidate's last log index and term. A server refuses to vote for a candidate whose log is less up to date than its own. 1
"More up to date" means a later term on the last entry. If the last terms are equal, the longer log wins. A candidate needs a majority, and every committed entry lives on a majority. So at least one voter has every committed entry, and that voter blocks a candidate that lacks one. 1
A new leader cannot treat an old entry as committed just because a majority holds it. It counts majorities only for entries from its own term. 1
3 servers or 5
A Raft group works while a majority of its servers are up and can talk, so five servers survive any two failures. 1 If more fail, the group stops making progress, but it never gives a wrong answer. 2
| Servers | Majority | Failures you survive |
|---|---|---|
| 3 | 2 | 1 |
| 4 | 3 | 1 |
| 5 | 3 | 2 |
| 7 | 4 | 3 |
A 4th server adds no failure tolerance. 3 4 etcd recommends an odd number of members, and probably no more than seven. 3 Consul recommends 3 or 5 servers. 4
What it costs
In the normal case, a command finishes after one round of messages to a majority. 1 Each of those messages usually waits for a disk write. The paper says this round trip may take 0.5–20 ms, based on the storage. 1 Servers in different data centres make each request slower. 3 More members also make writes slower, because data goes to more machines. 3
When the leader crashes, the group is unavailable for about one election timeout. 1 Reads need care too. A leader that answers from memory may already be replaced, so for fresh reads it first checks with a majority. 1
Our advice: put small, important data in Raft, like leaders, config, locks and metadata. Not every user event.
Where it runs
- etcd is built on Raft. Its leader handles all requests that need consensus. 3
- Consul servers use Raft. The log holds changes like new nodes, registered services and key-value updates. 4
- CockroachDB splits data into ranges. Each range has three or more copies, and they run their own Raft group. 7
- TiKV splits data into Regions. The copies of each Region form a Raft group. 8
- Kafka used to rely on ZooKeeper's consensus protocol. Its replacement, from KIP-595, is "a sort of Raft dialect": Kafka's own log copying plus Raft's leader election. 6 In KRaft mode, a quorum of controllers keeps the metadata. With 3 controllers it survives 1 failure, and with 5 it survives 2. 5
Paxos and FLP, briefly
Paxos, by Leslie Lamport, is the older consensus algorithm. Proposers suggest values and acceptors accept them, in two phases that each need a majority. One run picks one value. For a log, you run one instance per log position, with a leader as the only proposer. 9 Raft gives the same result as this multi-Paxos, but is easier to learn. 1
In 1985, Fischer, Lynch and Paterson studied consensus in an asynchronous system, where messages can take any amount of time. They proved that every protocol for it might never finish, even if only one process is faulty. 10 This is called the FLP result. Because of it, a reliable way to elect a leader must use randomness or real time, such as timeouts. 9 In Raft, safety never depends on timing. Only availability does. 1
Trade-offs
| Option | Lose committed writes? | Cost | Use it when |
|---|---|---|---|
| Single leader + async replication | Yes A primary crash can lose recent commits. 11 | Fast writes. Failover needs a safe way to choose one leader. | Most app databases. It is the Postgres default. 11 |
| Raft group (3 or 5 servers) | No , while a majority survives. 1 | Every write waits for a majority and a disk write. No writes without a majority. | Leaders, config, locks, metadata, and databases built on Raft. |
| Leaderless quorums | No single order. Apps may need to merge conflicting versions. 12 | Any node takes writes. You must design conflict rules. | You need writes to always work, like a shopping cart. 12 |
| External coordination service (etcd, Consul, ZooKeeper) | No , for data stored in it. Your own database is not protected. | One more system to run. Many services may depend on it. | You need leader election or locks but do not want to write Raft yourself. |
Simple rule: do not write your own consensus. Use a tested Raft library or a coordination service.
At work: how a senior uses this
- When a design says "only one worker does X", ask: "Who decides that, and what happens to the old one if it wakes up?" If the answer is a timestamp in a table, you have the payouts bug.
- Run 3 or 5 servers, never 2 or 4. Place them in different failure zones so one outage cannot take a majority.
- Know what Raft protects. At GitHub in 2018, Orchestrator used Raft for its own decisions. After a 43-second network cut, it still failed MySQL primaries over to the US West Coast. Both coasts ended up with writes the other did not have. 13 Consensus in the tool did not make the database safe.
- Watch the blast radius of the coordination cluster. Roblox used one Consul cluster for service discovery, health checks, session locking and key-value data. When it failed, Roblox had a 73-hour outage. 14
- Measure write latency on the Raft group, and alert on leader changes. If the leader changes often, check disk speed and the network first.
With AI
What to ask the agent
"Our cron job runs on 3 pods, and only one may run each night. Show me how to use an etcd lease and election so only the leader runs it. Explain what happens if the leader pauses for 30 seconds."
"Here is our Raft cluster config. List the election timeout and heartbeat interval, and check that the heartbeat is much shorter than the election timeout."
What to check yourself
- The code stops doing leader work as soon as it loses the lease or sees a newer term. It must not finish the batch "just this once".
- The cluster has an odd number of nodes, spread across failure zones.
- Any Raft code comes from a tested library. A "simple Raft" from scratch will miss edge cases, like the rule on older-term entries.
- Reads that must be fresh go through the leader's majority check, not a local read from any member.
- Monitoring and alerts do not depend on the same coordination cluster they watch.
Check yourself
Your progress is saved only in this browser. Export it to keep it safe.
You have finished 5 lessons. Your progress lives only in this browser. Export a copy so you don’t lose it.
Go deeper
Show 14 sources and related lessons
- Diego Ongaro and John Ousterhout, “In Search of an Understandable Consensus Algorithm (Extended Version)”, 2014 (USENIX ATC 2014) (opens in a new tab)
The Raft paper. Section 2 explains replicated state machines, section 5 the whole algorithm, and Figure 2 fits it on one page. - The Raft Consensus Algorithm (raft.github.io) (opens in a new tab)
A short intro to consensus and Raft, with a visual demo you can click through. - etcd documentation (v3.5): Frequently Asked Questions (opens in a new tab)
The cluster size and failure tolerance table, and why an odd number of members is best. - HashiCorp Consul documentation: Consensus protocol (opens in a new tab)
How Consul servers use Raft, what goes in the log, and a deployment table of servers, quorum size and failure tolerance. - Apache Kafka documentation (4.1): Operations, KRaft (opens in a new tab)
How Kafka controllers form a metadata quorum, and why you run 3 or 5 of them. - Apache Kafka, KIP-595: A Raft Protocol for the Metadata Quorum (opens in a new tab)
Kafka's design for a self-managed metadata quorum to replace ZooKeeper. It calls its protocol "a sort of Raft dialect". - CockroachDB design document (GitHub, cockroachdb/cockroach, docs/design.md) (opens in a new tab)
See "Raft - Consistency of Range Replicas". Each range of keys is its own Raft group. - TiKV README (GitHub, tikv/tikv) (opens in a new tab)
TiKV splits data into Regions, and the copies of each Region form a Raft group. - Leslie Lamport, “Paxos Made Simple”, 2001 (opens in a new tab)
Paxos in plain words. Section 3 shows how to build a replicated state machine on top of it. - Michael J. Fischer, Nancy A. Lynch and Michael S. Paterson, “Impossibility of Distributed Consensus with One Faulty Process”, Journal of the ACM 32(2), 1985 (opens in a new tab)
The FLP result. The abstract states the main claim in two sentences. - PostgreSQL documentation: Log-Shipping Standby Servers (opens in a new tab)
Streaming replication is asynchronous by default, so a primary crash can lose committed transactions. - Werner Vogels, “Amazon's Dynamo” (2007), with the SOSP paper (opens in a new tab)
A leaderless, "always writeable" store. Shows R + W > N quorums and how apps merge conflicting versions. - GitHub, “October 21 post-incident analysis” (opens in a new tab)
Orchestrator, a failover tool built on Raft, moved the MySQL primaries across the US after a 43-second network cut. - Roblox, “Roblox Return to Service 10/28-10/31 2021” (opens in a new tab)
How Roblox runs Consul (5 voters, Raft), and how a 73-hour outage followed when it failed.
Real incident: GitHub, 21 Oct 2018: GitHub outage: a 43-second network cut caused a day of trouble
Real incident: Roblox, 28 Oct 2021: Roblox outage: 73 hours down after Consul broke
Related: Leader election and leases · Replication · Quorums and leaderless replication · Coordination services: ZooKeeper and etcd · CAP, PACELC and consistency models
Before this: database replication, failure detection and membership and leader election and leases. Next: ZooKeeper, etcd and coordination, and CAP and consistency models.