Databases and storage

Consensus: Raft and Paxos

How a group of machines agrees on one value despite crashes and an unreliable network, how Raft and Paxos do it, and what that agreement costs.

Lesson16 min read
Video walkthrough: not recorded yet. The lesson below is complete without it.

The problem

Replication with a single leader raises a question it cannot answer by itself: when the leader stops responding, who decides which follower takes over? If each follower decides for itself, two of them can promote themselves at once. If a separate monitor decides, the monitor is a single point of failure, and two monitors can disagree. Worse, no node can tell a crashed leader from one that is slow or cut off, because in every case the messages just stop.

Getting this wrong produces split brain, with two leaders accepting conflicting writes. Engineers tried manual failover, which is safe but needs a person to be awake, and assorted timeout schemes that worked until the network misbehaved in a new way.

What is needed is a way for a group of machines to agree on one value, such as “node B is the leader for epoch 7” or “the next entry in the log is X”, so that the agreement holds even if some machines crash and messages are delayed, lost or reordered. This is the consensus problem. Leslie Lamport’s Paxos algorithm, published in 1998, became the first widely used solution. Raft, published by Diego Ongaro and John Ousterhout in 2014, solves the same problem and was designed to be easier to understand and to implement.

What consensus promises

A consensus algorithm has to provide two kinds of property:

  • Safety. No two nodes ever decide different values, and a decided value never changes.
  • Liveness. If enough nodes are up and can talk to each other, a decision is eventually reached.

The FLP result (Fischer, Lynch and Paterson, 1985) proves that when message delays have no upper bound, no deterministic algorithm can guarantee both if even one node may crash. Practical algorithms respond by never giving up safety and by making progress whenever the network behaves well for long enough.

Raft and Paxos assume that nodes fail by stopping, not by lying. Tolerating malicious nodes needs a different family of protocols.

Why a majority

Every decision in Raft and Paxos needs agreement from a majority of the cluster. The reason is one fact: any two majorities of the same group share at least one member. So two conflicting decisions cannot both be approved, and a new leader that gathers a majority must reach at least one node that knows about every earlier decision.

A cluster of 2f + 1 nodes therefore survives f failures. Three nodes survive one and five survive two. Four nodes also survive only one, since a majority of four is three, which is why clusters have odd sizes. In a network partition the side with a majority keeps working and the other side stops. Stopping is the point. It is what prevents split brain, and it puts these systems on the consistency side of the CAP trade-off.

Raft

Raft maintains a replicated log. Every node applies the same commands in the same order to its own copy of the state, so all copies end up identical. Consensus is used to agree on the log.

Terms and roles

Time is divided into numbered terms. Each node is a follower, a candidate or a leader, and a term has at most one leader. Every message carries the sender’s term. A node that sees a higher term adopts it and becomes a follower. A node that receives a message from a lower term rejects it. This is how a deposed leader finds out, and why its late messages do no harm.

Leader election

The leader sends heartbeats. Each follower runs an election timer of randomised length (the Raft paper suggests 150 to 300 ms). If the timer expires with no heartbeat, the follower becomes a candidate: it increments the term, votes for itself and asks the others for their votes.

A node grants at most one vote per term, and only to a candidate whose log is at least as up to date as its own. A candidate that collects votes from a majority becomes leader. If the vote splits, the timers expire again and a new term starts. The random timeouts make repeated splits unlikely.

Raft leader election

Open full screen
AFollowerterm 0BFollowerterm 0CFollowerterm 0DFollowerterm 0EFollowerterm 0

Break things

Leader
none
Term
0
Votes to win
3 of 5
Clock
0 ms

Press Start. The amber ring around each follower is its election timeout, reset by every heartbeat from the leader. Crash the leader and watch the first follower to time out ask for votes. Crash three nodes and nobody can reach a majority.

Simplified for clarity: messages arrive instantly and logs are left out. Real Raft also refuses to vote for a candidate whose log is behind the voter's.

What just happened

