Chapter 10 / 10 · Distributed Systems

Breaking it on purpose

Turning the wallet’s guarantees into checks, then trying to break them with recorded histories, injected faults, simulation and model checking.

This chapter lets you turn the wallet’s guarantees into checks a machine can run, and choose testing methods by the kinds of bugs each can find. The aim is to find the failure paths that are wrong before a partition in production finds them for you.

Over nine chapters we have made claims about the wallet. An acknowledged transfer is never lost. A retry never moves money twice. Money is conserved across shards. A balance never goes below zero. A read after “Sent” shows the new balance. Every one of those claims was argued in prose, and prose arguments have gaps. The bugs that slip through those gaps tend to need several unlikely things at once: a partition during an election while one server is paused. Unit tests do not produce that combination, and waiting for production to produce it is expensive.

Write the guarantees down as checks

The first step is to restate each claim as something a program can check against what the system did. Most fall into one of two families. Safety properties say that nothing bad ever happens, and a single counterexample disproves them. Liveness properties say that something good eventually happens, and they can only be checked with a time bound.

For the wallet, the safety properties are concrete. At every consistent snapshot, the sum of all balances plus all in-transit accounts equals the starting total plus top-ups minus withdrawals. No balance is ever observed below zero. Every transfer that a client saw acknowledged appears exactly once in the ledger. Every read that started after a transfer was acknowledged reflects it. The liveness property is that, once faults stop, every pending saga reaches completed or refunded within, say, two minutes.

Writing these down usually exposes a vague claim. “No transfer is lost” is ambiguous until you say what to do with transfers whose outcome the client never learned. Those are the timeouts from the first chapter. A correct checker must allow them either to have happened or not, but not both, and not twice.

Record a history, then check it

The approach Kyle Kingsbury’s Jepsen made widely known is to test the system the way it is used, from the outside, while breaking its environment. Several client processes run a workload against a real cluster. A separate component, which Jepsen calls the nemesis, injects faults: it cuts network links, kills processes, pauses them, and skews their clocks. Every operation is recorded with its start, its end, and its outcome: succeeded, failed, or unknown. At the end, a checker examines the whole history against the properties.

Jepsen has a workload that is almost exactly our wallet. It is called bank: clients make transfers between a handful of accounts and read all balances at once, and the checker verifies that every read sees the same total and no negative balance. Jepsen analyses of several databases that claimed snapshot isolation have found exactly these violations under partitions and process pauses.

The unknown outcomes need care in the checker. A transfer whose client timed out is recorded as indeterminate, and the checker must consider both histories, the one in which it happened and the one in which it did not, accepting the run if either is consistent. For a simple invariant such as the bank total, that is easy. For linearizability, where the checker searches for some order of all operations consistent with what every client observed, each indeterminate operation multiplies the orders to consider, and the general problem is computationally hard. Checkers such as Jepsen’s Knossos and the Porcupine library cope by checking each key independently and keeping histories short, which is one reason these tests use a handful of accounts rather than millions. The small scale is a deliberate choice: it raises contention, which makes violations more likely, and keeps the checking feasible.

Predict first

We run a bank-style test against the wallet for ten minutes, with the nemesis partitioning the network every thirty seconds. At the end, the total across all accounts equals the starting total. Does that show the wallet conserves money?

Show the worked answer

No, for three reasons. First, a final total only checks the end. A read in the middle of the test might have seen Ravi’s credit without Asha’s debit, a total ₹500 too high. That is a real bug, since a statement generated at that moment would be wrong, and the final check cannot see it. The checker has to examine every read.

Second, errors can cancel. A transfer lost in one partition and a different transfer applied twice in another leave the total unchanged. Checking that each acknowledged transfer appears exactly once catches what the sum misses.

Third, the test only explores the faults it injected. If the bug needs a process pause during an election, and the nemesis only partitions, ten minutes or ten hours will not find it. A passing test says the system survived these faults, in these timings, this time.

