SysDesignAtlas

How You Know It's Correct

Model checking, Jepsen, and deterministic simulation — the three techniques that find distributed bugs tests cannot, and why "we tested it" is not an answer.

HLDHard11 min readdistributedcorrectnesstestingverification
Confidence

#Why ordinary testing fails here

A distributed bug needs three things to line up: a specific interleaving of concurrent operations (the exact order in which steps from different nodes happen to run), a specific failure at a specific moment, and a specific piece of state. Your test suite explores maybe a dozen interleavings out of an astronomically large space, always on a healthy network, and always at the same speed.

The bugs that survive to production are precisely the ones that need an unusual schedule. Kyle Kingsbury's Jepsen work found correctness violations in the default configuration of nearly every distributed database he tested — systems written by good engineers with extensive test suites.

So "we have integration tests" is not a claim about correctness. Three techniques are, in increasing order of confidence and cost.

#1. Model checking: verify the design, not the code

Model checking means describing your protocol in a small formal language, stating the rules that must never be broken, and letting a tool mechanically try every state the system can reach — every interleaving, every crash point — looking for one where a rule breaks. Where testing samples the space, this exhausts it.

TLA+ is the dominant tool. You describe the system as a state machine — variables, an initial state, and the transitions allowed — then assert invariants and temporal properties. An invariant must hold in every single state ("never two leaders in the same term"). A temporal property is about how things unfold over time ("every request is eventually answered").

   A specification has three parts:

     Init      the allowed starting states
     Next      every transition the system may take
               (including crashes, message loss, reordering)
     Invariant what must be true in EVERY reachable state

   The model checker then does exhaustive search:

     enumerate all states reachable from Init via Next
     at each one, evaluate Invariant
     if it fails → print the exact sequence of steps that got there

That last line is what makes it worth the effort. A model checker doesn't say "something is wrong"; it hands you a minimal counterexample trace, step by step.

What it catches: protocol-level errors — a consensus algorithm that can elect two leaders under a specific partition-and-recovery sequence, a cache invalidation scheme with a window where a stale value can be written back, a state machine with an unreachable-but-required transition.

What it does not catch: anything about your actual code. A verified design implemented incorrectly is still broken. Model checking raises your confidence in the idea, not the artifact.

#2. Jepsen: break a real system and check what it promised

Jepsen takes the opposite approach: run the real database on a real cluster, hammer it with many clients at once, then deliberately break things — cut the network between nodes, skew their clocks, kill processes. It records when every operation started and finished, and afterwards asks a precise question: is this recorded history even possible if the database really provided what it advertises? If no valid ordering explains what was observed, the promise was broken.

  1. 1 Generate concurrent random ops across clients
  2. 2 Nemesis partitions, pauses, clock skew, kills
  3. 3 Record invoke/complete times for every op
  4. 4 Check is this history linearizable? serializable?
Jepsen's loop. The checker is the clever part.

The checker (Knossos/Elle) searches for any one-at-a-time ordering of the operations that fits both the recorded start/finish times and the claimed model. Example: client 1's write of x=5 finished before client 2's read started, yet the read returned the old value. No one-at-a-time order of a linearizable store can produce that. If no valid ordering exists, the system violated its own guarantee, and Jepsen prints the specific operations that cannot be reconciled.

Failure classes it reliably finds:

AnomalyWhat it means
Lost updateAn acknowledged write vanished
Stale readA read returned a value older than a completed write
Dirty readA read saw an uncommitted, later-aborted write
Split-brainTwo nodes both believed they were leader and both accepted writes
Non-monotonic readsA client saw a value, then saw an older one
Phantom / G2 cyclesTransactions interfered in a way no one-at-a-time order could explain, despite a claimed "serializable" isolation level

The recurring lesson from Jepsen reports is not that databases are badly built. It's that (a) documentation routinely overstates guarantees, (b) default configurations are frequently weaker than the marketed level, and (c) the interesting bugs appear during recovery, not during the partition — when a healed node rejoins and reconciles.

#3. Deterministic simulation: the one that scales

The most practical technique for a team building its own system, and the least widely known.

Run the entire cluster — every node — inside one process on one thread, and replace everything that could vary between runs with a random generator driven by a single seed: the clock, the order messages arrive in, which node runs next, how slow the disk is, when failures happen.

