Systemsfor Aravinda
0 / 78 core
Week 4 · Distributed systems

Consensus and Raft

3 hours · core path

Read first: Replication, Consistency models

In one sitting

Raft keeps one log by electing a single leader per term and committing an entry only after a majority has stored it. Any two majorities overlap, so two leaders cannot both commit conflicting entries. The protocol agrees on an order and does not shorten the round trip to the farthest voter.

Consensus is the problem of getting a set of replicas to agree on one sequence of commands, so a crash cannot fork that sequence into two histories. You need it for a lock, for membership, and for the log that makes a single leader safe. Raft is the version you should be able to walk.

Core concepts

A Raft cluster is usually an odd count of servers, so one node does not sit on the fence of a tie, and it has three roles. A follower accepts what a leader sends. A candidate is a follower that has started an election. A leader is the only server that appends new entries. Clients send commands to the leader. The state machine, which is yours, is whatever the commands mean: a lock table, a configuration, a key-value map. Raft’s job is the log. The meaning of the log is the state machine you apply it to.

Replication without this protocol is how you get two primaries. A lease with a fencing token, or a Raft term, is a real answer for who is allowed to write. The bully algorithm is a poor answer. Clocks alone are a poor answer. A timeout can start an election. It must not be the proof that lets two servers both believe they committed.

Terms

Every server stores a term, a monotonically increasing integer. Terms order the elections. A server that hears a higher term adopts it and steps down if it was leader or candidate. A candidate increments the term when it starts an election. A server votes for at most one candidate in a given term. Because a win requires a majority of votes, and two majorities of the same set of servers always share a server, two candidates in one term cannot both win. There is at most one leader per term.

An election

Followers expect heartbeats from the leader. A heartbeat is an ordinary message that carries the leader’s term and resets the follower’s election timer. If the timer fires, the follower has not heard a current leader. It becomes a candidate, bumps the term, votes for itself, and asks the others for votes.

The timers are randomized. If two followers timed out together, each would vote for itself and a split vote would leave the term with no leader. Randomization makes that unlikely to repeat: the next timers fire at different moments, one candidate starts first, and it collects a majority before the others campaign. Safety does not depend on the timer length. A timer that is shorter than a round trip only causes extra elections. Liveness depends on a majority being up and on a timeout that is longer than a typical round trip.

A voter refuses a candidate whose log is behind its own. “Behind” is concrete. Compare the term of the last log entry. The higher term is more up to date. If the terms match, the longer log is more up to date. This rule is why the winner already contains every committed entry. That property is leader completeness.

A commit

The leader appends the command locally and sends it to the followers, along with the index and term of the previous entry. A follower that has the same previous index and term appends the new entry. A follower that does not rejects the request. The leader then walks backward and overwrites the follower’s conflicting suffix. Log matching is the invariant this buys: if two logs have an entry with the same index and the same term, the prefixes of those logs are identical. They agreed at that point, and by the same check they agreed at every earlier point.

An entry is committed when a majority has stored it. The leader applies the committed prefix to its state machine and answers the client. Followers learn the commit index from a later heartbeat and apply then. Storing an entry on one follower is not a commit. Applying it early is how a follower acts on a command that a future leader is allowed to throw away.

A leader commits an entry from its own term once a majority has stored that entry. Log matching then commits the prefix in front of it. An entry inherited from an older term is not committed by a count of copies alone. That extra condition is what stops a later leader from discarding a command you already told the client had succeeded. You do not need the famous diagram to use the rule. You need the rule to walk a commit honestly.

Why two leaders cannot both commit

Suppose an old leader and a new leader are both alive, and each tries to commit a different command at the same index.

The new leader won an election, so a majority voted for it in its term. The old leader can commit only by getting a majority to store its entry. Any two majorities intersect in at least one server. The server in the intersection has seen the new term, or has stored the entry the new leader is built on, and it will reject the old term. The old leader cannot assemble a majority that still accepts it.

Run it from the other direction. A committed entry already sits on some majority. The next election’s majority overlaps that one, and the vote rule refuses a candidate who is missing that entry. Leader completeness says the new leader’s log contains every committed entry. It will replicate that entry, not a conflicting one, at that index.

Two majorities cannot exist at the same time in one configuration. That single fact is the whole safety argument you need on a board. You do not get two leaders that both commit.

The same problem, under the other name

Paxos is the same consensus problem, and it is a family of protocols. Synod decides one value. Multi-Paxos repeats the idea for a log. It is harder to learn. Raft was written so more people could implement this class of system without getting the safety wrong. A paragraph that lists message names is not a specification, and this page will not pretend to be one. Say what problem Paxos solves. Walk Raft when someone asks for the mechanism.