Here is the kind of bug such a test finds. The nemesis pauses the wallet’s Raft leader for twelve seconds with SIGSTOP. The other two replicas elect a new leader, which commits several transfers, including one of Asha’s, and acknowledges them. The nemesis resumes the old leader. Just before it was paused, it had received a balance read, checked that its leader lease was valid, and gathered Asha’s balance. Now it sends that reply. The client, whose read began after Asha’s transfer was acknowledged, receives ₹2,000. The checker flags a read that missed an acknowledged write.

This is the coordination chapter’s check-then-act gap again, inside the read path. The lease was valid when checked and expired before the reply left. Possible fixes are to check the lease again after assembling the reply, with a margin larger than any expected delay before sending, or to use a read index, which confirms leadership with a majority round trip per read or batch of reads. The first is cheap and narrows the window; the second closes it and adds latency. The test is what makes that tradeoff visible at all.

Inject faults into the real system

The nemesis’s tools are ordinary Linux facilities, and they are worth knowing because the same tools work in a staging environment and in a game day. iptables rules drop traffic between chosen machines, including in one direction only, producing the asymmetric partition where A can hear B but B cannot hear A. tc netem adds latency, jitter and packet loss. kill -9 crashes a process without cleanup. SIGSTOP and SIGCONT pause and resume it, which is the closest imitation of a long garbage-collection pause. Clock skew can be injected by setting a machine’s clock directly or by intercepting time calls with a library such as libfaketime. Slow disks can be simulated with a device-mapper target that delays I/O.

Some faults are realistic only in production, because staging lacks its traffic, data volume and network topology. Chaos engineering, as described in the Principles of Chaos Engineering, runs fault experiments there under strict rules. State a hypothesis in terms of a steady-state metric users would notice, such as “transfers completed per minute stays within 5 percent when one wallet replica is killed”. Limit the blast radius to one replica, one shard, or a small share of traffic. Keep an abort switch. Expand only when the hypothesis holds.

The largest single experiment for the wallet is a data-centre failover. If it was last run at launch, the configuration, the runbook and the people have all changed since. A failover that has not been rehearsed recently should be treated as untested, and rehearsing it on a schedule, with the steady-state metric watched throughout, is how teams find that the DNS record has a one-hour time-to-live or that the standby lacks a new table.

Deterministic simulation: the bug you can replay

Fault injection against a real cluster has a frustrating property. When it finds a bug that depends on exact timing, rerunning the test usually does not reproduce it. Deterministic simulation testing removes that problem by removing every source of randomness the test does not control.

The system is written so that all interactions with the outside world, the network, the disk, the clock, random numbers and the scheduling of concurrent tasks, go through interfaces. In production, the interfaces call the real operating system. In testing, a simulator implements them, running every replica of the wallet in a single process on a single thread, with a random number generator seeded from one integer. The simulator decides when each message is delivered, dropped or duplicated, when each disk write completes or is torn, and what time each node’s clock reports.

for seed in 1..1_000_000:
    sim = Simulator(seed)
    wallet = sim.start_cluster(replicas=3, shards=4)
    sim.run(workload=random_transfers,
            faults=random_partitions_crashes_pauses,
            steps=50_000)
    if not sim.check_invariants():
        report(seed)    # rerunning this seed reproduces the run exactly

Because everything flows from the seed, a failing run can be replayed exactly, step by step, under a debugger, as many times as needed. Because simulated time does not wait for real time, a simulated hour in which nodes sleep on timeouts can pass in seconds, and a farm of machines can explore millions of seeds overnight. FoundationDB’s team built their simulator before the database itself and credit it for the database’s reliability; TigerBeetle, a financial ledger database, runs a similar simulator continuously.

The cost is architectural. Every source of nondeterminism must go through the interfaces, including those inside third-party libraries, and a library that opens its own sockets or reads the clock directly breaks the property. The simulator also only produces faults it was written to produce; a disk that silently returns stale data after a power loss will not appear unless someone modelled it. This is a decision to make early in a system’s life. Adding it to an existing codebase is possible but slow.

Cheaper tests that catch most retry bugs

