Part 9 · 1 chapters · ~8 min
Raft in Code
Implementing Raft's core: terms and roles, randomised election timeouts, RequestVote with the up-to-date log rule, AppendEntries with the consistency check, commit rules and the current-term restriction, applying to a state machine, persistence of term, vote and log, and testing with simulated network faults.
10
The core rules
code
// the heart of a follower's AppendEntries handler (Raft paper, Figure 2)
function onAppendEntries(req) {
if (req.term < state.currentTerm) return { term: state.currentTerm, success: false };
becomeFollower(req.term, req.leaderId); resetElectionTimer(); // randomised 150-300 ms
if (req.prevLogIndex > 0 && state.log[req.prevLogIndex]?.term !== req.prevLogTerm)
return { term: state.currentTerm, success: false }; // logs disagree: leader will back up
for (const [i, e] of req.entries.entries()) {
const idx = req.prevLogIndex + 1 + i;
if (state.log[idx] && state.log[idx].term !== e.term) state.log.length = idx; // delete conflicting suffix
state.log[idx] = e;
}
persist(state); // term, votedFor, log: before replying
if (req.leaderCommit > state.commitIndex) state.commitIndex = Math.min(req.leaderCommit, lastIndex());
applyCommitted();
return { term: state.currentTerm, success: true };
}Test it the way Distributed Systems part 13 describes: a deterministic simulated network that drops, delays and reorders messages and partitions nodes, with invariants checked after every step (at most one leader per term; committed entries never change). MIT 6.5840's Raft labs are the classic exercise.
RAFT IN CODE: ONE ENTRY COMMITTED
the messages and rules you implement
swipe the figure sideways, or tap expand for full screen
1/4
append locally
The leader appends the command to its log with its current term. Nothing is committed yet.
leader appends with its termnot committed yet