Goal

After this module you can run Raft by hand: say what every variable of the paper’s Figure 2 means and why it is persistent or volatile, execute RequestVote and AppendEntries on concrete logs (including the walk-back of nextIndex and the truncation of conflicting entries), decide when an entry is committed, and explain how clients are served exactly once.

Module 5 built the skeleton of a leader-based consensus algorithm: terms, one vote per term, majorities, and the Election Safety theorem. This module adds the part that carries data, the replicated log. Raft (1) is total order broadcast in the sense of Module 4 (Definition 4.3): the leader assigns each client command a position in its log, copies the log to the other servers, and every server applies the commands in log order to a deterministic state machine.

The algorithm is small enough to be written on one page (the paper’s Figure 2) and subtle enough that each rule on that page exists to block a specific failure. We go through the rules in the paper’s names, give the complete handlers as pseudocode, prove the local property of the AppendEntries consistency check, and trace two scenarios step by step. The global safety proofs (Log Matching, Leader Completeness, State Machine Safety) and the reason for the “current term” condition in the commit rule are in Module 7.

The module follows lectures 07.01 to 07.04, 08.01 and 08.02 (with the correction made in 08.04), §5.1 to §5.3, §5.5, §5.6 and §8 of the Raft paper, and Kleppmann’s notes §6.2, slides 111 to 120 (2).

Raft at a glance: roles, logs, commitment

The question is what exactly Raft agrees on. The answer is a log.

Every server keeps a log: a sequence of entries , each a pair (term, command). The term of an entry is the term of the leader that first appended it. Lecture 07.02 calls the log the ground truth of the system: it is an append-only file on stable storage, and the in-memory state (say, the value of x) is just the result of replaying it. If two servers have the same log prefix, replaying it gives the same state, because the state machine is deterministic (Module 4). So Raft only has to make the logs agree.

The three roles of Figure 5.1 stay as in Module 5. In normal operation one leader handles all client requests; followers only answer the leader’s and candidates’ requests; a client that contacts a follower is redirected. Raft uses two RPCs: RequestVote, sent by candidates, and AppendEntries, sent by the leader to replicate entries and, when it carries no entries, as a heartbeat. How these RPCs run over a real network, and why they stay safe when lost, repeated or delayed, is the subject of Appendix A.

Definition 6.1 (Committed entry).

An entry at index is committed once it is safe to apply it to the state machines, that is, once Raft guarantees that every future leader holds it and no server will ever apply a different command at index . A leader decides that entry is committed when an entry of its current term at some index is stored on a majority of servers (the commit rule below); this commits all entries at once.

Lecture 07.02 makes the difference between the two kinds of entries concrete. An uncommitted entry may still be lost, for example if the leader crashes before replicating it; this is acceptable because the client has not been told that its command took effect, and it will retry. A committed entry must never be lost or changed, because the client has been told “done” and will not retry. Figure 6.1 shows a typical moment.

1 2 3 4 5 6 7 8 index leader 1 x<-3 1 y<-1 1 y<-9 2 x<-2 3 x<-0 3 y<-7 3 x<-5 3 x<-4 S2 1 x<-3 1 y<-1 1 y<-9 2 x<-2 3 x<-0 S3 1 x<-3 1 y<-1 1 y<-9 2 x<-2 3 x<-0 3 y<-7 3 x<-5 3 x<-4 S4 1 x<-3 1 y<-1 S5 1 x<-3 1 y<-1 1 y<-9 2 x<-2 3 x<-0 3 y<-7 3 x<-5 committed entries (1 to 7)
Figure 6.1. Raft logs (after the Raft paper, Figure 6). Each cell is one entry: its term on top, its command below; the shading distinguishes the three terms. Entries 1 to 7 are on a majority (leader plus two followers) and are committed; entry 8 is not yet.

The state of a server

The question is which variables a server needs and which of them must survive a crash. Figure 2 of the Raft paper lists them, and lecture 08.01 goes through the reason for each.