Not every bug needs a cluster and a nemesis. A large share of the bugs in this pathway are in idempotency and retry handling, and those can be tested in an ordinary integration suite by making the network misbehave in targeted ways.

Put a fault-injecting proxy, such as Toxiproxy, between the API and the wallet in the test environment. Then write tests for each case from the first chapter. Drop the request before it reaches the wallet, and check that a retry with the same key moves the money once. Let the request through and drop the reply, and check the same. Delay the request until after the caller’s deadline, and check that the wallet refuses to start it. Send the same request twice at the same moment, from two threads, and check that exactly one transfer exists and both callers receive the same answer. Send the same key with a different amount, and check for the key-conflict error.

Each of those tests is short, deterministic and runs in seconds. Together they cover the bugs that produced the double charges on the slow afternoon. They would also have caught the colleague’s separate check-then-insert version in the RPC chapter, because the concurrent test makes both requests pass the check.

Property-based testing extends this. Instead of writing individual scenarios, the test generates random sequences of operations, such as transfers, retries, duplicated deliveries and restarts of a consumer, runs them against the code, and checks the invariants after each sequence. When a sequence fails, the framework shrinks it to the shortest sequence that still fails, which often reads like a bug report: transfer, deliver event, restart consumer, deliver event again, history shows two rows. This sits between hand-written tests and full simulation, and it is cheap to adopt in an existing codebase.

Check the design before the code exists

Some bugs are in the design rather than the code. A saga whose compensation can run while a retry of the forward step is still in flight is wrong however carefully it is implemented. For the few protocols at the centre of the system, a formal specification finds these before any code is written.

In TLA+, we describe the saga as a state machine: the variables (balances, in-transit accounts, each transfer’s status, messages in flight), the actions that change them (debit, deliver an event, credit, compensate, crash, duplicate a message), and the invariants that must hold in every reachable state. The TLC model checker then explores every possible ordering of those actions for a small instance, perhaps three accounts, two concurrent transfers and one crash, and if any ordering breaks an invariant, it prints the exact sequence of steps that does so.

Engineers at Amazon described this in a 2015 article on their use of formal methods. Model checking found serious bugs in designs for DynamoDB and other services, one of which needed a sequence of 35 steps to trigger, far beyond what testing or review would plausibly hit. The limitation is the gap between specification and code: the model checker proves things about the design, and the implementation can still diverge from it.

Choosing what to use

TechniqueWhat it findsWhat it missesWhat it costs
History checking under faultsReal violations in the real binaryFaults and timings it never producedA test cluster, a nemesis, a checker
Fault injection and chaosOperational gaps: timeouts, runbooks, configRare interleavings; hard to reproduceCareful experiment design; production risk
Deterministic simulationRare interleavings, with exact replayFaults the simulator does not modelArchitecture built around it from early on
Model checkingDesign flaws in protocolsImplementation bugs; anything outside the modelLearning a specification language; keeping the spec current

These complement each other. Model checking finds problems in the saga’s design. Simulation finds the interleavings in our implementation of it. History checking confirms that the database underneath behaves as its documentation claims. Chaos experiments confirm that the deployed system, with its real configuration and runbooks, recovers as planned.

How much is enough

The effort should follow the code you own and the cost of being wrong. A service that stores user preferences in a managed database inherits most of its correctness from that database; checking its own retry logic with fault injection is probably enough. The wallet owns its idempotency handling, its saga, its fencing and its read path, and an error in any of them moves money. That justifies history checking in continuous integration and a model of the saga, and, if the team is building the replication layer itself, simulation from the start.

Revisit the level whenever a new protocol enters the system, such as a new kind of cross-shard operation, and after any incident whose cause was in a failure path. An incident is evidence that the existing tests did not explore that path, and the first change after it should be a test that would have caught it.

That completes the wallet: a transfer that survives timeouts, replicas that agree, a leader that can be replaced, ownership that is fenced, transfers across shards that stay conserved, and tests that try to break all of it. The next pathway, System Design, takes these tools up a level and applies them to whole products, where the question becomes which of them a given feature needs at all.