The Raft consensus algorithm in Python: leader election, log replication and a replicated key-value store, running as a cluster of processes over TCP. Written to understand how machines that can crash, stall and lose messages still agree on one ordering of events.
Break it in your browser → Five nodes
running core/raft.py under Pyodide on a simulated network. Crash the leader, partition
nodes, turn up message loss, and write keys while it happens; the logs, terms, election
timers and every message in flight are drawn live. Partition the leader and then read from
it: the read is refused rather than answered from a copy the rest of the cluster has moved
past.
A cluster needs one leader, and every node has to agree on which one it is, without any node being able to tell a crashed peer from a slow one. Raft's answer is terms and timeouts: time is divided into numbered terms with at most one leader each, and a node that hears nothing for long enough assumes the leader is gone and stands for election. Once there is a leader, it alone appends to the log, and an entry is committed once a majority has stored it.
core/raft.py is the whole algorithm, and it does no I/O. A RaftNode never reads the
clock, sleeps or opens a socket: time comes in through tick(now), messages come in
through handle_request and handle_response, and messages to send come back out. That
one decision is what lets the same file run in three places:
core/node.pydrives it with asyncio time and the TCP transport, as a real process.tests/test_raft.pydrives it with a virtual clock and a lossy in-memory network.web/sim.pydrives it inside a browser for the demo.
- Elections. A follower that hears no valid leader within a randomized 1.5 to 3 second timeout becomes a candidate: it increments the term, votes for itself and asks every peer for a vote. A fresh timeout is drawn for every election. A fixed one makes two nodes that split a vote wake in the same order next term and split it again.
- Voting. A node grants at most one vote per term, and only to a candidate whose log is at least as up to date as its own (a later last term, or the same term and at least as long). That rule is why an elected leader always already holds every committed entry.
- Terms. Any message carrying a higher term makes the receiver adopt it and step down to follower. A stale leader learns it has been replaced the moment it hears from the new term.
- Replication. The leader sends
AppendEntrieswith the entries from each follower'snext_indexon, plus the index and term of the entry just before them. A follower whose log does not contain that entry rejects the request with a hint of where to back up to, and the leader retries immediately rather than waiting a heartbeat. Accepted entries are appended, truncating only at the first entry that actually conflicts, so a delayed, shorter request cannot erase entries a newer one already added. - Commitment. The leader commits the highest index stored on a majority, but only by counting replicas of an entry from its own term (Figure 8 of the paper). An older entry can sit on a majority and still be overwritten by a future leader. Each new leader appends a no-op in its term so that inherited entries commit without waiting for a client write.
- Persistence. Term, vote and log reach stable storage before the node answers the
RPC that changed them. Both halves matter: a node that forgets a vote can vote twice in
one term and elect two leaders, and a node that forgets an entry it acknowledged can
leave a committed entry held by a minority.
core/storage.pyhas three backends behind one interface, so the algorithm itself stays free of I/O: files for a real process, memory for the tests, nothing at all for the browser. - Crash and restart.
load()brings back term, vote, log and the latest snapshot, and nothing else. The node relearns the commit index from the leader and rebuilds its store by applying the log again from the snapshot onwards. - Snapshots. Everything at or below
last_appliedhas already reached the state machine, socompact()replaces that prefix of the log with a snapshot of the state. Without it the log is the whole history: a restart replays all of it, and a node that has been away is caught up one entry per round trip. When a follower needs entries that have been compacted away, the leader sendsInstallSnapshotinstead ofAppendEntries, and the follower adopts the state wholesale. - Linearizable reads. A leader cannot tell by itself that it still leads: partition it and it keeps its state and keeps calling itself the leader. Before answering a read it pins the read to the current commit index and waits for a majority to reply to a round of heartbeats started after that point (the read index of section 6). It also waits for its own no-op to commit, because a fresh leader does not yet know which inherited entries are committed.
- Transport. Messages are length-prefixed JSON over TCP, and every RPC is bounded by a timeout: a partitioned peer neither accepts nor refuses, and an unbounded wait on it would stall the timer meant to detect it.
Requires Python 3.11 or newer. No dependencies.
git clone https://github.com/apollo-2006/nexus_cluster.git
cd nexus_cluster
# five terminals, or background them
python cluster_cli.py node 1
python cluster_cli.py node 2
python cluster_cli.py node 3
python cluster_cli.py node 4
python cluster_cli.py node 5
python cluster_cli.py set color blue # goes to whichever node is leader
python cluster_cli.py get color
python cluster_cli.py status # each node's term, role, leader, log and storeKill the leader's process and run status again: a new leader is elected within a few
seconds with every committed key intact, and writes keep working as long as three of the
five nodes are up.
python -m unittest discover -s tests -t .The tests run five nodes on a virtual clock with an in-memory network that delays, drops and reorders messages, and can crash or partition nodes. After every simulated 5 ms they assert Raft's safety properties: at most one leader per term, log matching, leader completeness (every leader holds every entry committed before its term), and state machine safety (no index applied as two different commands). Scenarios cover election, leader failover, a minority partition that must not commit, a healed partition whose stale leader's entries are overwritten, a restarted node catching up, and 40 seeds of random loss, crashes and partitions that must end with every store identical.
Recovering a node in the simulation builds a new RaftNode over the same storage and
loads from it, so a test that sees a term, a vote or an entry after a crash is seeing
something that was really stored. On top of the safety properties, the suite covers the
three things a prototype usually skips: a vote that survives a restart and is not granted
twice in one term, a node caught up by InstallSnapshot after the entries it missed were
compacted away, and a partitioned leader that refuses a read it can no longer prove is
current. Ten more seeds run the whole chaos loop with compaction switched on.
To check the tests can fail, each safety rule was deleted from raft.py in turn: voting
twice per term, skipping the up-to-date log check, accepting stale-term AppendEntries,
skipping the previous-entry consistency check, dropping the new-leader no-op, using a
fixed election timeout, committing old-term entries by count, and truncating logs
unconditionally. The random simulation caught six of the eight. The last two need
message orderings it almost never produces, so each has a direct test on hand-built
state, and all eight are now caught.
core/raft.py the algorithm: elections, replication, commitment, snapshots
core/raft_rpc.py RequestVote / AppendEntries / InstallSnapshot payloads
core/storage.py stable storage: files, memory, or nothing
core/state_machine.py the key-value store the log drives
core/node.py RaftNode as an asyncio TCP server, plus client commands
network/tcp_transport.py length-prefixed JSON RPC with bounded timeouts
cluster_cli.py start a node, or set/get/status against the cluster
tests/test_raft.py deterministic simulation and safety checks
web/ the Pyodide demo
- Fixed membership. Five nodes on hardcoded ports; no joint consensus for adding or removing one.
- No pre-vote. A node that comes back from a partition raises the term of the whole cluster and forces an election it cannot win, which costs an election timeout of availability for nothing.
- Snapshots are sent whole. The paper chunks
InstallSnapshot; here the state goes in one message, which is fine while a state machine is a few thousand keys and would not be beyond that. - A log truncation rewrites the file. Appends are appended and fsynced, but the rare case of a new leader overwriting entries this node never committed rewrites the log whole. Honest at these sizes, wrong at real ones.
- One connection per RPC. Simple and bounded, but a connection pool would cut heartbeat overhead considerably.
- The state machine is a dictionary. No expiry, no transactions, no iteration order guarantees beyond insertion.
MIT. See LICENSE.
Abir Deol · abirdeol.tech