VariableKindInitialWhy it is kept this way
currentTermpersistent0a restarted server must not return to an old term and vote again
votedForpersistentnullone vote per term must survive a crash
log[]persistentemptya stored entry may count toward a commit majority
commitIndexvolatile0can be learned again from the leader
lastAppliedvolatile0the state machine is rebuilt by replaying the log
nextIndex[j]leader, volatilelast index + 1a guess, corrected by the walk-back
matchIndex[j]leader, volatile0raised only by acknowledgements

The three persistent variables are written to stable storage before the server replies to the RPC that changed them; otherwise the reply could promise something that a crash erases.

  • currentTerm: lecture 08.01’s example is a server in term 5 that crashes and comes back in term 0. It would accept requests from leaders of long-dead terms and could vote in terms where it already voted; several such servers together could elect a second leader of an old term.
  • votedFor: without it, a restarted server can vote twice in one term, which breaks Lemma 5.9 and hence Theorem 5.10 (the forgetful voter, Example 5.11).
  • log[]: when a follower acknowledges an entry, the leader counts it toward a majority and may tell the client “done”. If the follower forgot the entry after a crash, the committed entry could end up on fewer than a majority of servers, and a later leader without it could be elected and overwrite it.
  • commitIndex may be volatile because a follower learns it again from the next AppendEntries (field leaderCommit), and a new leader learns it again by committing an entry of its own term (this is one reason for the no-op entry in the client section).
  • lastApplied may be volatile because the state machine itself lives in memory; after a restart it is rebuilt by replaying the log from index 1 (or from a snapshot, paper §7).
  • nextIndex is the leader’s optimistic guess of where follower ‘s log stops agreeing with its own; matchIndex is its pessimistic, confirmed knowledge. Both are reset after each election.
