Sub topic 9
What must be written to disk before replying
This chapter assumes you know the RequestVote and AppendEntries handlers from the earlier chapters. It also assumes you know that a server can crash and restart with its memory wiped.
The rule
A Raft server may crash at any moment. After it restarts, it must behave as if it had never forgotten anything it promised. A reply to an RPC is a promise. So the rule is:
Write the state an RPC changed to stable storage before sending the reply.
"Stable storage" means data that survives a crash. A write that sits in the operating system's page cache does not count. You need a flush such as fsync.
What is persistent and what is not
Raft's paper splits server state into two groups.
| State | Persist? | Why |
|---|---|---|
| `current_term` | Yes | Prevents the server from accepting a stale leader or voting in an old term again |
| `voted_for` | Yes | Enforces one vote per term across restarts |
| `log` | Yes | Acknowledged entries may be part of a committed majority |
| `commit_index` | No | Can be relearned from the leader |
| `last_applied` | No | Rebuilt by replaying the log (or from a snapshot) |
| `next_index`, `match_index` | No | Leader-only, reinitialized after each election |
Volatile state can be lost because the protocol can recompute it. Persistent state cannot be recomputed, because it records decisions other servers have already relied on.
Why each item matters
voted_for and current_term
Suppose a follower votes for candidate A in term 5, replies, and then crashes before saving the vote. It restarts with voted_for = None. Candidate B then asks for a vote in term 5, and the server grants it. Both A and B can now collect a majority in term 5, which breaks the guarantee of at most one leader per term.
The handler in the election chapter ends with s.persist() before returning True for this reason. It also persists on rejection, because it may have raised current_term or cleared voted_for earlier in the handler.
The log
When a follower replies True to AppendEntries, the leader counts that follower toward the majority. If the leader then commits the entry and replies to the client, the entry must survive on a majority of servers. If followers acknowledged entries only from memory, a majority could crash and restart without them. The cluster would have lost a committed entry.
The leader follows the same rule. It must write a new entry to its own disk before counting itself in match_index. In advance_commit_index, the leader's own value in match_index represents durable storage, not just memory.
A minimal durable store
This example saves all three persistent fields in one atomic step. It writes to a temporary file, flushes it, renames it over the old file, and then flushes the directory so the rename itself is durable.
import json
import os
import tempfile
class Storage:
def __init__(self, path):
self.path = path
def save(self, current_term, voted_for, log):
tmp = self.path + ".tmp"
with open(tmp, "w") as f:
json.dump(
{"current_term": current_term, "voted_for": voted_for, "log": log}, f
)
f.flush()
os.fsync(f.fileno()) # data reaches the disk
os.replace(tmp, self.path) # atomic swap: old or new, never half
dir_fd = os.open(os.path.dirname(os.path.abspath(self.path)), os.O_RDONLY)
try:
os.fsync(dir_fd) # make the rename durable (POSIX)
finally:
os.close(dir_fd)
def load(self):
if not os.path.exists(self.path):
return 0, None, [{"term": 0}] # fresh server: term 0, sentinel log entry
with open(self.path) as f:
d = json.load(f)
return d["current_term"], d["voted_for"], d["log"]
with tempfile.TemporaryDirectory() as d:
store = Storage(os.path.join(d, "raft.json"))
store.save(5, "A", [{"term": 0}, {"term": 5, "cmd": "x=1"}])
print(store.load()) # simulates a restart: the vote for A in term 5 survivesRewriting the whole file on every call is fine for learning. Real systems append to a write-ahead log instead, so each RPC costs one small sequential write.
Practical points
- Persist once per RPC. Update the term, vote, and log in memory, then do one flush before replying.
- Batch. Leaders and followers can combine several client commands into one flush. This is the main way to recover throughput, because
fsyncis usually the slowest step. - Order matters. Never send the reply, and never count your own vote or log entry, until the flush returns.
- Snapshots are also persistent state. A snapshot lets you drop old log entries, so it must be durable before you delete them.
Exercise
A follower grants a vote in term 7 and replies "granted", but it saves voted_for to disk only after the reply. It crashes between the reply and the save. Describe how two leaders could exist in term 7.
Show answer
After restarting, the follower has voted_for = None for term 7, so it can grant a second vote to a different candidate. Together with the first vote, that second vote can give two candidates a majority in the same term, so both become leader of term 7. Persisting voted_for before replying prevents this.
Exercise
Why does Raft not need to persist commit_index?
Show answer
A restarted server can learn the current commit index from the leader's next AppendEntries. Since every committed entry is already in the persisted log, losing commit_index loses no committed data. The server only has to replay entries to rebuild the state machine.