The costliest bugs in a distributed system happen once and then refuse to happen again on request. A leader election that overlaps with an 800 millisecond disk stall can lose a write that a client was already told was safe. The logs record the lost write, and the on-call engineer can spend a week failing to reproduce it.
Unmesh Joshi’s article on deterministic simulation testing on martinfowler.com names the gap. Chaos testing and Jepsen-style frameworks find bugs well, and each bug they find still has to be reproduced before it can be fixed. When the fault schedule is unseeded and thread timing varies from run to run, the test runner cannot regenerate the execution that failed.
For a team running queues, replication, payments or orchestration, that gap costs data, reconciliation effort and customer trust. Deterministic simulation testing closes it by turning a rare interleaving into a test case that replays from a single number. It also demands a particular way of writing the system, and most of the work sits in that design.
Why rare interleavings escape staging
Distributed systems fail in the ordering of events. Three messages in flight arrive in 6 possible orders, and ten messages arrive in 3,628,800 orders. Each of those orders then combines with a crash, a partition, a slow disk write or a clock that has drifted 200 milliseconds.
Staging samples that space thinly. Take a planning figure, a defect that needs one specific interleaving and shows up once in 10 billion operations. A production service handling 50 million operations per day meets it about once every 200 days, while a staging cluster driven at 500 operations per second processes about 43 million operations per day and needs more than 230 days of continuous traffic to see it once.
Diagnosis carries the cost
When a rare failure occurs in production, the logs record the outcome and omit the schedule that produced it. Engineers rebuild the sequence from partial traces, add instrumentation, deploy it and wait for a recurrence that can take weeks. A fix shipped without a reproduction carries no proof that it works, and a test that passes after the fix may only mean the schedule changed.
Mature projects meet the same limit. The etcd maintainers described in a CNCF post on autonomous robustness testing how issues in the v3.5 release pushed them to strengthen testing of the datastore Kubernetes depends on. Skilled review, unit tests and staging leave a residue of interleavings that only systematic exploration reaches.
How deterministic simulation testing works
Deterministic simulation testing runs the production code of a distributed system inside a simulator that owns every source of nondeterminism. The simulator controls the clock, the random number generator, the network and the disks. It executes the whole cluster as state machines on one thread and drives them with workloads and faults derived from one seed.
FoundationDB built its database this way from the start. Its testing documentation describes a deterministic simulation of an entire cluster within a single-threaded process, built on the Flow actor runtime, with simulated machines, drives and network. The team runs tens of thousands of simulations every night, with faults such as “swizzle-clogging”, which randomly clogs and later unclogs network connections across a subset of nodes.
Invariants are checked continuously while the simulation runs. When one fails, the seed reproduces the failure exactly, on any machine, as many times as the investigation needs.
Inside and outside testing
Jepsen-style testing probes a running system from outside through its public API. It generates random operations, injects faults and checks whether the observed history satisfies a consistency model such as strict serializability. That gives it high fidelity to production and makes it excellent at finding violations users can observe.
Simulation tests from inside, with direct access to the state of every replica. TigerBeetle’s post on protocol-aware simulation gives a precise example. Every time a request commits on a replica, the simulator asserts that if the same request committed on another replica, their checksums match, which checks write-ahead log agreement on every request.
The two approaches find different defects, and teams with consequential data benefit from both. Antithesis sits between them, running whole systems inside a deterministic hypervisor and testing them through their external interfaces, as the same TigerBeetle post describes. Chaos engineering in production answers another question again, whether the deployed system and its operators survive real faults.
Fidelity and speed trade against each other
Deterministic simulation replaces the network and storage with simplified, controllable models. Because simulated time skips idle periods, it runs faster than real time and covers far more schedules per CPU hour than any real cluster. The fault model must be written deliberately, and any behavior the model omits stays untested.
That trade-off is the central engineering judgment in adopting the technique. A model that is too thin gives false confidence, and a model that tries to emulate every kernel and device detail loses the speed that made simulation worth building.
Design decides the outcome
The same TigerBeetle post notes that FoundationDB and Dropbox’s sync engine both used determinism in their design alongside simulation testing. TigerBeetle adds two properties. Logical determinism means all database code is deterministic and multithreaded concurrency is avoided in the control plane, and physical determinism means replicas converge to byte-identical state on disk.
Dropbox’s account of testing its sync engine states the rule its team followed. All randomized testing frameworks must be fully deterministic and reproducible from a seed, and a failing test prints that seed. Each of these properties came from architectural decisions made early, and retrofitting them into a system built on threads, wall-clock reads and direct socket calls costs more with every module that touches the outside world.
Five gates of simulation readiness
A component must pass five gates before simulation yields results the team can trust. The gates are ordered by dependency, so a failure at an earlier gate invalidates the later ones. Apply them as a review checklist to any service, new or existing.
Click to expand Gate 1 for controlled time
No code path reads the wall clock directly. All time comes from an injected clock interface, and every timer, timeout and retry is scheduled through it. In production the interface wraps the system clock, and in simulation it is a counter that the simulator advances to the next scheduled event.
Simulated time jumps over idle periods, so a 30-second election timeout costs microseconds of real time. The simulator also gives each node its own clock with configurable skew and drift. That exposes the lease and timeout bugs that appear only when nodes disagree about the time.
Gate 2 for controlled randomness
Every random choice in the system draws from a seeded generator that the simulator supplies. That includes retry jitter, election tie-breaks, identifier generation and sampling. The simulator derives workload, fault timing and message delays from one root seed, and the seed is the first line printed in every test log.
Derive an independent random stream for each component from the root seed. Then an engineer who adds a random call to the network model leaves the disk model and the workload generator unchanged. Recorded failing seeds keep replaying the failures they were recorded for.
Gate 3 for controlled input and output
Network and storage sit behind narrow interfaces. In production those interfaces call sockets and files, and in simulation they call a model that holds messages and disk operations in queues the simulator controls.
The network model delivers, delays, reorders, duplicates and drops messages, and it creates and heals partitions between arbitrary groups of nodes. The disk model returns errors, completes writes out of order, tears writes, corrupts blocks silently and writes to the wrong address. TigerBeetle generates partitions, disk corruption and replica crashes together with concurrent client operations, because many defects sit in the interactions between faults.
Gate 4 for single-threaded execution
The simulator runs the cluster as cooperating state machines on one thread, so the operating system scheduler cannot change the order of events. Hidden nondeterminism still slips in through hash map iteration order, pointer values used as keys, environment lookups, and third-party libraries that spawn threads or read their own clocks.
Checking for leaks is mechanical. Run the same seed twice and compare a hash of the full event trace, and any difference identifies a leak. Run this check in continuous integration from the first day, because leaks arrive quietly through dependency upgrades.
Gate 5 for invariants stated as executable checks
Simulation finds only the violations the checks can see. Safety invariants define what must never happen, and liveness invariants define what must eventually happen. A payment system might state them as follows.
- The sum of all ledger balances equals zero after every committed transaction.
- Every acknowledged write remains readable after any combination of crashes and recoveries.
- No two replicas commit different requests at the same log position.
- After faults heal and a majority of replicas are online, the cluster makes progress within a bounded simulated time.
Liveness checks deserve particular attention. TigerBeetle points out that a majority of replicas can give the appearance of availability while the rest are stuck, so it checks liveness for each replica. One of its rules is that a replica with an uncorrupted write-ahead log never needs to coordinate with the cluster to recover, since a cluster that restarts together and coordinates unnecessarily can stall.
A scorecard for choosing the component
Simulation costs engineering time. It pays back where a single defect is expensive, coordination logic is dense and the code already separates logic from I/O. Score each criterion 0, 1 or 2 for a total between 0 and 10.
Click to expand | Criterion | Score 0 | Score 1 | Score 2 |
|---|---|---|---|
| Cost of one lost, duplicated or reordered write | Recoverable by retry | Requires manual reconciliation | Financial, regulatory or contractual exposure |
| Density of coordination logic | None, stateless services | Queues or caches with replication | Consensus, leases, leader election or distributed transactions |
| Separation of logic from I/O | Direct socket, file and clock calls throughout | Partial interfaces | Clock, network and disk already behind interfaces |
| Unreproduced production incidents in the last 12 months | None | 1 to 2 | 3 or more |
| Ability to state invariants as executable checks | Cannot state them | Can state some informally | Can write them as assertions today |
A total of 7 to 10 justifies a dedicated simulation effort on the highest-scoring component. A total of 4 to 6 supports a pilot on one narrow component, such as a replication module or a payment state machine, and the pilot exposes the refactoring needs. A total of 0 to 3 means integration tests, chaos experiments and external consistency checking return more per engineering hour.
Where the technique fits
Consensus implementations, replicated storage engines, message queues with delivery guarantees, payment and ledger state machines, and workflow orchestrators with retry and compensation logic all score high. Stateless request handlers, user interface code and analytics jobs score low, and conventional testing serves them well. Machine Learning pipelines need golden datasets and drift checks for the models, while the orchestration layer that schedules them benefits from simulation like any other distributed component.
When to hold back despite a high score
A high score does not settle the decision on its own. Three situations argue against adopting the technique now.
The first is a component scheduled for replacement within a year, where the simulator’s value expires with the code. The second is a team with no engineer who will own the simulator, since an unowned simulator decays as the code moves on without it. The third is a core built on threads and blocking calls with no budget to extract the state machine, and in each case the money goes further on external consistency checking and controlled fault experiments.
A 30-day plan for the first simulated component
The plan targets one component of moderate size, such as a replication module or a job scheduler. Treat the day counts and seed volumes as planning figures and scale them to the codebase. Sequence matters most, because each phase produces what the next phase depends on.
Click to expand Days 1 to 7 for baseline and seams
Select the component with the scorecard. Write 5 to 10 invariants in plain language, then translate each into an assertion sketch. Inventory every call that reaches the clock, the random number generator, the network, the disk or a thread primitive.
The inventory is the refactoring backlog, and its length is the best available estimate of the remaining effort. Introduce interfaces for the 3 or 4 busiest seams first, with production implementations that preserve existing behavior. Existing tests pass unchanged at the end of the week, which gives the team a safe base for the rest of the work.
Days 8 to 14 for the simulator core
Build the event loop, the simulated clock, the seeded random streams and a basic network model that delivers messages with random delay. Run a cluster of 3 to 5 nodes under a simple workload with no faults and confirm the invariants hold. Then add the twice-run trace comparison from Gate 4 to continuous integration.
Aim to run 1,000 seeds in under 10 minutes on a standard CI runner, printing the failing seed for any run that breaks. If throughput falls well short, profile the simulator before adding features. Seed volume decides how much of the state space the effort covers.
Days 15 to 22 for fault injection and invariants
Add message reordering, duplication, loss and partitions, then node crashes and restarts with state recovered from the simulated disk. Add disk faults, including read errors, corrupted blocks and torn writes, and per-node clock skew. Introduce each fault class at a low rate and raise it in steps, so the system keeps making progress and the checks exercise recovery as well as failure.
Convert the written invariants into assertions that the simulator evaluates after every event. Then validate the checks by planting a known defect, such as a missing fsync or an off-by-one in quorum counting, and confirm simulation finds it within a few thousand seeds. A check that cannot catch a known bug will not catch an unknown one.
Days 23 to 30 for continuous integration and triage
Run 1,000 seeds on every pull request, 100,000 seeds nightly and a million or more over a long weekend run. Store every failing seed with its commit hash in a regression file, so each one replays as a permanent test. Assign an owner to triage failures within one working day, because an unattended failure queue erodes trust in the suite.
Close the month with a short review of seeds executed, defects found, how many of those production monitoring had never surfaced, and engineering time per defect, in the same spirit as production readiness reviews. Those figures give leadership the evidence to extend the approach to a second component.
Failure modes and their countermeasures
Most failed adoptions share a small number of causes. Each one shows up early and has a direct countermeasure.
Nondeterminism leaks back in
A dependency upgrade, a new helper that calls the system clock or a map iteration in a serialization path breaks reproducibility without any warning. Failing seeds stop replaying, and engineers lose confidence in the tool. Run the trace hash comparison from Gate 4 on every commit, and add a lint rule that forbids direct clock, thread and random calls outside the interface layer.
The fault model is too gentle or too harsh
Fault rates need calibration. A model that never corrupts a disk block never tests repair logic. A model that drops half of all messages never lets the system make progress, and both produce dashboards that carry no information. Track coverage counters for events such as elections, recoveries and repairs, so the team sees which behaviors the runs reached.
Invariants that cannot fail
Weak checks let a suite pass forever. Plant known defects at the start and repeat the exercise each quarter. If a planted bug survives 100,000 seeds, strengthen the invariants or the workload generator before trusting the pass rate.
The simulator diverges from production
Simulation checks the code against the model, and the model can be wrong. Jepsen’s 2025 analysis of TigerBeetle reports that the VOPR simulator initially missed a bug triggered by bit flips in padding, because it corrupted whole sectors, and TigerBeetle then changed it to inject single-byte errors. Keep external consistency checking in the program, and feed every production incident back into the model as a new fault type with a regression seed.
Retrofitting into thread-heavy code
A service whose core logic spans many threads and blocking calls resists simulation. The refactoring cost tends to exceed the first estimate by a wide margin, and partial determinism provides little value. Extract the state machine that makes the consequential decisions, simulate it, and leave the thread-heavy shell to conventional tests or a deterministic hypervisor.
What to do this week
Score the two or three components with the highest cost of failure. In the top scorer, count the direct clock, network, disk and thread calls to size the refactoring. Write its invariants as sentences a finance or operations leader can verify, and name one engineer to own a 30-day pilot.
Algorithmic builds production systems where a lost write has a price, and our record across more than 35 complex engagements includes zero production outages. A founder leads every engagement, and we can review your highest-scoring component, map its seams and size the simulator with your team. Start a conversation and send us the component you scored first.