Press Start to begin the first election.

    Crash the leader and watch a new term begin, then partition the cluster so that the leader is in the minority and see which side can still elect one.

    Log replication and the commit rule

    Clients send commands to the leader. The leader appends each command to its log and sends it to the followers. Each message includes the index and term of the preceding entry, and a follower refuses the new entry unless its own log matches at that point. After a refusal the leader steps back and resends earlier entries, overwriting whatever the follower holds that conflicts. A leader never overwrites its own log.

    An entry is committed once the leader has stored it on a majority of nodes. Only then does the leader apply it and reply to the client. Followers learn the commit position from later messages.

    Raft log replication, commit and a leader crash4 components: Client, Server S1, Server S2, Server S3. Connections: Client to Server S1 (commands); Server S1 to Server S2 (append entries); Server S1 to Server S3 (append entries); Server S2 and Server S3 (vote requests).ClientServer S1leader, term 3, log 1-4Server S2follower, log 1-4Server S3follower, log 1-4commandsappend entriesappend entriesvote requests

    Step 1 of 9

    Three servers form a Raft cluster. S1 is the leader for term 3, and all three logs are identical up to index 4. The leader sends regular heartbeats so that the followers do not start an election.

    Read the steps as text
    1. Three servers form a Raft cluster. S1 is the leader for term 3, and all three logs are identical up to index 4. The leader sends regular heartbeats so that the followers do not start an election.
    2. A client sends the command set x to 5. The leader appends it to its own log at index 5, stamped with term 3. The entry is not committed yet, and the client has not been answered.
    3. The leader sends the entry to both followers. Each message also carries the index and term of the entry before it, so a follower can refuse the new entry if its own log does not match at that point.
    4. S2 appends the entry and acknowledges. The message to S3 is lost. The leader will keep retrying S3, but it does not need to wait for it.
    5. The entry is now stored on two of the three servers, which is a majority. The leader marks index 5 as committed, applies it to its state machine and replies to the client.
    6. Now the leader crashes, before S3 has received entry 5. The client has been told the write succeeded, and S2 is the only running server that holds it.
    7. The election timer on S3 fires first. S3 starts term 4 and asks S2 for its vote. S2 refuses, because the log on S3 is shorter than its own. S3 has only its own vote, which is not a majority, so it cannot win.
    8. S2 times out next, starts term 5 and asks S3 for its vote. The log on S2 is at least as up to date as the log on S3, so S3 says yes. With its own vote S2 has two of three, and becomes leader.
    9. S2 sends entry 5 to S3 and the logs converge. The write survived because a commit needs a majority and so does an election, and any two majorities share a server that holds the entry.
    Raft log replication, commit and a leader crash

    Why it is safe

    Two rules combine. A commit needs a majority to store the entry. An election needs a majority to vote, and each voter refuses candidates whose logs are behind its own. Since any two majorities overlap, every winning candidate already holds every committed entry, and a committed entry is never lost while a majority of nodes keep their data.

    One subtlety is worth knowing for follow-up questions. A new leader does not commit entries left over from earlier terms by counting replicas. It commits an entry from its own term, usually an empty one written on election, and that commits everything before it.

    Reads need care too. A leader that has been cut off may not know it has been replaced, so answering a read from local state could return stale data. Implementations confirm leadership with a round of heartbeats before answering, or rely on a time-bounded lease.

    Paxos in brief

    Basic Paxos agrees on a single value in two phases.

    1. Prepare and promise. A proposer picks a proposal number n, higher than any it has seen, and sends prepare(n) to the acceptors. An acceptor that has not promised a higher number promises to ignore anything lower, and reports the highest-numbered proposal it has already accepted, if any.
    2. Accept and accepted. With promises from a majority, the proposer sends accept(n, v). If any promise reported an accepted value, v must be the one with the highest number. Only otherwise may the proposer use its own value. An acceptor accepts unless it has since promised a higher number. A value accepted by a majority is chosen.

    The rule in phase two, adopting a value that may already have been chosen, is what stops a later proposer from overturning an earlier decision.

    A real system needs a sequence of decisions, one per log position. Multi-Paxos elects a stable leader that runs the prepare phase once and then needs only the accept phase for each new entry. At that point it looks much like Raft. The practical difference is that Raft specifies elections, log repair and membership changes in full, while Paxos leaves much of that to the implementer.

    Where it is used and what it costs

    You rarely implement consensus. You use something built on it:

    • etcd (Raft) holds the cluster state for Kubernetes. Consul uses Raft too.
    • ZooKeeper uses Zab, a closely related leader-based protocol. Kafka depended on ZooKeeper for years before moving to KRaft, its own Raft-based mode.
    • Spanner (Paxos), CockroachDB and TiKV (Raft) run one consensus group per shard of data.

    Typical jobs are leader election, distributed locks, configuration, and the metadata that says which node owns which shard.

    The costs:

    • Latency. Every write waits for a majority to write it to disk, so it costs at least one network round trip plus a disk flush. Across regions that is tens of milliseconds or more.
    • Throughput. All writes pass through one leader. Adding nodes makes the majority larger and writes slower, not faster. Clusters of three or five are normal.
    • Availability. Without a majority the cluster accepts no writes at all.

    Choose consensus for small, critical state where a wrong answer is worse than no answer: who the leader is, who holds the lock, what the configuration says. Do not choose it for high-volume data where eventual consistency is acceptable, and do not put bulk user data in a single consensus group. Databases that need both split the data into many small groups.

    In the interview

    Consensus usually enters a design in one sentence: “leader election and shard metadata live in etcd, a three or five node Raft cluster”. Be ready to defend that sentence. Explain that a majority is required because two majorities always overlap, which rules out split brain, and that the minority side of a partition stops. Sketch Raft in three steps: terms and randomised elections, a log replicated by the leader, and commit on a majority. Then give the cost: a majority round trip on every write, one leader, and no writes without a quorum, which is why it holds metadata and not the bulk of the data.

    Key takeaways

    • Consensus lets a group of nodes agree on a value, or a log of values, so that the agreement survives crashes and lost messages.
    • Every decision needs a majority, because any two majorities share a node. 2f + 1 nodes tolerate f failures.
    • Raft has one leader per numbered term. The leader replicates a log, and an entry is committed once a majority has stored it.
    • A candidate wins only with a majority of votes, and voters refuse candidates whose logs are behind, so a new leader always holds every committed entry.
    • Paxos reaches the same guarantee with prepare/promise and accept/accepted. Multi-Paxos with a stable leader behaves much like Raft.
    • Consensus costs a majority round trip and a disk flush per write, funnels writes through one leader and stops without a majority. Use it for small, critical state.

    Try it

    Check yourself

    1. A five-node Raft cluster is split by a network partition into a group of three and a group of two. What happens?
    2. Why is a four-node cluster no more fault tolerant than a three-node one?
    3. In Raft, a follower whose log is missing a committed entry times out and asks for votes. Why can it not become leader?
    4. In basic Paxos a proposer collects promises from a majority, and one acceptor reports that it has already accepted a value. What must the proposer do?
    5. A team wants to keep 2 TB of user events in one five-node etcd cluster because it is strongly consistent. What is the main objection?

    0 of 5 answered

    Flashcards

    These 6 cards are in your review deck. Tap a card to see the answer.

    Why do Raft and Paxos require a majority for every decision?

    Any two majorities of the same cluster share at least one node. So two conflicting decisions cannot both be approved, and a new leader always reaches a node that knows every earlier decision.

    How many failures does a cluster of 3, 4 and 5 nodes tolerate?

    One, one and two. A cluster of 2f + 1 nodes tolerates f failures, and an even-sized cluster tolerates no more than the odd size below it.

    What is a term in Raft?

    A numbered period that starts with an election and has at most one leader. Nodes reject messages from older terms, which is how a deposed leader is ignored.

    When is a Raft log entry committed?

    When the leader has stored it on a majority of nodes. Only then is it applied and acknowledged to the client. It will be present in the log of every future leader.

    What is the election restriction in Raft?

    A node votes only for a candidate whose log is at least as up to date as its own, comparing the term of the last entry and then the length. This keeps committed entries from being lost in a leader change.

    What are the two phases of basic Paxos?

    Prepare and promise: a proposer reserves a proposal number with a majority and learns any value already accepted. Accept and accepted: it asks the majority to accept a value, which must be that earlier value if one was reported.

    Review the deck