All my work / Distributed systems · by Ravindra Sawant

Quorum

Deterministic Raft consensus simulator with fault injection and an always-on invariant checker.

Python 3.11+ · standard library · virtual clock 514 lines of core code source on GitHub ↗ CI status

4/4 core requirements 6 tests passing 2/2 benchmark targets

Verified 2026-11-28; CI re-runs the acceptance tests on every push.

The problem

Replicated services must agree on an ordered log despite leader failures and network partitions. This is a deterministic Raft simulator with a fault-injecting network and an invariant checker that runs after every single event.

What I found

  • 140 randomized schedules of drops, duplicates, reordering, partitions and crashes produced zero safety violations, and every run converged after healing.
  • The benchmark first stalled: every client proposal started its own replication chain. Capping in-flight appends per follower (with heartbeats as recovery) fixed it - real Raft implementations batch and pipeline for the same reason.
  • The liveness test had to model client retries: a write accepted by a leader that is deposed before replicating is correctly discarded.

Architecture

Cluster.step(t): scheduled faults/proposals ─► deliver due messages (partition + liveness check at delivery)
                 ─► node.tick(t) (election timeout | heartbeat) ─► Checker callbacks on leader/commit/truncate/apply
Node: follower ─timeout─► candidate (term+1, persist self-vote, RequestVote) ─majority─► leader (+ no-op entry)
      leader ─► AppendEntries(prev_index, prev_term, ≤64 entries, leader_commit, seq) ─► follower checks prefix,
      truncates conflicting *uncommitted* suffix, appends, persists, replies match_index
      leader ─► match_index monotonic; commit N only if log[N].term == current term and a majority has N
  • Index convention: log[0] is a sentinel Entry(term=0, index=0).
  • Persistence: term, voted_for and log are saved (Memory or File storage, temp+fsync+rename) before any reply that depends on them. Restart reloads them; commit/applied are re-derived from the leader and re-applied.
  • Stale replies: responses from older terms are ignored; a success can only raise match_index; only the newest rejection (matching seq) can move next_index back; at most one append in flight per peer (+ heartbeats).
  • Network model: seeded per-message delay (min..max ticks → reordering), drop and duplicate probabilities, partitions as groups; undeliverable messages are counted.
  • Checker: one leader per term; committed entry at each index is unique across nodes; committed entries never truncated; applied entries equal the committed entry and are applied in order.

Requirements → tests

ReqPriRequirement Proven byStatus
FR-01P03/5-node clusters; follower/candidate/leader; persistent term/vote/log; seeded timers + heartbeatsT01, T03pass
FR-02P0RequestVote (one vote/term, freshness) and AppendEntries (prev checks, conflict repair, step down)T03, T04pass
FR-03P0Leader writes, nextIndex/matchIndex, commit only current-term majority entries, ordered applyT01, T02pass
FR-04P0Virtual delay/drop/reorder/duplicate, partitions, crash/restart; trace, roles, logs, commit/appliedT02, T05pass
FR-05P1Client request-id dedup, leader no-op, randomized property schedules, visual log comparisonT05pass
TestWhat it provesResult
T013-node election, steady heartbeats, client command, majority commit, identical applied statepass
T02Isolated leader cannot commit; majority elects new leader and commits; heal repairs old suffixpass
T03Crash after vote persisted -> no second vote in same term; follower log survives restart (file storage)pass
T04Freshness rule (term then index), conflict repair, stale/old-term replies never regress match/commitpass
T05100+ randomized delay/drop/partition/crash schedules with invariants after every event, then livenesspass

Benchmark

Target (hypothesis from the spec)GoalActual
zero safety violations across all seeds and fault schedules00met
every scenario converges with a stable majority and bounded delaysall8/8met
  • commit_p95_ticks_steady = 15.5
  • failover_ticks_p50 = 48.5
  • messages_per_entry_steady = 1.8250000000000002

quick run · 2026-11-28T23:57:30+00:00 · Virtual ticks and message counts only; finite tests are not a formal proof.

Design questions

Why does Raft need randomized election timeouts?

To make split votes unlikely: one node usually times out first, wins a majority, and heartbeats suppress others.

Why only commit current-term entries by counting?

An entry from an older term replicated on a majority can still be overwritten by a later leader (Figure 8); committing a current-term entry commits all prior entries transitively.

What does the log-matching property guarantee?

If two logs have an entry with the same index and term, they are identical up to that index - enforced by the prevLogIndex/prevLogTerm check.

Why persist term and vote before replying?

Otherwise a crash-restart could vote twice in one term and allow two leaders.

Can a minority partition serve writes?

No. It can accept proposals but never commit them; once healed, its uncommitted suffix is overwritten. Linearizable reads need read-index or leases (not implemented).

Limitations

  • Fixed membership, no snapshots, no linearizable read protocol, no pre-vote
  • Simulation only (no real RPC); finite tests are not a proof

Run it

git clone https://github.com/ravirs/quorum.git && cd quorum
pip install -r requirements.txt
PYTHONPATH=src python -m raftsim demo   # demo
PYTHONPATH=src python -m pytest -q   # test
PYTHONPATH=src python benchmarks/bench.py --quick   # bench

More systems I've built from scratch

Storage & data systems

  • Strata LSM-tree key-value storage engine: WAL, SSTables with Bloom filters, atomic manifest, compaction
  • Tidelog Kafka-style durable partitioned log broker: CRC'd records, offsets, generation-fenced consumer groups
  • Floe Iceberg-style table format: immutable Parquet, manifests, snapshots, time travel, compare-and-swap commits
  • Flint Spark-style batch engine: lazy lineage, stage planning, shuffles, broadcast and salted skew joins
  • Watermark Event-time stream processor: windows, watermarks, lateness, exactly-once checkpoints
  • Warden Data governance catalog: explainable grants, row filters, column masks, lineage impact
  • SnapshotDB MVCC transaction engine: snapshot isolation, the write-skew anomaly, a serializable mode

AI infrastructure

  • Nearline HNSW-style vector search index from scratch, measured against exact search
  • KVPager Paged KV cache with copy-on-write forks and prefix reuse (PagedAttention-style)
  • Batchwise LLM inference scheduler simulator: static vs continuous vs chunked-prefill batching
  • Steadyhand Durable AI agent runtime: allowlisted tools, approvals, budgets, crash recovery, replay
  • Toolgate Model Context Protocol gateway: curated tools, signed identity, tenant policy, approvals, audit

Distributed systems

  • Tandem Collaborative text editor on a sequence CRDT: offline edits, any delivery order, always converges
  • Burrow Minimal Linux container runtime in Go: namespaces, pivot_root, cgroup v2 limits

← See all my work: apps, ML/AI and systems