The payoff is in that word seed. The same seed replays exactly the same run, so a bug found on run 4,318,201 can be reproduced on demand — which is the thing that makes distributed bugs fixable rather than merely observable.

   REAL SYSTEM                    SIMULATED SYSTEM

   wall clock                 →   virtual clock, advanced by the sim
   OS scheduler               →   deterministic task ordering from seed
   real network               →   in-memory queues, seed-chosen delays,
                                  reordering, duplication, partitions
   real disk                  →   in-memory model with injected latency,
                                  torn writes, and fsync failures
   random()                   →   seeded PRNG

   Consequences:

     · a whole cluster-hour runs in seconds — no real waiting
     · a failing run is reproducible EXACTLY from its seed
     · you can search millions of schedules, not a dozen

The two properties that matter:

Speed. Because there is no real waiting, simulated time advances as fast as the CPU can compute. A day of cluster operation with hundreds of failures can run in under a minute. You run millions of randomised scenarios overnight.

Reproducibility. A failure is a seed. Hand the seed to a colleague and they get a byte-identical failure. You can attach a debugger and step through the exact interleaving that broke it. Compare this to the usual distributed-systems debugging experience: a heisenbug (a bug that vanishes or changes when you try to observe it, because adding logging or a debugger changes the timing) that appeared once in staging three weeks ago.

FoundationDB is the canonical example — they built the simulator before the database, and credit it as the reason FoundationDB survived Jepsen without a single violation found. TigerBeetle, Antithesis, and several newer systems use the same approach.

#Choosing among them

TechniqueVerifiesCostFinds
Model checking (TLA+)The designDays to learn, hours to writeProtocol logic errors
Property tests + fault injectionYour code, shallowlyLowCommon ordering and retry bugs
Jepsen-style history checkingA running systemModerateConsistency-model violations
Deterministic simulationYour whole implementationHigh upfront, low ongoingNearly everything, reproducibly
Chaos engineering in productionThe real system + operationsOngoingOperational and dependency failures

They are complementary, and the ordering is roughly a maturity ladder. A useful default for a team building something with real correctness requirements:

  1. Write the invariants down first, in plain language. Half the value arrives here, before any tooling.
  2. Model-check the protocol if there is a novel coordination scheme. If you are using off-the-shelf Raft, someone already did this.
  3. Property-test with fault injection — this is cheap and catches the common retry, ordering, and idempotency bugs. See idempotency.
  4. Check histories against a model in integration tests.
  5. Deterministic simulation if you are building storage or consensus yourself, and you intend to maintain it for years.

#Exercise

#Check yourself

Why don't ordinary tests find most distributed bugs?Show answer
A bug needs a specific interleaving, a failure at a specific moment and specific state. The space is astronomically large, and CI explores about one path on a healthy network at one speed.
What does model checking (TLA+) verify, and what doesn't it?Show answer
It exhaustively explores every reachable state of a protocol specification and hands you a step-by-step counterexample when an invariant breaks. It verifies the design, not your code.
What did AWS report from using TLA+?Show answer
It found design bugs needing rare failure sequences that testing would likely never have caught and that would have lost data — and writing the spec was valuable even when it found nothing, because stating invariants exposed disagreements.
How does Jepsen decide a database broke its promise?Show answer
It runs the real system under concurrent clients while injecting partitions, pauses, clock skew and kills, records every operation's start and finish, then checks whether any valid ordering under the claimed model explains the history.
What are the recurring lessons from Jepsen reports?Show answer
Documentation overstates guarantees, default configurations are often weaker than advertised, and the interesting bugs appear during recovery, when healed nodes rejoin.
What is deterministic simulation, and what are its two big benefits?Show answer
Run the whole cluster in one process, replacing clock, scheduling, network, disk and randomness with a seeded generator. Simulated time runs far faster than real time, and any failing run replays exactly from its seed.
Why is deterministic simulation hard to adopt late?Show answer
Every call to the clock, randomness, threads or sockets must go through a substitutable abstraction; one stray call reintroduces nondeterminism. It has to be designed in from the start.

#What to carry forward

  • Distributed bugs need specific schedules; ordinary tests explore almost none of the space.
  • Model checking verifies the design. Cheap, actionable counterexamples, no guarantee about your code.
  • History checking verifies a running system against a claimed consistency model. Most violations show up during recovery, not during the partition.
  • Deterministic simulation turns "unreproducible heisenbug" into "here's the seed" — the highest-value technique, and the one you must design in from the start.
  • Whatever you use: state the invariants explicitly first. That step alone finds disagreements about what the system is supposed to guarantee.
00:00
/ 11m