Sub topic 9
What Must Be Written to Disk Before Replying
This chapter assumes you know the Raft roles (follower, candidate, leader), terms, the RequestVote and AppendEntries RPCs, and the commit rule from the earlier chapters. It also assumes you can read short Python. The question here is narrow: which pieces of server state must survive a crash, and at what moment they must reach durable storage.
Why persistence is a safety issue
A Raft server can crash and restart at any time. After a restart, everything in memory is gone. If the server then behaves as if it had never made earlier promises, it can break the guarantees the rest of the cluster relies on.
Raft's safety argument depends on promises that servers make through their RPC replies:
- A vote reply says "I will not vote for anyone else in this term."
- A successful
AppendEntriesreply says "this entry is stored on my disk, and you may count it toward a majority."
If a server sends either reply and then forgets it after a crash, the quorum arithmetic no longer holds. The cluster may elect two leaders in one term, or lose an entry that a leader already reported as committed.
Durable here means the data has reached stable storage and will be readable after a power loss. Handing bytes to the operating system is not enough. We return to this point later.
The persistent state
The Raft paper splits a server's state into persistent and volatile parts. Only three items are persistent.
| State | Where it changes | Why it must survive a crash |
|---|---|---|
| `current_term` | Seeing a higher term, starting an election | Prevents a restarted server from acting in an old term and granting a second vote there |
| `voted_for` | Granting a vote | Enforces at most one vote per term, which gives at most one leader per term |
| `log[]` | Appending or truncating entries | Holds the entries that the server has promised are stored |
The remaining state is volatile and can be rebuilt:
commit_indexandlast_appliedrestart at 0 and are rediscovered. A leader's nextAppendEntriestells the follower the current commit index. The state machine is rebuilt by replaying the log (or by loading a snapshot, then replaying the rest).next_index[]andmatch_index[]exist only on leaders. A new leader re-initializes them after each election.- The role itself. A restarted server always comes back as a follower.
The following diagram shows how a restart moves a server through recovery.
Why each item is required
`current_term` and `voted_for`
Consider a three-server cluster, S1, S2, S3, in term 5.
- S1 becomes a candidate in term 5 and asks S2 for a vote.
- S2 grants it and replies yes. S1 gets a majority (S1 and S2) and becomes leader.
- S2 crashes before writing
voted_for = S1to disk, then restarts withvoted_for = Noneandcurrent_term = 4. - S3 times out and becomes a candidate in term 5. It asks S2 for a vote.
- S2 has no memory of voting. It grants the vote. S3 now has S2 and itself, a majority.
Term 5 now has two leaders, S1 and S3. Both can append entries and tell followers different things. This breaks the Election Safety property that Raft's other proofs build on.
Persisting current_term matters for the same reason. A server that forgets its term can accept messages from a stale leader whose term it had already moved past, or vote twice across term boundaries in confusing ways. The two values are stored together because voted_for is only meaningful relative to a term. When the term increases, voted_for is cleared in the same update.
The log
When a follower returns success from AppendEntries, the leader may count that follower toward the majority needed to commit the entry. The follower has therefore promised that the entry will still be there after a crash.
Suppose a follower acknowledges entry 7 but holds it only in memory:
- The leader replicates entry 7 to two of three servers, counts a majority, and marks it committed.
- The leader replies to the client "done."
- One of the two followers crashes and restarts without entry 7. The leader also crashes.
- The two remaining servers might both lack entry 7. A candidate without it can win an election, because the voting rule compares logs and no surviving log contains the entry.
The client was told the write succeeded, and the cluster has lost it. Writing the log to disk before replying prevents this: a majority of durable copies means at least one durable copy exists in any majority that later forms an electorate.
Leaders have the same obligation for their own log. The leader's own copy counts in the majority (in the match_index list, its own last index is included), so the leader must write new entries to its own disk before counting itself.
The rule: persist, then reply
The order of operations is what matters. In each RPC handler, update the persistent state, flush it, and only then send the response.
Here is the vote handler from earlier chapters with the persistence points highlighted by comments.
def handle_request_vote(s, req):
# s.log[0] is a sentinel entry with term 0, so real entries start at index 1.
if req.term < s.current_term:
return (s.current_term, False)
if req.term > s.current_term:
s.current_term = req.term
s.voted_for = None
s.role = "follower"
last_index = len(s.log) - 1
last_term = s.log[last_index].term
candidate_up_to_date = (req.last_log_term, req.last_log_index) >= (last_term, last_index)
can_vote = s.voted_for is None or s.voted_for == req.candidate_id
if can_vote and candidate_up_to_date:
s.voted_for = req.candidate_id
s.persist() # must be durable before the reply leaves this server
s.reset_election_timer()
return (s.current_term, True)
s.persist() # a term change may have happened above
return (s.current_term, False)Notice the final s.persist() on the rejection path. If the handler raised current_term at the top, that change is persistent state too. Skipping the persist on a "no" reply is a common bug, because the reply feels harmless. The term change is not harmless if it is lost.
The AppendEntries handler follows the same pattern: it persists after modifying the term, the vote, or the log, and before returning. In the version from the earlier chapter, s.persist() runs just before each return that follows a state change.
One detail is worth noting. commit_index is updated in that handler, but it is not persisted. That is fine, because it can be recomputed.
What a leader must persist
A leader handling a client command does this:
- Append the new entry to its in-memory log.
- Persist the log.
- Send
AppendEntriesto followers (it may send in parallel with step 2 in optimized implementations, as long as the leader does not count its own copy toward the majority until step 2 completes). - Advance the commit index when a majority, including the leader's durable copy, has the entry.
Optimizing step 3 to overlap with step 2 is allowed by the protocol. Counting the leader's own vote before its disk write completes is not.
What "durable" means in practice
Writing to a file does not guarantee persistence. Operating systems buffer writes in memory and flush them later. A power failure can lose buffered data even after write() returned successfully. To force data to the device you need a call such as fsync.
The following sketch shows a minimal persistent store. It writes the term and vote to a temporary file, flushes it, and then renames it over the real file. The rename is atomic on POSIX file systems, so a crash leaves either the old file or the new one, never half of each.
import json
import os
class MetaStore:
"""Stores current_term and voted_for durably."""
def __init__(self, directory):
self.directory = directory
self.path = os.path.join(directory, "meta.json")
os.makedirs(directory, exist_ok=True)
def load(self):
try:
with open(self.path) as f:
data = json.load(f)
return data["current_term"], data["voted_for"]
except FileNotFoundError:
return 0, None
def save(self, current_term, voted_for):
tmp = self.path + ".tmp"
with open(tmp, "w") as f:
json.dump({"current_term": current_term, "voted_for": voted_for}, f)
f.flush()
os.fsync(f.fileno()) # data reaches the device
os.replace(tmp, self.path) # atomic swap
dir_fd = os.open(self.directory, os.O_RDONLY)
try:
os.fsync(dir_fd) # make the rename itself durable
finally:
os.close(dir_fd)
if __name__ == "__main__":
store = MetaStore("raft-data")
store.save(5, "S1")
print(store.load()) # (5, 'S1')The directory fsync at the end makes the rename durable. Without it, a crash could bring back the old file even though the new one was fully written.
The log needs a different design. Rewriting the whole file on each append is too slow. Real implementations append records to a write-ahead log file and call fsync after each batch. Truncation, which happens when a follower deletes conflicting entries, is recorded either by truncating the file or by writing a marker record.
Cost and batching
The fsync is usually the slowest step in a Raft commit. A commit needs a disk flush on the leader and on at least one follower, so commit latency is bounded below by flush latency plus one network round trip.
Common ways to reduce the cost without breaking safety:
- Batching. Collect several client commands and write them with one
fsync. The leader sends oneAppendEntriescarrying all of them. Followers flush once per request, not once per entry. - Group commit. While one flush is in progress, queue new entries and flush them together when it finishes.
- Pipelining. Send the next
AppendEntriesbefore the previous one is acknowledged, as long as acknowledgments are matched to the right indexes.
What you must not do is reply before the flush completes. Disabling fsync for speed turns a majority-durable system into one that can lose committed data after a correlated power failure, such as a rack losing power.
Common errors
- Persisting only the log. Forgetting
voted_fororcurrent_termallows two leaders in a term, as the example above showed. - Replying before the flush. The code persists, but a refactor moves the
returnearlier or an asynchronous write is not awaited. - Updating the term without persisting on a rejection path. The handler raises
current_term, rejects the request, and returns with the change only in memory. - Persisting
voted_forandcurrent_termin separate writes. A crash between them can leavecurrent_termat the new value with a stalevoted_forfrom the old term, or the reverse. Write both in one atomic update. - Persisting the commit index and trusting it blindly. It is allowed as an optimization, but then it must never exceed what the log actually holds. Most implementations skip it.
- Assuming a restart is the same as a network partition. A partitioned server keeps its memory. A restarted server does not, and only persisted state survives.
What recovery looks like
On startup a server:
- Loads
current_term,voted_for, and the log (and the latest snapshot, covered in a later chapter). - Sets its role to follower and
commit_indexto 0, or to the snapshot's last included index. - Starts its election timer.
- Applies committed entries to the state machine as it learns the commit index from a leader.
The server does not need to know whether it was the leader before the crash. If it was, a new election eventually elects someone. If it wins again, it does so in a higher term.
Exercise
A follower receives an AppendEntries request from a leader in term 9. The follower is in term 8. It accepts the request, appends two entries to its in-memory log, and sends back success. It writes its log to disk after sending the reply, and the machine loses power between the reply and the write. Name two things that can go wrong and the rule that prevents both.
Show answer
First, the leader may count this follower toward a majority and commit the two entries, which the follower no longer has after restart, so a committed entry can later be lost in an election. Second, the follower's currentterm of 9 was also not persisted, so after restart it is back in term 8 and may vote in term 9 again if it had already voted there. The rule is to persist currentterm, voted_for, and the log before sending the reply.
Exercise
Why can commit_index be left out of persistent state, and what happens to a server's state machine after restart if it is?
Show answer
The commit index is rediscovered: the next AppendEntries from a leader carries leader_commit, and the server then advances its own commit index and applies entries. After a restart the state machine starts empty (or from a snapshot) and the server replays committed entries from its log as the commit index advances. Safety is not affected, only the time before the server is caught up.