Raft is famous for being the understandable consensus algorithm. The paper is readable, the animations are clear, and after an hour you feel you have it. Then you try to implement it, and you find that every sentence in the paper is there because of a specific failure, and that leaving out any one of them produces a cluster that works until the day it loses data.

raft-kv is my attempt to learn it properly: a distributed key-value store on a from-scratch Raft implementation in Go, using only the standard library. Half of the project is the system itself. The other half is the tooling to torture it and check that it stays correct. It is a learning project, not a production database.

What it does

There are four parts:

  • raft: the consensus core. Leader election, log replication with a fast conflict-skip, commit index tracking, persistence (term, vote, log), snapshots with log compaction and InstallSnapshot, and single-server membership changes.
  • kv and httpapi: a replicated key-value state machine, an HTTP API for clients, cluster join and leave, and the Raft transport over HTTP.
  • simnet: an in-memory network that partitions, drops, delays, reorders and duplicates messages, so a whole cluster can be tortured in one test process.
  • linearize: a Porcupine-style linearizability checker, used to verify histories recorded from concurrent clients.

The path of a write looks like this:

client ─► HTTP /kv/{key} ─► kv.KV.Do ─► raft.Node.Propose (leader only, else 307) │ append + persist, send AppendEntries ▼ followers: check prevIndex/prevTerm → append (truncate only on conflict) → persist → reply Match (or a Hint to skip a whole term) │ leader: match[] majority on an entry of the current term → commit ▼ applier goroutine: Apply in order → wake the waiting Propose every SnapshotThreshold entries: FSM.Snapshot → compact the log follower behind the compaction point ← InstallSnapshot 

What I built from scratch, and what it teaches

Why Raft needs each of its rules. The up-to-date check on votes. Committing only entries of the current term by counting replicas (section 5.4.2 of the paper, the "figure 8" problem). The leader's no-op entry. And a subtle one: a follower must truncate its log only on a real conflict, because a stale, reordered AppendEntries must not erase newer entries.

Messages, not RPCs. Requests and replies are independent one-way messages (raft.Message). The node never blocks on the network, which turns loss, duplication and reordering into "just another message". The HTTP transport gives each peer a bounded queue and drops when it is full. The leader also pipelines: it advances next[peer] optimistically after sending a batch, and a lost batch shows up as a rejected heartbeat, after which next is reset from the follower's hint.

Persistence and snapshots. What must be on disk before replying, how the log is re-based on a snapshot marker, and what happens to a follower that is behind the leader's compaction point (it gets an InstallSnapshot). The hard state (term, vote, log) is written as one file, atomically: temp file, fsync, rename, fsync of the directory.

Membership changes. They happen one server at a time, with the fix from the raft-dev 2015 thread: a leader must commit an entry in its own term before a change. Membership is the latest config entry in the log, committed or not, as in the Raft dissertation. A new node starts with an empty log and no config, so it never campaigns until the leader has replicated a config that contains it. There is also leader stickiness, so removed or partitioned nodes cannot depose a healthy leader with ever-higher terms.

Linearizable reads, the simple way. Reads go through the log, so they are linearizable without leases or ReadIndex. The cost is a log write per read.

How to test a distributed system. This is what I most wanted to learn: deterministic-ish simulation, failure injection, and checking linearizability instead of eyeballing logs. One detail shows why a checker is needed: a Put that times out has an unknown outcome. It may have been applied or not. It is recorded as pending forever, and the checker handles that.

How to use it

Install the binary with Go:

go install github.com/AbdeldjalilChougui/raft-kv/cmd/raftkv@latest 

From a clone of the repository, start a three-node cluster on localhost:

go build -o raftkv ./cmd/raftkv # First node creates the cluster; the others join through any member. ./raftkv -id n1 -listen 127.0.0.1:7001 -bootstrap & ./raftkv -id n2 -listen 127.0.0.1:7002 -join http://127.0.0.1:7001 & ./raftkv -id n3 -listen 127.0.0.1:7003 -join http://127.0.0.1:7001 & curl -L -X PUT --data hello http://127.0.0.1:7002/kv/greeting # 204 curl -L http://127.0.0.1:7003/kv/greeting # hello curl -L -X DELETE http://127.0.0.1:7001/kv/greeting curl http://127.0.0.1:7001/cluster/status curl -L -X POST -d '{"id":"n3"}' http://127.0.0.1:7001/cluster/leave 

You can write to one node and read from another. Followers answer 307 Temporary Redirect to the leader, and curl -L follows it and keeps the method and body.

State lives in data/<id>/, in two JSON files, state and snapshot. Restarting a node with the same -id and -data recovers it, and -bootstrap and -join are ignored then. A good experiment is to kill the leader and watch /cluster/status on another node.

How it is tested

go test -race ./... # ~35 s; -short skips the longest chaos test 

The raft tests run a 3 to 5 node cluster on simnet. They check a single leader per term, re-election, no leader without quorum, a follower catching up after a disconnect, a minority leader's entries being discarded, crash and restart of every node, snapshot compaction, InstallSnapshot for a lagging follower, adding a node, and removing the leader itself. Then comes a 4-second chaos run: 10% loss, 5% duplication, 0 to 25 ms random delays, random partitions and crashes, with proposals flowing. Every apply on every node is checked against every other: no two nodes may ever apply different commands at the same index.

The kv tests put six concurrent clients against a 5-node cluster for 3 seconds, on a reliable network, with random partitions, and with loss, reordering and crash and restart. The recorded history, roughly 1,200 operations, must be linearizable.

The httpapi tests use three real nodes on 127.0.0.1: bootstrap, join (one through a follower redirect), writes and reads through followers, leader failure, and restarting a node from its data directory.

Things to know

This is a learning project, not a production database. The README is specific about it:

  • Whole-state persistence. Every log change rewrites the full log file. It is simple and obviously correct, but O(log size) per write. A real implementation appends to a segmented WAL.
  • No client sessions. Retried commands are not deduplicated, so a retried PUT after a timeout may apply twice. That is harmless here, because PUT and DELETE are idempotent and there are no non-idempotent operations.
  • Reads cost a log entry. No ReadIndex or leader leases.
  • No pre-vote, no leadership transfer, no learners and no joint consensus. A new node counts toward the quorum as soon as it is added.
  • Snapshots are taken synchronously in the apply goroutine and sent in one message, so they must fit in memory.
  • The HTTP transport has no TLS and no authentication. Run it only on a trusted network.
  • A storage error panics the node rather than risking unsafe behaviour.

What I learned

The main lesson is that for this kind of code, the tests are the project. A Raft implementation that passes a happy-path demo proves very little. What gives confidence is a network that misbehaves on purpose and a checker that states precisely what "correct" means.

The second is that the rules I had read as details are the algorithm. Truncating only on a real conflict looks like an optimisation until a reordered message arrives.

The third is that unknown outcomes are normal. A timeout does not mean "failed". Recording such an operation as pending forever is the only honest way to write the history down.

Get the code

The source, the simulator, the checker and the tests are on GitHub: https://github.com/AbdeldjalilChougui/raft-kv. It is MIT licensed.

Originally published at abdeldjalilchougui.biz.