Raft
Distributed systems should be fault tolerant - we want the system to stay available and continue operating “correctly” even if some nodes fail. One way to achieve this is to run replicas, so that if the main server goes down, another node can take over and keep serving requests. For that to work, the replicas need to stay “up-to-date”.
A common approach is to model each node as running the same deterministic program (a state machine), and to ensure that all nodes execute the same operations in the same order. This idea is called replicated state machines. Different nodes may make progress at different speeds, but as long as identical operations are applied in the same sequence, they will eventually converge to the same state. The hard part is deciding on the order of operations, and getting every node to agree on it.
Raft is a consensus algorithm designed to help nodes reach this agreement. This article closely follows the original Raft paper and references several figures from it.
Raft Overview
Section titled “Raft Overview”Before diving into how Raft works, we first need to specify the failure model - a set of failures the system is designed to tolerate.
-
Fail-stop model: a node that fails stays down permanently.
-
Fail-recover model: a failed node may later restart and rejoin the system, potentially with a stale state.
-
Byzantine model: failures can be arbitrary; a faulty node might behave unpredictably or even send forged messages.
Here, let’s assume the fail-recover model.
In addition, Raft assumes that a majority of nodes/servers are always up. For example, with 5 servers, Raft can tolerate at most two failures at a time.
Raft has a leader and followers. Only the leader serves client requests. The leader’s responsibility is to order incoming operations, replicate that order to followers by sending AppendEntries RPC, mark operations as committed once they are “set in stone” (will never be overwritten in the future), and then respond back to the client.
Time in Raft is divided into terms of arbitrary length. In each term, at most one server is elected a leader (“at most one” because an election can end in a split vote, in which case no leader is chosen and a new election/term begins shortly after).
- Figure 5 from the Raft paper
Suppose we are in term 1. The leader of term 1 regularly sends heartbeat messages to announce that it is still alive. If the leader crashes, followers stop receiving heartbeats. After waiting for some time period (electionTimeout), a follower assumes that the leader has crashed, increments its term counter to 2, becomes a “candidate”, and starts a campaign (sends RequestVote RPC to the other servers). If the candidate receives votes from a majority, it becomes the new leader.
Split votes are also possible, where no candidate reaches a majority. In that case, another server will soon timeout, increment its term counter, and start a new election. To reduce the chance of repeated split votes, each server sets a randomized timeout.
Servers may not immediately realize that a new term has started or that an election has occurred. Each server maintains its own currentTerm and may advance through terms at different speeds, though it will typically catch up quickly as it exchanges messages with other servers.
Also note that a candidate must win votes from a majority of all servers, not just the servers that are up at the moment. Under our failure assumption that a majority of servers remain alive, it is always possible in principle for a candidate to collect a majority vote.
Both the leader and followers maintain an indexed log of operations. Each log entry stores the term in which it was created and the operation itself (we’ll see later why the term is relevant). The leader sends AppendEntries RPC to followers to replicate new entries and keep their logs up-to-date.
- Figure 6 of the Raft paper illustrates what the logs look like conceptually.
The Invariants
Section titled “The Invariants”We now have a high-level overview of Raft (though many details have been omitted). Before diving deeper, it helps to keep these key invariants in mind (Figure 3 from the Raft paper).
-
Election Safety. At most one leader can be elected in a given term.
-
Leader Append-Only. A leader never overwrites or deletes entries in its own log; it only appends new entries.
-
Log Matching. If two logs contain an entry at the same index with matching terms, then the logs are identical up through (and including) that index.
-
Leader Completeness. If a log entry is committed in a given term, then that entry will appear in the logs of all future leaders. Committed entries are durable and will eventually be executed by all of the available state machines. Uncommitted entries, however, may be overwritten by future leaders. The leader should commit only if it is certain that the entry will not be overwritten in the future (more on this later).
-
State Machine Safety. If a server has applied a log entry at a given index to its state machine, then no other server will apply a different entry at that same index. This highlights the distinction between having an entry in the log and applying it to the state machine. Each server tracks
lastAppliedand may apply log entries at its own pace, but it must apply entries only prior to its localcommitIndex(i.e.,lastApplied <= commitIndex).
Takeaways
Section titled “Takeaways”Below, we will look at how Raft is implemented in practice. While these implementation details help us build an intuitive picture of Raft, they can also blur the line between the core algorithm and minor design choices that do not really affect its correctness.
If I had to summarize Raft in two or three key takeaways, this would be the right mental model: to preserve the invariants listed above, Raft is very selective about choosing the right leader. By ensuring that only a server containing all committed entries can become leader, Raft guarantees that committed entries are never lost. This differs from other consensus protocols such as Paxos, where leader election is less restrictive, but additional mechanisms are needed to ensure that committed entries are preserved.
Server State
Section titled “Server State”Let’s take a look at the server’s state (the book-keeping metadata it maintains, not the state machine’s state). Every server (both leader and follower) maintains the following data alongside its indexed log (log[]).
currentTerm
Section titled “currentTerm”The highest term this server has seen so far. Different servers can have different currentTerm at the same time, and currentTerm increases monotonically.
Each RequestVote and AppendEntries RPC includes the sender’s term t. When a receiver receives a message with t greater than its own currentTerm, it updates currentTerm to t. If the receiver was the leader, it will step down and become a follower.
If a receiver receives a message with term t less than its currentTerm, it treats the sender as stale and rejects/ignores the message.
votedFor
Section titled “votedFor”Each server can vote only once per term. votedFor records which candidate the server voted for in the currentTerm. If the server has already voted for another candidate in that term, it will not grant another vote in response to a RequestVote.
If the server receives a message (AppendEntries or RequestVote) with a higher term, it will update currentTerm and reset votedFor to NULL, making it able to vote again.
commitIndex
Section titled “commitIndex”The index of the highest log entry known to be committed; commitIndex increases monotonically. Different servers can temporarily have different commitIndex. The leader includes its commit point (leaderCommit) in each AppendEntries, and a follower updates its local commitIndex to min(leaderCommit, lastLogIndex) (min so it never commits entries it doesn’t yet have).
Unlike currentTerm and votedFor, commitIndex is volatile: it can be lost if the server crashes. After recovery, the server can reinitialize commitIndex to 0 and then catch up quickly from the leader’s commit point carried in subsequent AppendEntries messages.
lastApplied
Section titled “lastApplied”lastApplied is the index of the highest log entry the server has applied to its state machine. Because applying is only safe for committed entries, each server applies entries while lastApplied < commitIndex: it increments lastApplied and applies log[lastApplied] until lastApplied == commitIndex. lastApplied is also volatile, and since commitIndex is initialized to 0 after a crash, lastApplied is initialized to 0 as well (so lastApplied <= commitIndex holds).
In addition to these, the leader maintains the following items.
nextIndex[]
Section titled “nextIndex[]”nextIndex[f] is the first index the leader believes follower f’s log is missing. The leader sends entries starting at nextIndex[f] up through its latest log entry. When a leader is newly elected, nextIndex[f] is initially set to the leader’s latest log index + 1 (i.e., the leader assumes that the follower is fully up-to-date).
When the leader sends an AppendEntries message to follower f, the follower may reply false if nextIndex[f] is too far ahead (i.e., the follower does not have an entry at index nextIndex[f] - 1). This means the follower is missing more entries than the leader’s initial guess. In that case, the leader decrements nextIndex[f] and tries again by sending more entries.
matchIndex[]
Section titled “matchIndex[]”matchIndex[f] is the highest log index the leader knows has been replicated on follower f. When a follower is fully synchronized, matchIndex[f] + 1 should equal nextIndex[f].
When a new leader is elected, it initializes matchIndex[f] to 0 for all followers (unlike nextIndex[f], which starts at the leader’s last log index + 1). As AppendEntries succeed, the leader updates matchIndex[f].
The leader uses the matchIndex[] values across followers to determine which log index has been replicated on a majority and can therefore be committed (more on this below).
Missing Pieces
Section titled “Missing Pieces”Hopefully at this point, we have a good overview of how Raft works, even though the picture is not yet complete. Next, we’ll fill in the missing pieces and walk through the subtleties that require a bit more care.
Casting Votes
Section titled “Casting Votes”Raft guarantees the Leader Completeness property by ensuring that a newly elected leader has all committed entries, and that it will never overwrite them. This is enforced during elections: servers grant their votes only to candidates whose logs are “sufficiently up to date”.
When a candidate sends RequestVote to other servers, it includes: term, candidateId, lastLogIndex, and lastLogTerm. The receiver will first compare its currentTerm with the candidate’s term.
-
If
term < currentTerm, the receiver will refuse to vote and respond false. The candidate will convert to a follower when it receives false. -
If
currentTerm <= term, the receiver will first update itscurrentTerm(if needed), and then continue to check the candidate’s eligibility.
Next, the receiver will check whether the candidate’s log is “at least as up to date” as its own. Concretely, the receiver will cast its vote if:
-
the candidate’s
lastLogTermis higher than its own, OR -
the
lastLogTerms are the same, but the candidate’s log is longer (i.e., has a higherlastLogIndex).
If the request satisfies this condition, the receiver casts its vote on a first-come-first-served basis. It can vote for at most one candidate in each term.
Appending Entries
Section titled “Appending Entries”Only the leader sends AppendEntries RPC to followers. AppendEntries includes: term, leaderId, prevLogIndex, prevLogTerm, entries[], and leaderCommit.
We’ve discussed how the leader maintains nextIndex[f], its guess for the first index follower f is missing. The follower uses (prevLogIndex, prevLogTerm) to check whether it agrees with the leader up to index prevLogIndex, and therefore whether it can safely attach new entries.
If the follower does not have an entry at prevLogIndex, or if the entry at prevLogIndex does not have the same prevLogTerm, it rejects the message and returns false without appending any entries. This means the follower’s log is not identical to the leader’s log up through prevLogIndex.
The leader then retries with a smaller prevLogIndex (decrementing nextIndex[f]) and sends more entries. Once the follower finds a matching (prevLogIndex, prevLogTerm), the Log Matching property implies the logs are identical up through and including that index, and the follower overwrites any entries that come after it and appends the leader’s entries.
As a result, whenever AppendEntries succeeds, the leader will know that the follower’s log is identical to its own log up through the new entries.
When to Commit
Section titled “When to Commit”We haven’t yet discussed when a leader can mark an entry as committed. The leader can advance its commit index once it knows an entry is replicated on a majority of servers.
A subtlety here is that the leader can only commit entries from its current term by counting replicas. Entries from earlier terms are not safe to commit based on majority replication alone.
- Figure 8 from the Raft paper demonstrates this point.
In (a), S1 is the leader, but it crashes before it can fully replicate entry 2. In (b), S5 becomes the leader (it wins votes from S3, S4, and itself) and appends entry 3. In (c), S5 crashes, and S1 becomes the leader again.
At this point, S1 can resume replicating entry 2. However, even if S1 manages to replicate 2 onto three servers, this is not enough to safely commit 2.
The reason is shown in (d). If S1 crashes again, S5 can be elected leader again and overwrite the 2s with 3. This is possible because leader election does not compare the value/operation stored at a particular index. It only compares the candidate’s (lastLogTerm, lastLogIndex), so a candidate can win even if its log contains a different entry.
The fix is in (e). After S1 regains leadership, it should replicate a new entry from its current term (entry 4) and try to commit that entry first. Once 4 is replicated on a majority, S1 can commit 4, and then the earlier entry 2 becomes safe as well (it will not be overwritten by future leaders). But if S1 crashes again before 4 is replicated on a majority, neither 4 nor the earlier 2 is guaranteed to survive, and both may be overwritten.
Timeouts
Section titled “Timeouts”Raft relies on electionTimeout to detect leader failures. To keep leaders stable while still reacting to crashes, it helps to choose the timeout so that: broadcastTime << electionTimeout << MTBF. Here, broadcastTime is the average time for the leader to broadcast messages to followers (in parallel), and MTBF is the average time between failures for a single server.
The Raft paper dives deeper into many more details, but this should give us a solid picture of what Raft is and how it works.
- Figure 7 from Raft paper illustrates the possible follower scenarios when a new leader comes to power.
Before ending, I want to point to Figure 7 from the Raft paper. It’s a good reminder of how “out of sync” the servers can be at any given moment, and it highlights a number of interesting edge cases. The beauty of Raft is that even under these chaotic circumstances, the servers will work together to decide which entries stay committed.