etcd and Consul use Raft. The original Spanner paper uses Paxos, not Raft. Each group of replicas in that design runs Paxos, and a transaction that touches several groups adds two-phase commit on top of the Paxos leaders. That is a Spanner fact, not a reason to describe Paxos message by message.

What Raft does not do

Raft does not make a cross-region system fast. A commit waits for the voter that completes the majority. If that voter is 4,000 km of fiber away, the floor is about 40 ms before routers, and a California-to-Netherlands pair is about 150 ms. Agreement is the product. Speed is not. A multi-region design that puts a Raft majority across oceans has chosen that bill on every write.

Raft also does not shard your keys, pick your query language, or make a retried client command exactly once. If the leader commits and then loses the response, the client retries. Unless the command is idempotent, the log can contain it twice. The protocol gave you one order. It did not give you one click.

A worked example

Three servers, S1, S2, and S3, in one datacenter. You are walking a seat sale: the command is “seat 14 is sold.” Assumptions, labeled as assumptions:

  • Dean’s same-datacenter round trip, 0.5 ms, is the network cost of one heartbeat or one append.
  • Election timeouts are drawn at random between 100 ms and 200 ms. That is an assumption for the walk, not a number from a vendor. A hundred milliseconds is 100 / 0.5 = 200 local round trips, so one dropped heartbeat is not an election.
  • A majority of 3 is 2. The cluster survives one fault and loses the ability to commit on the second.
N = 3
majority = 2
faults survived = 1

same-datacenter RTT = 0.5 ms
assumed timeout range = 100 ms to 200 ms
100 / 0.5 = 200 local round trips

commit of an entry stored on S1 and S2
  waits about one 0.5 ms RTT
  does not wait for S3

Start with S1 as leader of term 1. It heartbeats. The client sends “seat 14 is sold.” S1 appends it and reaches S2. S3’s reply has not arrived. Two copies is a majority, so the entry is committed. S1 applies it and tells the client the seat is sold. The network piece of that wait was about half a millisecond. S3 is behind and the sale is still committed. You do not need the slow server to sell the seat.

Then S1 becomes unreachable. S2’s timer, drawn at 110 ms, fires before S3’s timer, drawn at 190 ms. The randomization is the reason those numbers differ. S2 becomes a candidate, moves to term 2, votes for itself, and asks S3.

S2’s last entry is the seat sale at term 1. S3 does not have it. S2’s log is more up to date, so S3 grants the vote. S2 has two votes and becomes leader of term 2. Leader completeness is visible here: the committed sale is already on S2. S2 will fill S3’s hole. It will not sell seat 14 a second time under a different command at that index.

Watch the election S3 must not win. S3’s log is missing a committed entry. S2 will refuse S3’s vote request, because S3 is behind. S1 is unreachable. S3 cannot build a majority. The server that is missing the sale cannot become leader. That is the vote rule earning its keep.

Now S1 comes back, still believing it is leader of term 1, and tries to commit “seat 14 is sold” to a different customer, or any other command at the next index. S2 and S3 are in term 2. They reject term 1. The only majorities are S1+S2, S1+S3, and S2+S3. Every one of them includes S2 or S3. S1 cannot commit. It hears term 2 and becomes a follower. Two leaders were briefly alive in the sense that S1 had not noticed yet. Only one of them could commit.

flowchart TB
  timeout[Election timeout fires]
  cand[Candidate bumps the term]
  votes[A majority grants votes]
  lead[Leader appends the entry]
  stored[A majority stores the entry]
  commit[Entry is committed]
  timeout --> cand
  cand --> votes
  votes --> lead
  lead --> stored
  stored --> commit

Stretch the same three servers across regions and the arithmetic changes. The protocol steps do not.

4,000 km fiber
one way = 20 ms
round-trip floor = 40 ms before routers
assumed planning RTT = 60 ms

a commit whose second ack crosses that path waits about 60 ms
60 / 0.5 = 120 times the in-building commit

California to the Netherlands, about 150 ms RTT
if that pair is the second ack, the commit waits about 150 ms

assumed election timeout of 150 ms across a 60 ms RTT
150 / 60 = 2.5 round trips
one delayed heartbeat can start a needless election
a calmer timeout is several RTTs, and the commit is still one RTT

Five servers is the same story with a bigger majority. A majority of 5 is 3, so you survive two faults. The commit returns when the third store finishes, not when the fourth and fifth do. Those two can be down. If the third ack is the far region, you still pay the far round trip. Adding servers adds fault tolerance. It does not cancel fiber.

