If you run Kubernetes, CockroachDB or TiDB, there is a small algorithm deep inside keeping your data consistent: Raft. The etcd Raft library alone powers etcd, Kubernetes, Docker Swarm, CockroachDB, TiDB “and more” 1.
Its job is to make a group of servers behave like one server that doesn’t go down. In this article, let’s see how it does that, with a little cluster you can crash yourself.
Problem
Keep your data on one server and you are down when it dies. So you keep copies on several servers. Now they have to agree.
Say client A sends x = 1 to one server, and at the same moment client B sends x = 2 to another. If one server applies 1 then 2, and the other applies 2 then 1, they end up with different values. Which one is right?
The standard answer is a replicated log 2. Every server keeps a log of commands and applies them in order. If every log has the same commands in the same order, every server ends up in the same state. Keeping that log the same everywhere is the job of a consensus algorithm.
And it has to do that while things go wrong: servers crash and come back, messages get delayed, lost or reordered. The Raft paper asks for two things 2:
- Never return a wrong result, no matter how slow or broken the network is.
- Keep working as long as more than half of the servers are up. “A typical cluster of five servers can tolerate the failure of any two servers.”
Raft was designed at Stanford by Diego Ongaro and John Ousterhout to be easier to understand than Paxos, the classic answer to this problem. In their user study, 33 of 43 students answered questions about Raft better than questions about Paxos 2.
Why a majority
Raft never acts on one server’s word. To elect a leader or to save a write, it needs a yes from a majority: more than half of the servers. With 5 servers, that’s any 3 of them.
Why more than half? Because two groups that are each more than half always have a server in common. Say a write was saved on S1, S2 and S3. Later, S3, S4 and S5 vote in a new leader. Both groups are majorities, and S3 is in both. Try to pick two groups of 3 out of 5 with nobody in common: you can’t, since 3 + 3 = 6 and there are only 5 servers.
Here are two random majorities, drawn as circles. The servers where the circles overlap are in both:
That shared server is the cluster’s memory. Whatever the first group agreed on, the second group has someone who knows about it. You’ll see this idea show up twice below.
One leader at a time
Raft keeps things simple by having one leader. It takes all the writes and tells everyone else what to append. The others are followers. Log entries only flow one way, from the leader to the followers 2.
Time is split into terms, numbered 1, 2, 3, and so on. Each term starts with an election, and there is at most one leader per term 2. Every message carries the sender’s term. If a server sees a higher term than its own, it updates its term and goes back to being a follower. That’s how an old leader that was cut off finds out it has been replaced.
So how does an election work 2?
- The leader sends heartbeats regularly (an empty AppendEntries message).
- Every follower has an election timeout. If it hears nothing from a leader for that long, it assumes the leader is dead.
- It adds 1 to its term, becomes a candidate, votes for itself and sends RequestVote to every other server.
- Each server votes for at most one candidate per term, first come first served. A candidate with votes from a majority becomes the leader.
What if two followers time out at the same moment and split the votes? Then nobody wins, they both time out again and retry. To make that rare, each server picks its timeout at random from a range, e.g., 150 to 300 ms 2. Almost always one server times out first and wins before the others wake up.
Here is a live cluster. The ring around each server is its election timer. Crash the leader and watch who takes over:
Now crash three servers. The two that are left can keep voting forever, but 2 votes out of 5 is never a majority, so no leader is elected. That’s the price of never being wrong: with too few servers, the cluster stops instead.
Replicating the log
Once there is a leader, a write goes like this 2:
- The leader appends the command to its own log, tagged with the current term.
- It sends the entry to the followers in AppendEntries.
- Once the entry is stored on a majority of servers, it’s committed: safe to apply. The leader applies it and answers the client.
- The leader puts its commit index in every later message, so the followers learn about it and apply the entry too.
What if a follower missed some entries, or has extra ones from a dead leader? Every AppendEntries carries the index and term of the entry just before the new ones. If the follower doesn’t have exactly that entry, it refuses. The leader then steps back one entry and tries again, until they find a point where both logs agree. The follower drops everything after that point and takes the leader’s entries 2.
Because of this check, if two logs have an entry with the same index and term, they are identical up to that entry. The paper calls it the Log Matching Property 2.
Try it. Write a few entries, crash a follower, write more, then restart it and watch it catch up. Each cell is the term of an entry, and dashed cells aren’t committed yet:
Notice that writes still commit with one or two followers down. Three servers out of five is enough.
Who can be leader
There is still a hole. The paper gives the example 2: a follower is down while the leader commits a few entries. Then it comes back, the leader dies, and this follower times out first. If it wins, it would overwrite entries the cluster already promised to clients.
Raft fixes this with one rule on voting: a server refuses to vote for a candidate whose log is behind its own. To compare two logs, look at their last entries. The one with the later term is ahead. If the terms are equal, the longer log is ahead 2.
Why is that enough? Back to the overlap. A committed entry is on a majority of servers. A winner needs votes from a majority. Those two majorities share at least one server, and that server has the entry, so it won’t vote for a candidate without it. So every new leader already has every committed entry. Nice!
You can see the refusal in the simulator above. Crash a follower, write a few entries, crash the leader, then restart the follower. If the stale follower times out first, the others turn it down.
The tricky one: Figure 8
Even with that rule, there is one more trap. “Committed once it’s on a majority” is only true for entries from the leader’s current term. An entry from an older term can sit on a majority and still get overwritten.
This is Figure 8 from the paper 2. Step through it, and watch the entry at index 2:
So Raft adds one more rule: “Raft never commits log entries from previous terms by counting replicas” 2. A leader only counts copies of entries from its own term. When one of those is committed, every entry before it is committed along with it.
Final Thoughts
Raft isn’t free. A few limits worth knowing:
- Every write goes through one server, so the leader is the bottleneck.
- When the leader dies, the cluster can’t take writes until a new one is elected. The paper says it is “unavailable for roughly the election timeout” 2.
- Correctness doesn’t depend on timing, but staying available does. The paper asks for broadcastTime ≪ electionTimeout ≪ MTBF, i.e., a message round much shorter than the election timeout, which is much shorter than the time between server failures. With broadcast times of 0.5 to 20 ms, that puts the election timeout somewhere between 10 and 500 ms 2.
- This post skipped two parts a real system needs: changing the set of servers safely, and compacting the log with snapshots. Both are in the paper (sections 6 and 7).
But the core is small: one leader per term, a vote rule, and majorities that always overlap. The paper’s whole summary of it fits in a single figure 2.
Footnotes
-
etcd, etcd-io/raft README. ↩
-
Diego Ongaro and John Ousterhout, In Search of an Understandable Consensus Algorithm (Extended Version). User study in the abstract; replicated state machines in section 2; terms and roles in 5.1; elections and randomized timeouts in 5.2; log replication and Log Matching in 5.3; the stale-follower example and election restriction in 5.4 and 5.4.1; Figure 8 and the commit rule in 5.4.2; timing in 5.6; the summary in Figure 2. ↩ ↩2 ↩3 ↩4 ↩5 ↩6 ↩7 ↩8 ↩9 ↩10 ↩11 ↩12 ↩13 ↩14 ↩15 ↩16 ↩17