RaftKV
Raft consensus from scratch: a 5-node replicated key-value store over gRPC
Raft-based replicated key-value store in Python: leader election and log replication over gRPC, a SQLite-backed log, snapshot compaction with InstallSnapshot, client leader redirect, and a 5-node Docker Compose cluster.
The problem
A replicated store must agree on one order of writes across nodes that crash, restart and fall behind, without split-brain or losing committed entries.
The approach
Raft leader election and log replication over gRPC with a crash-safe SQLite WAL log, snapshot compaction with InstallSnapshot, and client-side leader redirect with per-client sequence numbers for idempotent retries.
Architecture
- 01
Client driver
RaftKVClient tries cluster nodes, follows NOT_LEADER replies using the returned leader hint, retries after short fixed delays, and tags each request with a client id and sequence number.
- 02
gRPC and Protobuf
proto/raft.proto defines the RequestVote, AppendEntries and InstallSnapshot RPCs and the client service; each node runs an async gRPC server.
- 03
Consensus engine
An asyncio engine with follower, candidate and leader roles, randomized election timeouts, periodic heartbeats, per-peer nextIndex and matchIndex, and majority-based commit index advancement.
- 04
Durable log
SQLite in WAL journal mode with synchronous=FULL stores the current term, vote, log entries and snapshot metadata.
- 05
State machine and snapshots
An in-memory key-value state machine applies committed entries and skips duplicate client sequence numbers; the log is compacted into snapshot.json at a size threshold and sent to lagging peers with InstallSnapshot.
- 06
Cluster and dashboard
Docker Compose defines a 5-node cluster on a bridge network, and web_demo.py serves a dashboard with kill and revive controls and a hand-built /metrics text endpoint.
Key decisions
- Persists Raft state in SQLite with WAL journaling and synchronous=FULL, giving crash-safe term, vote and log writes from the Python standard library at the cost of a sync on every commit.
- Compacts the log into a JSON snapshot once it holds 50 entries and sends the full snapshot to followers that are behind it; the low threshold exercises compaction often but rewrites the whole state each time.
- Records the highest applied sequence number per client id in the state machine, so a write retried after a leader change is not applied twice.
- Has followers reject client calls with NOT_LEADER and a leader hint, and makes the client follow the hint, instead of proxying requests through followers.
- Serves reads from the leader's local state machine after a role check, without a ReadIndex or lease round; reads stay cheap, but a deposed leader that has not yet stepped down could return stale data.
Results
- In the in-process five-node tests a new leader is elected after the leader's task is cancelled, writes succeed with two nodes stopped, and the expected values are read back after those nodes rejoin.
- A Docker Compose file and Dockerfile package the same node code as a five-node container cluster, and the web dashboard can stop and restart nodes interactively.
| Metric | Value | Source |
|---|---|---|
| Nodes stopped while writes still commit (5-node cluster) | 2 of 5 | tests/test_fault_injection.py |
| Randomized election timeout | 150–300 ms | raftkv/consensus/engine.py |
How it is tested
- 8 test functions in total: WAL metadata, append and truncate, and compaction; the engine's initial state and its RequestVote and AppendEntries handlers; a 5-node failover test; and a 5-node fault-injection sequence.
- The cluster tests run 5 nodes as asyncio tasks in one process on loopback ports and simulate crashes by cancelling a node's task, checking re-election of a different leader, writes through client redirection, writes with two nodes stopped, and reads after the stopped nodes rejoin.
- CI compiles the Protobuf definitions, runs pytest, and runs benchmark.py; the benchmark step does not start a cluster, so it is not a performance measurement.
Limits, stated plainly
- The test suite is thin (8 functions); there is no dedicated test of InstallSnapshot to a lagging follower, and partitions are simulated by stopping nodes rather than cutting network links.
- No benchmark results are committed; the throughput figures in the README are sample output without a backing result file.
- Sub-second re-election is a stated target; the failover test polls for a new leader but does not enforce a one-second bound.
- Reads are not linearizable across a leader change, there is no cluster membership change, and /metrics is a hand-written text endpoint in web_demo.py rather than a Prometheus client.
- docs/ARCHITECTURE.md has drifted from the code (it states synchronous=NORMAL and 150 to 350 ms timeouts; the code uses synchronous=FULL and 150 to 300 ms).