Understanding Raft · Part 4
Understanding Raft, Part 4: Building Crystal in Go
The paper turned into a database. Crystal's crash-safe write-ahead log, snapshots, InstallSnapshot, and the single control loop that owns consensus state.
Paper versus disk
The first three parts covered Raft as an algorithm: why consensus is hard, leader election and replication and safety. The paper is unusually complete, but it describes an ideal machine whose log lives in memory, never loses anything and grows forever. Real hardware gives you none of that.
Crystal is my implementation of Raft in Go, wrapped around a replicated key-value store. This part is about the problems that only show up once you build it, and each one maps to a piece of the code.
Dependencies point one way. The storage layer imports Raft, and Raft never imports HTTP or the key-value layer, so the consensus core can be tested on its own.
Durability
Raft’s safety proof assumes that when a server records something (its term, its vote, a log entry), it still knows it after a crash. Memory doesn’t give you that. If a server appends an entry, tells the leader “got it”, crashes and forgets, then the majority that committed the entry never really existed.
So two kinds of state have to be on disk before the server acts on them. The current term and the vote, or a restarted server could vote twice in one term. And every log entry, before it is acknowledged to the leader.
Crystal writes both through a write-ahead log. Entries are framed and appended to a file, and fsync puts them on disk before the reply goes out. On startup the server replays the file and gets back its log and term exactly as they were. If the last frame was only half written when the machine died, recovery cuts it off instead of trusting it.
fsync is slow, and one per entry quickly becomes the throughput limit. Crystal buffers a batch of entries and syncs once for the whole batch. Durability stays the same, because nothing is acknowledged until the batch is on disk.
Log growth
The log only grows. After months of writes it would be too big to keep and far too slow to replay, and most of it is useless anyway. Once SET x=3 is followed by SET x=9, the first entry no longer matters.
The paper’s answer is snapshots (section 7). A server saves the current state of its state machine, “as of index N the store is {x: 9, y: 1}”, and deletes every log entry up to N. The snapshot remembers the index and term of the last entry it covers, so the consistency check from Part 3 still works for the entry right after it.
One detail took me a while. Crystal snapshots at the last applied index, not the commit index. A snapshot is a copy of the state machine, and the state machine only contains what has been applied. On a follower the two numbers drift apart all the time, and a snapshot taken at the commit index would claim entries whose effects it doesn’t contain and then delete the entries needed to fill that gap. Crystal also refuses to snapshot at an index whose term it doesn’t know, because a snapshot with a made-up term breaks every consistency check against it after a restart.
Followers that are too far behind
Snapshots create a new problem. A leader normally repairs a lagging follower by stepping back and resending the missing entries. If those entries were already compacted into a snapshot, the leader doesn’t have them anymore.
That’s what the InstallSnapshot RPC is for. The leader sends its whole snapshot to the follower, the follower replaces its state with it, and normal AppendEntries continues from the snapshot’s last index. In Crystal the leader compacts on a timer, even while a follower is unreachable, so this path gets exercised exactly in the situation it exists for. A node that was down for a long time, or a brand new one, can rejoin without the leader keeping its history forever.
Concurrency
The paper doesn’t say how to structure this part, and it’s the decision I’m happiest with.
A Raft node handles a lot at once. Client writes, votes, replication replies, reads and timers all want to look at the same few fields and change them. Raft’s dangerous operations are read-modify-write steps across several fields. “Advance the commit index if a majority has this entry and it’s from my term” reads the replication progress, the log and the term, then writes the commit index. With mutexes, that’s four chances to hold the wrong lock, and consensus bugs don’t crash. They show up later as two replicas that quietly disagree.
So Crystal has one rule. One goroutine, the control loop, is the only writer of consensus state: the commit and apply indices, the role, and the lists of requests waiting for an answer. Everything else sends it a message.
for {
select {
case <-done:
e.failAllWaiters(ErrNotLeader)
return
case prop := <-e.proposals:
e.handleProposal(prop)
case higherTerm := <-e.stepDownCh:
e.handleStepDown(higherTerm)
case v := <-e.preVoteCh:
e.handlePreVoteResult(v)
case v := <-e.voteCh:
e.handleVoteResult(v)
case a := <-e.ackCh:
e.handleAck(a)
case r := <-e.readCh:
e.handleRead(r)
case <-ticker.C:
e.onTick()
}
}
Crystal’s control loop, slightly shortened. Each case is one event, handled to the end before the next one starts.
Because those decisions happen in one place, one at a time, the safety rules from Part 3 become plain functions that read and write fields directly. The log and the persisted term keep their own locks, and the loop is what decides what to do with them. Replication still runs in parallel, with one goroutine per follower that owns all the network latency to that follower. Those goroutines only report results back to the loop and never change consensus state themselves, so a slow follower only slows down its own goroutine.
Testing
You can’t trust consensus code you only ran on the happy path. Crystal is tested at three levels.
Unit tests go after the invariants one by one. A message with an older term can’t change the log, a stale leader steps down, and the commit rule refuses to count an entry from an older term (there is a test that replays Figure 8 exactly). An in-process cluster runs several nodes over a fake network for fast, repeatable scenarios. And the integration suite starts real processes that talk over HTTP. It kills the leader and checks that no acknowledged write is lost, restarts a follower and checks that it catches up, forces a snapshot and checks that a lagging node recovers through InstallSnapshot, and checks that a retried client request is applied exactly once.
The integration suite is the one I trust most, because it tests what anybody actually wants from this thing. The leader dies and the data is still there.
What building it taught me
Reading the paper, I understood Raft. Building Crystal is where I believed it, because every shortcut I considered maps to a failure the paper already describes. Skip an fsync and a crash eats a committed write. Use the naive commit rule and the Figure 8 test fails. After a while the paper’s restrictions stop looking arbitrary.
So if you want to really learn how consensus works, read Crystal, or better, build your own. The paper is 18 pages long and it was written to be understood.
Reference: Diego Ongaro and John Ousterhout, “In Search of an Understandable Consensus Algorithm,” USENIX ATC 2014. Persistence and compaction follow sections 5 and 7. The diagram is mine. This is the last part of the series. The code is in Crystal, and its docs/ folder explains the concurrency design in more depth.