Remark 6.2 (Kleppmann's version).

Kleppmann’s slides 112 to 120 describe the same algorithm with different names, 0-based arrays and lengths instead of 1-based indices. With 1-based indices, “the first entries” ends at index , so lengths and indices coincide and the translation is exact. Kleppmann also keeps commitLength in stable storage, while the paper keeps commitIndex volatile; both are correct, the paper’s choice only means that a restarted server waits to relearn it.

Kleppmann (slides 112 to 120)Raft paper (Figure 2)
VoteRequest, VoteResponseRequestVote and its reply
LogRequest, LogResponseAppendEntries and its reply
cLogLength, cLogTermlastLogIndex, lastLogTerm
prefixLen, prefixTerm, suffixprevLogIndex, prevLogTerm, entries[]
commitLengthcommitIndex
sentLength[f]nextIndex[f] - 1
ackedLength[f]matchIndex[f]
ack in LogResponsematchedUpTo in our reply
function AppendEntriesreceiver steps 3 to 5 of Figure 2
deliver msg to the applicationapply command to the state machine

Elections with logs

The question is how Module 5’s election changes once servers have logs. Two things are added: a candidate announces how up-to-date its log is, and a voter refuses candidates with less up-to-date logs.

The first block holds the rule that every server applies to every message (Module 5’s adopt rule) and the start of an election. The functions lastIndex() and lastTerm() describe the server’s own log.

// Applied first to every request and every reply, on every server
on any message carrying term T:
    if T > currentTerm:
        currentTerm := T                 // persist
        votedFor := null                 // persist
        state := follower
 
function lastIndex(): return length(log)            // 0 if the log is empty
function lastTerm():  return log[lastIndex()].term if lastIndex() > 0 else 0
 
on election timeout:                     // follower or candidate, never leader
    currentTerm := currentTerm + 1       // persist
    state := candidate
    votedFor := self                     // persist
    votesReceived := {self}
    restart election timer with a fresh random value in [Tmin, Tmax]
    for each server j != self:
        send RequestVote(currentTerm, self, lastIndex(), lastTerm()) to j

The receiver grants a vote if the term is current, it has not voted for someone else, and the candidate’s log passes the up-to-date test.

Definition 6.3 (At least as up-to-date).

A log whose last entry has term and index is at least as up-to-date as a log whose last entry has term and index (an empty log has term and index ) if

In words: compare the terms of the last entries first; only if they are equal does the longer log win.

on receive RequestVote(term, candidateId, lastLogIndex, lastLogTerm) from c:
    if term < currentTerm:
        reply RequestVoteReply(currentTerm, false); return
    if votedFor in {null, candidateId}
            and upToDate(lastLogTerm, lastLogIndex):
        votedFor := candidateId          // persist BEFORE replying
        restart election timer
        reply RequestVoteReply(currentTerm, true)
    else:
        reply RequestVoteReply(currentTerm, false)
 
// Is a log ending with (cTerm, cIndex) at least as up-to-date as mine?
function upToDate(cTerm, cIndex):
    if cTerm != lastTerm():
        return cTerm > lastTerm()        // 1. the later last term wins
    return cIndex >= lastIndex()         // 2. same last term: not shorter
LinePurpose
term < currentTerma candidate from an old term gets “no” and learns the new term
votedFor in {null, candidateId}one vote per term (Module 5); a repeated request gets the same answer
upToDate(...)voters only elect candidates that hold everything they hold (proved useful in Module 7)
restart timer on a granta server that just voted does not immediately start its own election

Why compare last terms before lengths? The last term says which leader the log last listened to. A log that ends in term 5 has heard from the leader of term 5; a longer log ending in term 3 may contain entries that the leader of term 4 or 5 never had and has since overwritten elsewhere. Length only breaks ties between logs that last followed the same leader, and those logs agree on a common prefix (Module 7), so the longer one simply has more of the same leader’s entries.

Exam trap: the leader has the longest log

“Raft elects the server with the longest (or most up-to-date) log.” Wrong. Lecture 08.02 is explicit: votes are granted first come, first served, and a vote cannot be withdrawn. If a server with 4 entries asks first, a voter with 4 entries grants the vote and must refuse a server with 5 entries that asks later in the same term. The winner only needs to be at least as up-to-date as each of its voters, a majority, not as every server. Correctness does not need the best log; Module 7 shows that “at least as up-to-date as a majority” already contains every committed entry.

Exam trap: comparing lengths first

“Candidate X has log length 7, voter Y has length 5, so Y votes for X.” Not necessarily. If X’s last entry has term 2 and Y’s has term 3, then Y’s log is more up-to-date and Y refuses, whatever the lengths.

Collecting votes and taking office:

on receive RequestVoteReply(term, voteGranted) from j:
    if state != candidate or term != currentTerm:
        return                           // a late reply from an older election
    if voteGranted:
        votesReceived := votesReceived + {j}
        if |votesReceived| >= floor(n/2) + 1:   // n = configured cluster size
            becomeLeader()
 
function becomeLeader():
    state := leader
    for each server j != self:
        nextIndex[j] := lastIndex() + 1  // optimistic: j has all of my log
        matchIndex[j] := 0               // pessimistic: nothing confirmed
    for each server j != self:
        sendAppendEntries(j)             // the first heartbeat claims office
    start heartbeat timer                // repeat during idle periods

A candidate also stops being a candidate if it receives an AppendEntries of its own term from another server: by Election Safety that server is the legitimate leader of the term, so the candidate becomes its follower (handled in the AppendEntries receiver below).

Randomized timeouts and liveness

Elections can fail by splitting the vote (Figure 5.5). Raft picks each election timeout at random from an interval such as 150 to 300 ms (lecture 07.03) and picks a new one at the start of every election. The following proposition quantifies why this works, in a simple model.

Proposition 6.4 (A clean election round is likely).

Assume that after the leader fails, servers with equally up-to-date logs start their election timers at the same moment, each drawn independently and uniformly from ; that these are all the live servers and form a majority, ; that no server crashes during the round; that every message arrives within time ; and that a leader sends heartbeats at least every , where and . Call the round clean if the earliest timer fires more than before the second earliest. Then

and in a clean round the first candidate becomes leader. If every unclean round starts fresh timers under the same assumptions, the number of rounds until a leader is elected is at most geometric, with expectation at most .

The Raft paper states the resulting design rule as a timing requirement (§5.6):

Here broadcastTime is the time to send RPCs to all servers and collect the replies (0.5 to 20 ms, depending on how fast stable storage is), and MTBF is the mean time between failures of one server (months). The left inequality makes heartbeats arrive before followers time out and makes split votes rare (the proposition with about one broadcast time). The right one makes the time without a leader, about one election timeout per failure, a negligible fraction of all time. Safety never depends on these inequalities; only availability does.

Replicating the log: AppendEntries

The question is how the leader makes every follower’s log equal to its own, even though followers may be missing entries or hold extra entries left behind by earlier leaders.

The leader appends a client’s command to its own log and sends each follower the entries from nextIndex[j] on, together with the index and term of the entry just before them.

on client request command:               // command carries (clientId, seq)
    if state != leader:
        reply NotLeader(currentLeader); return   // redirect the client
    append (currentTerm, command) to log         // persist
    for each server j != self:
        sendAppendEntries(j)
    // the client's reply is sent by the apply loop, after commit and apply
 
function sendAppendEntries(j):           // also on every heartbeat tick
    prevLogIndex := nextIndex[j] - 1
    prevLogTerm := log[prevLogIndex].term if prevLogIndex > 0 else 0
    entries := log[nextIndex[j] .. lastIndex()]   // empty: a pure heartbeat
    send AppendEntries(currentTerm, self, prevLogIndex, prevLogTerm,
                       entries, commitIndex) to j

The follower’s side has four steps: the consistency check, deleting a conflicting suffix, appending what is missing, and learning the commit index.

on receive AppendEntries(term, leaderId, prevLogIndex, prevLogTerm,
                         entries, leaderCommit) from L:
    if term < currentTerm:
        reply AppendEntriesReply(currentTerm, false, 0); return
    state := follower                    // a candidate of this term gives up
    currentLeader := leaderId
    restart election timer
    // 1. consistency check on the entry just before the new ones
    if prevLogIndex > lastIndex()
            or (prevLogIndex > 0 and log[prevLogIndex].term != prevLogTerm):
        reply AppendEntriesReply(currentTerm, false, 0); return
    for k := 1 to length(entries):
        i := prevLogIndex + k
        // 2. a different term at index i: drop it and everything after it
        if i <= lastIndex() and log[i].term != entries[k].term:
            delete log[i ..]             // persist; never touches 1 .. i-1
        // 3. append what is missing; it lands exactly at index i
        if i > lastIndex():
            append entries[k] to log     // persist
    // 4. learn commitment, but only up to what this request just checked
    lastNew := prevLogIndex + length(entries)
    if leaderCommit > commitIndex:
        commitIndex := max(commitIndex, min(leaderCommit, lastNew))
    reply AppendEntriesReply(currentTerm, true, lastNew)
StepWhat it protects
reject term < currentTerma stale leader (Module 5) cannot change anything; the reply tells it the new term
1. consistency checknew entries are only attached behind an entry that agrees with the leader’s log
2. delete only on conflicta delayed, shorter AppendEntries must not erase entries that a later one already added
3. appendentries arrive in order; a repeated request is idempotent (paper §5.5)
4. min(leaderCommit, lastNew)entries after lastNew were not checked against the leader and may be stale

The reply of the paper’s Figure 2 has only term and success; the leader then knows that the follower matches up to prevLogIndex + length(entries) of the request it sent. We put that number into the reply as matchedUpTo (Kleppmann does the same with ack), so the leader need not remember which request a reply answers. The max in step 4 keeps commitIndex monotone when an old request arrives late; the paper states this monotonicity in Figure 2 without writing the max.

The next lemma is the local guarantee of one successful AppendEntries. It is the induction step of the Log Matching property, which Module 7 proves for whole logs.

Lemma 6.5 (What a successful AppendEntries guarantees).

Suppose follower replies success to AppendEntries with arguments , and (length ). Then right after the handler, ‘s log satisfies

  1. if ;
  2. for ;
  3. the entries are the same as before the handler.

The leader handles the replies. On success it records what is confirmed; on failure it steps nextIndex[j] back by one and retries.

on receive AppendEntriesReply(term, success, matchedUpTo) from j:
    if state != leader or term != currentTerm:
        return                           // a stale reply, or we stepped down
    if success:
        matchIndex[j] := max(matchIndex[j], matchedUpTo)
        nextIndex[j] := matchIndex[j] + 1
        advanceCommitIndex()
    else:
        nextIndex[j] := max(1, nextIndex[j] - 1)   // walk back one entry
        sendAppendEntries(j)                       // and retry

Lecture 08.01’s example: the leader has 10 entries and a follower has only 2. After the election nextIndex[j] = 11, so the first request checks index 10 and fails, then 9, and so on. The check at index 2 succeeds, and that request carries entries 3 to 10, exactly the ones the follower lacks. It took 8 rejections. The paper (§5.3) mentions an optimization in which the follower reports the term of the conflicting entry and the first index it stores for that term, so the leader can skip a whole term per round trip; the paper doubts it is needed in practice.

Proposition 6.6 (The walk-back terminates).

Suppose stays leader of term and sends AppendEntries to follower one at a time, each eventually answered. Then after at most consecutive failures (counted from the first of them), a request to succeeds.

Proposition 6.7 (Leader Append-Only).

A leader never deletes or overwrites entries in its own log; it only appends. Formally, if server is leader of term from time to time , then at is a prefix of at every time in .

This is the second of the five properties in Figure 3 of the Raft paper. The other three, Log Matching, Leader Completeness and State Machine Safety, are proved in Module 7.

Try it: send SET x from the client and step through. Watch the leader’s matchIndex row fill in as acknowledgements arrive, then commitIndex jump once a majority (the leader included) has the entry; the followers apply only after the next AppendEntries carries the new leaderCommit.

client A B C SET x 5 ok (after apply) AppendEntries, index 1 A commits 1 leaderCommit 1: apply leaderCommit 1: apply
Figure 6.2. Normal replication with three servers (the raft-sim replication scenario). The entry is committed when the leader holds it together with one follower, two of three. The followers learn this from leaderCommit on the next AppendEntries.

Committing and applying

The question is when the leader may consider an entry committed, and how the rest of the cluster finds out.

Definition 6.8 (Commit rule).

A leader of term sets if all three of these hold:

  1. ;
  2. ;
  3. .

Setting commits every entry with index at most , including entries of earlier terms. Every server applies entries in index order up to its .

function advanceCommitIndex():           // on the leader, after each success
    for N := lastIndex() down to commitIndex + 1:
        replicas := 1 + |{ j != self : matchIndex[j] >= N }|   // 1 = leader
        if replicas >= floor(n/2) + 1 and log[N].term == currentTerm:
            commitIndex := N             // commits 1 .. N at once
            return
 
// Every server, whenever commitIndex > lastApplied:
while commitIndex > lastApplied:
    lastApplied := lastApplied + 1
    result := apply log[lastApplied].command to the state machine
    if state == leader and a client waits for entry lastApplied:
        reply result to that client

The third condition, , is easy to forget and essential. Without it a leader could count replicas of an entry from an older term, declare it committed, and later see it overwritten by another leader: the Raft paper’s Figure 8. Module 7 shows the counterexample and proves that the condition fixes it. Entries of older terms are still committed, but only indirectly, when an entry of the current term after them reaches a majority.

Lecture correction: the commit rule

Lecture 08.03 states the commit rule as “a majority of matchIndex at least ”, without the current-term condition. That version is unsafe (Figure 8 of the paper, Module 7). The rule in Figure 2 of the paper, and in Kleppmann’s slide 120, requires that the entry at belongs to the leader’s current term.

Followers learn about commitment lazily. The leader puts its commitIndex into every AppendEntries as leaderCommit (lecture 08.01: no separate “commit” message is needed), and a follower raises its own commitIndex in step 4 of the receiver. In the good case one entry costs one round trip from the leader to a majority before the leader can apply it and answer the client, and the followers apply it one heartbeat later (Figure 6.2).

Exam trap: committing up to the end of the follower's log

“On AppendEntries the follower sets commitIndex to min(leaderCommit, its last log index).” Wrong; the bound is the index of the last entry this request verified, . Example: leader A of term 3 has log terms (1, 1, 3, 3) and . Follower E still holds stale entries with terms (1, 1, 2, 2). An implementation that sends empty heartbeats from sends , , no entries, . The check passes. With the wrong bound E would set and apply its term-2 entries at indices 3 and 4, which are not the committed ones. With the correct bound, .

Lecture correction: a new leader does not learn committed entries from followers

Lecture 08.02 says that when a new leader is elected, a follower that holds a committed entry may tell the leader about it, and the leader must then spread it. Lecture 08.04 retracts this. Raft has no such transfer: data flows only from leader to followers, and the up-to-date restriction on votes already guarantees that every new leader holds every committed entry (Leader Completeness). The paper says the same in §5.4.1. The proof is in Module 7.

Worked example 1: catching up lagging followers

We follow five servers A to E. The history before the example is as follows. In term 1, leader B replicated x<-1 and y<-2 (indices 1 and 2) to A, B, D and E, and they were committed; C had crashed after receiving index 1. In term 2, E became leader, appended three entries (z<-7, z<-8, z<-9 at indices 3 to 5) to its own log only, and crashed. In term 3, A was elected with the votes of A, B and D (all with logs ending in term 1 at index 2). A then received two client commands and appended x<-3 and y<-4 at indices 3 and 4 in term 3.

So A has log terms (1, 1, 3, 3), , and, from its election, and for all . B and D have (1, 1); C has (1); E has (1, 1, 2, 2, 2). Figure 6.3 shows C and E before and after.

StepAppendEntries sent by AFollower’s checkEffect
1to B: prev 2, term 1, entries 3 and 4index 2 has term 1: passB appends 3, 4; reply success, 4
2to D: same as step 1passD appends 3, 4; A now has 3 replicas of index 4
3(A runs the commit rule)index 4 has term 3 = currentA: commitIndex 4, applies 3 and 4, answers both clients
4to C: prev 2, term 1, entries 3 and 4C has no index 2: failA sets nextIndex[C] to 2
5to C: prev 1, term 1, entries 2 to 4index 1 has term 1: passC appends 2, 3, 4; commitIndex min(4, 4) = 4
6to E: prev 2, term 1, entries 3 and 4passindex 3 conflicts (2 vs 3): E deletes 3 to 5, appends 3, 4

Checks a reader can make:

  • Step 3: replicas of index 4 are A, B, D, three of five. Without the current-term condition the result would be the same here, because index 4 is a term-3 entry; the condition matters only for older-term entries (Module 7).
  • Step 4: C first adopts term 3 (the common rule), then fails the check because .
  • Step 6: E adopts term 3. The loop compares index 3: term 2 against 3, a conflict, so E deletes indices 3, 4, 5 (all three term-2 entries; none was ever committed) and appends the two new entries. In the same request E learns .
  • After step 6, every log is (1, 1, 3, 3) and every on A equals 4.
1 2 3 4 5 A (leader) 1 x<-1 1 y<-2 3 x<-3 3 y<-4 term 3, nextIndex 3 C before 1 x<-1 prev 2: no entry, fail C after 1 x<-1 1 y<-2 3 x<-3 3 y<-4 prev 1 ok, gets 2 to 4 E before 1 x<-1 1 y<-2 2 z<-7 2 z<-8 2 z<-9 prev 2 ok, 3 conflicts E after 1 x<-1 1 y<-2 3 x<-3 3 y<-4 3 to 5 deleted, 3, 4 stored
Figure 6.3. Catching up two followers (worked example 1). C lacks entry 2, so the first check fails and nextIndex steps back from 3 to 2. E has stale term-2 entries from a leader that crashed; the check at index 2 passes, entries 3 and 4 conflict, E deletes its entries 3 to 5 and stores the leader's.

Worked example 2: a partition heals

This is the scenario of lecture 07.03 (the animation part of the lecture), now with the variables. Five servers; B is leader of term 1; every log holds one committed entry (term 1, SET x 5). A partition separates A and B from C, D and E. Logs are written as lists of (term, command).

StepEventA and BC, D and E
0B leads term 1term 1; log (1, SET x 5)term 1; same log
1partitionB still leader of term 1no heartbeats arrive
2C times out, gets votes of C, D, Eunchangedterm 2; C leader
3client 1 sends SET x 3 to Blog + (1, SET x 3) on A and Bunchanged
4client 2 sends SET x 8 to Cunchangedlog + (2, SET x 8); committed
5heal; C’s AppendEntries reaches A and Badopt term 2; index 2 replacedunchanged
6client 1 retries; redirected to Cgets (2, SET x 3) at index 3appends and commits it

Checks:

  • Step 3: B’s entry at index 2 is on B and A only. B’s commit rule needs replicas, and B cannot reach C, D or E. So B never commits it, and client 1 gets no answer. This is Proposition 5.12 at work: C, D, E voted in term 2, so no majority of term-1 acknowledgements can be gathered any more.
  • Step 4: C’s entry is on C, D, E, three of five, and has term 2 = C’s current term, so C commits it, applies and answers client 2.
  • Step 5: C sends AppendEntries(term 2, prevLogIndex 1, prevLogTerm 1, entries [(2, SET x 8)], leaderCommit 2). A and B adopt term 2 (B steps down), pass the check at index 1, find a conflict at index 2 (term 1 against term 2), delete their entry SET x 3, append SET x 8, and set . The same step-down would happen if B’s own term-1 AppendEntries reached C first: C would refuse with term 2.
  • Step 6: from client 1’s point of view nothing distinguishes this run from a lost message (lecture 07.03). It times out, retries, is redirected by B to C, and its command is committed at index 3, so the final value is .

Try it: cut the network between A, B and C, D, E, send SET x 3 to B and SET x 8 to C, and compare the commitIndex on both sides. Then heal the partition and watch B step down and its uncommitted entry at index 2 get replaced.

A, B (2 of 5) C, D, E (3 of 5) A term 1 1 x<-5 1 x<-3 B leader t1 1 x<-5 1 x<-3 C leader t2 1 x<-5 2 x<-8 D term 2 1 x<-5 2 x<-8 E term 2 1 x<-5 2 x<-8 SET x 3: on 2 of 5, not committed SET x 8: on 3 of 5, committed index 2 will be overwritten index 2 is final
Figure 6.4. The partition scenario of lecture 07.03 just before the network heals. B, the leader of term 1, has SET x 3 on two servers and cannot commit it. C, elected in term 2 by C, D, E, has committed SET x 8. After the heal B steps down and the entry SET x 3 is overwritten.

Clients: redirects, exactly once, no-op entries, reads

The question is how a client uses Raft so that each command takes effect exactly once and reads never return stale data. The paper’s §8 answers four sub-questions.

Finding the leader. A client sends its request to any server. A follower rejects it and names the leader it last heard from (leaderId arrives with every AppendEntries). If the leader crashes, the client’s request times out and the client tries another server. Lecture 07.02 adds that the client library knows the cluster membership, so it always has someone to ask.

Answering only after commit and apply. The leader answers the client only after the entry is committed and applied, with the result of applying it. Before that moment the entry may still be lost (step 3 of worked example 2), and the client must be free to retry.

Exactly once. A retry can duplicate a command: the leader commits the entry, applies it, and crashes before answering; the client retries and the new leader appends the command a second time. For a command like “add 1” this is wrong. The fix is that each client numbers its commands. A command carries (clientId, seq), and the state machine remembers, for each client, the highest seq it has executed and the response. A command whose seq has already been executed is not executed again; the stored response is returned. This is the deduplication of Module 3 (Proposition 3.5), done inside the replicated state machine. Together with answering only after apply, it gives linearizable semantics (3).

A no-op at the start of each term. A new leader holds every committed entry (Module 7), but it does not know which of its entries are committed: commitIndex is volatile, and the commit rule only lets it commit through an entry of its own term. So a new leader immediately appends a blank no-op entry of its term and replicates it. Once the no-op is committed, so is everything before it.

Reads. A read does not change state, so it is tempting to answer it from the leader’s state machine without touching the log. The danger is a stale leader, like B in worked example 2, answering after was committed. The paper requires two precautions: the leader must have committed its no-op (so its state reflects everything committed), and before answering it must exchange heartbeats with a majority. By Proposition 5.12, if a newer leader had been elected, at least one server in that majority would have answered with a higher term. An alternative is a lease: the leader answers reads for a while after its last successful heartbeat round, which is faster but makes safety depend on bounded clock drift. Appendix B proves the heartbeat version (called ReadIndex in production libraries) linearizable and states the clock condition a lease read needs.

What breaks

  • Byzantine servers. A follower deletes entries because the leader says so; it does not verify that the sender really is the leader (lecture 08.02). A single faulty or malicious server claiming a high term can wipe out the logs of the whole cluster. Lecture 08.02 also reports that a bit flip on the leader’s disk is copied to every follower: replication alone does not protect against corruption.
  • Losing stable storage. All arguments assume that persistent state survives crashes. A server that loses its log and rejoins can make a committed entry fall below a majority.
  • Membership changes. The majorities above are taken over one fixed configuration. Changing the set of servers needs the joint-consensus procedure of §6 of the paper.
  • No majority. If fewer than servers are up and connected, no entry can be committed and no leader elected; the system is unavailable but still safe.
  • Timing. If approaches , elections keep splitting and heartbeats arrive too late; availability suffers, safety does not.

Why it matters

This module gave the whole of basic Raft: Figure 2’s state, both RPCs, the commit rule, and the client protocol. Each rule has a local job (the consistency check glues a follower’s log onto the leader’s, the up-to-date check filters voters’ choices, the current-term condition guards commitment). Module 7 combines these local facts into the global guarantees, Log Matching, Leader Completeness and State Machine Safety, and explains Figures 7 and 8 of the paper. Module 10 maps every rule here onto Multi-Paxos: terms become ballots, the election becomes Paxos phase 1, and AppendEntries becomes phase 2.

Further reading

  • The Raft paper, Figure 2 and §5.1 to §5.6, §8 (1); Ongaro’s thesis, chapter 3 and chapter 6 on clients (4).
  • Kleppmann’s notes §6.2, slides 111 to 120 (2).
  • Schneider’s tutorial on the state machine approach that Raft implements (5).
  • Viewstamped Replication, a closely related earlier protocol (6).

Homework

The problems for this module are in Homework 6.

1.
Ongaro D, Ousterhout J. In Search of an Understandable Consensus Algorithm. In: Proceedings of the USENIX Annual Technical Conference (ATC). 2014. p. 305–19.
2.
Kleppmann M. Distributed Systems: Lecture Notes [Internet]. University of Cambridge, Computer Science Tripos Part IB; 2021. Available from: https://www.cl.cam.ac.uk/teaching/2122/ConcDisSys/dist-sys-notes.pdf
3.
Herlihy MP, Wing JM. Linearizability: A Correctness Condition for Concurrent Objects. ACM Transactions on Programming Languages and Systems. 1990;12(3):463–92.
4.
Ongaro D. Consensus: Bridging Theory and Practice [phdthesis]. Stanford University; 2014.
5.
Schneider FB. Implementing Fault-Tolerant Services Using the State Machine Approach: A Tutorial. ACM Computing Surveys. 1990;22(4):299–319.
6.
Oki BM, Liskov BH. Viewstamped Replication: A New Primary Copy Method to Support Highly-Available Distributed Systems. In: Proceedings of the 7th ACM Symposium on Principles of Distributed Computing (PODC). 1988. p. 8–17.