Tradeoffs

Choice What you gain What you spend
3 servers Survives one fault, simple to operate A second fault stops commits
5 servers Survives two faults More nodes, and the commit waits for a third ack
All voters in one building Commits near a 0.5 ms round trip One site is a shared fate
A voter on another continent The cluster survives a site loss Every commit pays that round trip, tens or hundreds of milliseconds
Leader serves reads under a lease Reads skip a quorum round trip A lease that outlives the leader is a split brain unless you fence it
Paxos family for the same log The same class of agreement Harder to implement safely; Raft is the walkable one

Waiting for every server, rather than a majority, feels stricter and then stops the cluster because one disk is slow. The majority is the strictness that still makes progress. The strictness beyond it is availability you threw away.

Pitfalls

  • Electing a leader with the bully algorithm, or with “whoever has the highest clock wins,” and calling it consensus.
  • Letting the old leader keep accepting writes after a new term has started. The term is the fence. Without it you have two primaries.
  • Treating “stored on the leader” as “committed.” One copy is not a majority. A crash of that leader drops the command, or a new leader overwrites it.
  • Applying a stored entry on a follower before it is committed. A later leader is allowed to delete an uncommitted suffix.
  • Changing members by rewriting the server list in one step. That is how two majorities appear.
  • Setting an election timeout of a couple of round trips across a 60 ms link, then debugging a flap that is the timeout.
  • Promising a sub-millisecond cross-region write because “Raft is fast in the local benchmark.”
  • Forgetting that a retried client command can be appended twice after a lost success response.

In the interview

Walk three nodes in the first five minutes. One leader, one committed entry stored on two servers, the leader dies, the follower whose log contains the entry times out first because the timers are random, it wins the next term, and the old leader cannot commit because every majority intersects the new one. The number is the commit wait: half a millisecond in the building, about 40 ms of fiber if a voter is 4,000 km away. The bottleneck is that farthest voter. The tradeoff is fault tolerance against that round trip.

Skip a Paxos proof. You are not being graded on one. Name Paxos as the same problem and Raft as the protocol you can implement from carefully. Skip membership changes unless they ask how you add a server. If they ask, the failure is two majorities that need not overlap, and the repair is the staff-level note above rather than a cutover you invent on the board.

The question that usually follows is the cross-region one. “What is the commit latency if one voter is in another region?” Answer with the fiber floor, and say that Raft has not made that number smaller.

Check yourself

Three followers time out. Why does randomizing the election timeout matter?

A server whose timer fires becomes a candidate, increments the term, and votes for itself. If two candidates start together they can split the vote and finish the term with no leader. Different timeouts make one candidate start first and collect a majority before the others campaign. If a split happens anyway, the next round of timers is random too. Safety holds either way. The randomness is there so elections end.

When is a log entry committed, and when does a follower apply it?

A leader commits an entry from its current term once a majority has stored it. Log matching then treats the prefix as committed too. An entry from an older term is not committed just because several servers happen to hold it. A follower applies an entry after it learns the entry is committed, not at the moment it first stores the bytes. The client hears success only after the commit.

Why can an old leader and a new leader not both commit conflicting entries?

A commit needs a majority, and any two majorities share a server. The new leader already collected a majority in its term, so the old leader cannot find a majority that still accepts the old term. From the other side, a committed entry is already on a majority, the next election overlaps that majority, and the vote rule withholds votes from a candidate whose log is missing the entry. The new leader therefore contains every committed entry and will not commit a different value at that index.

A Raft voter sits 4,000 km from the leader. What does a commit wait, and what does Raft not fix?

Fiber is about 200 km per millisecond, so the one-way floor is 20 ms and the round trip is about 40 ms before routers. If that voter is the one that completes the majority, the commit waits on that round trip. A planning figure in the tens of milliseconds is honest. Raft agreed on the entry. It did not shorten the path. A pair from California to the Netherlands is about 150 ms if that is the ack you need.

Someone proposes the bully algorithm, or the highest clock, to pick a primary. What do you say?

Neither is consensus. The bully algorithm has no overlapping-majority argument, and a clock cannot tell a slow peer from a dead one. Use a Raft term, or a lease that carries a fencing token, so the old primary cannot keep writing after the new one is chosen. A timeout may start the election. The term is what makes the winner exclusive.

Based on: Raft, Ongaro and Ousterhout; Paxos; Spanner, OSDI 2012, Corbett and others; Designing Data-Intensive Applications, Kleppmann and Riccomini.