SENIORCHAPTER 19

Testing across services: fault injection and deterministic simulation

A timeout is not a failure, it is a question you cannot answer. Make the provider fail on demand, then let one seed explore the failures you would never think to combine

55 MINSOFTWARE TESTING AND QUALITYUPDATED 2026-11-24
PREDICT

Ojaline's checkout client waits 2 seconds for the provider. The provider receives a charge, takes 3 seconds, creates the charge and answers. place_order raised PaymentUnavailable at the 2 second mark. When it returns, what is true? Pick the best description.

Two services that talk over a network have a property that one service on one machine lacks: a call can fail in a way that tells you nothing. Inside a process a function either returns or raises. Across a wire a request can be lost, the work can be done and the answer lost, or the work can be done late. The caller sees one symptom for all three: silence, then a timeout.

This chapter is about testing code that lives with that uncertainty. It has two halves. The first is fault injection: make the provider misbehave on demand, one fault at a time, and assert what your code does. The second is deterministic simulation: let a seeded random generator combine faults, delays and retries into thousands of worlds, check what must be true in every one, and replay any bad one from its seed.

You already have the pieces. The fakes chapter built doubles and said what each one cannot promise. The API and contract chapter held the lab’s fake provider to its contract. The database chapter separated rollback from compensation, and named the gap this chapter fills: a failure in the middle of a flow that no raised exception can model. The flaky tests chapter showed the idempotency race with two threads and a lucky timing. Here you find the same class of bug without luck.

What place_order does when the provider does not answer

Read checkout/orders.py once more with failure in mind. The flow is: look up the idempotency key, price the cart, reserve the stock, charge, save the order. The reserve and the save are database writes that commit on their own. The charge is a network call between them, and it is the only step whose result can be unknown.

reserve_all(db, lines)
paid = False
try:
    charge = payments.charge(idempotency_key, quote.total, idempotency_key)
    if charge.status != "succeeded":
        raise PaymentDeclined(charge.code)
    paid = True
finally:
    if not paid:
        release_all(db, lines)      # compensation: give the stock back
order = db.save_order(...)

PaymentsClient turns a timeout, a connection error and any 5xx into one exception, PaymentUnavailable. A decline is not an exception at the client; it comes back as a ChargeResult with status declined, and place_order raises PaymentDeclined. The API maps the first to 502 and the second to 402. So the code distinguishes a no (decline: we know no money moved) from a don’t know (unavailable: we do not). That is the right split. What a test must establish is that each branch leaves the world in a state you can defend.

For one order there are three things you can look at afterwards, and a test of a failure should look at all of them:

Where What to read How
Our database, orders Is there an order for this key? db.count_orders() or db.find_order_by_key(key)
Our database, stock Was stock taken and not returned? db.stock_of(product_id)
The provider How many charges does it hold? GET /_admin/stats, which returns {"charges": n}

A test that checks only “it raised PaymentUnavailable” has checked nothing about money. The raise is the symptom. The three numbers are the state.

Fault injection: make the failure happen on demand

The lab’s fake provider (fake_provider/app.py, port 8095) has five modes. The mode is chosen, highest priority first, by the X-Fake-Mode request header, then by the mode set with POST /_admin/mode, then by FAKE_PROVIDER_MODE, then ok. Each mode is a fault you can inject without touching the code under test. For each one, write down what must be true afterwards before you write the test. That list is the specification.

Mode What the provider does Order Stock Charges held
ok 201 with a charge created taken 1
decline 402, card_declined none all back 0
500 500, internal_error none all back 0
slow answers ok after FAKE_PROVIDER_SLOW_S (1.0 s) created, if the client waits long enough taken 1
timeout hangs 30 s none all back 0

Two details in the table matter.

First, slow is two different faults. If the client’s timeout is 2.0 s and the provider takes 1.0 s, the slow answer is a success that costs a second. If the client’s timeout is shorter than the delay, the client gives up while the provider is still working, and then, because the fake carries on after its sleep, the charge is created anyway. The same mode makes a harmless delay or the Friday evening in the Why, depending on one number on the client side. A suite that only runs slow with a patient client has not tested the dangerous half.

Second, timeout mode never charges. It hangs and does nothing. That is a legitimate fault (the request was lost on the way in), but it is only one of the two ways silence happens. The other, where the work is done and the answer is lost, you get from slow with an impatient client. Name which fault you injected. “The provider timed out” is not one fault.

Run the real client

Inject the fault under the real PaymentsClient, over real HTTP, to a real running fake provider, not into a stub above it. Then the client’s own code runs: its timeout, its mapping of 5xx to PaymentUnavailable, its reading of the 402 body. A stub that raises PaymentUnavailable skips all that, and the fakes chapter explains why that matters.

The cost is time. A real timeout is real seconds. The test cannot make the provider hang for 30 s and wait for the client’s default 2 s, so give the client a short deadline for the test (0.3 s) and keep the provider’s slow delay slightly above it (0.6 s). That is a design choice: set the knobs that make the faults fast, and say so in the test, because a reader who sees timeout_s=0.3 will otherwise think it is a typo.

Start the provider as a subprocess in a session fixture, so the test owns it. One trap: do not stop it politely. A request in timeout mode is still asleep inside the server, and a graceful stop waits for it for up to 30 s. Kill it, since a fake provider has nothing worth saving. The lab step shows both the fixture and the trap.

The answer that arrives after the client gave up

The most useful test in this half is the one from the Why. Put the provider in slow mode, give the client a deadline shorter than the delay, and call place_order. Read the three numbers straight after it raises:

  • Our side: no order, stock back at 100. Correct: nothing happened as far as we know.
  • The provider: wait a moment, then charges is 1. The charge exists.

That state is the bug in the Why. Money has moved and there is no order. Nothing in the code can fix it from inside this call, because the code does not know. What the system can do is make the retry safe. The shopper tries again with the same idempotency key. The provider recognises the key and returns the existing charge with status 200 instead of creating a second one. place_order finds no order for the key, reserves the stock again, receives the old charge, and saves the order. The test asserts that the second attempt creates one order, takes the stock once, and the provider still holds one charge.

That is the contract of an idempotency key, tested at the seam where it matters: not “calling twice returns the same result”, but “calling again after an unanswered call repairs the state”. The idempotency chapter in the Payments course explains why providers offer it. What is left is the shopper who never retries: a charge with no order, for ever. That case has no unit test. It is found by a reconciliation job that compares the provider’s charges with your orders, which the Testing money chapter builds. For now, name the gap.

Where one fault at a time stops being enough

The five modes and the three numbers give you a tidy table. Now count what the table leaves out.

A real checkout sees a sequence of calls, not one. A shopper retries after a timeout. A second tab sends the same order. The provider is fine for the first call and slow for the second. A reply is late by 0.2 s on one attempt and by 5 s on the next. For three attempts across five outcomes there are already 125 sequences, and the order in which different shoppers’ calls interleave multiplies that again. You will not write 125 tests, and you would not think of the ones that matter.

Fault-injection tests are examples chosen by a person. They are good at the faults you can name. They are poor at the combinations you cannot, and at timing, because a test that runs one call from start to finish never has a second request arrive in the middle of the first. That is exactly the shape of the check-then-act race you made fail on demand in the concurrency chapter, and met first in the flaky tests chapter: two requests with one key, and the second looks up the key before the first has saved. With real threads you hit it by luck and see a rate. You want to hit it on purpose, and to rerun it exactly.

Deterministic simulation

A simulation takes control of everything that makes a run vary and puts it behind one number.

  • Randomness. Every choice (which shopper goes next, what the provider does to a charge) comes from one random.Random(seed).
  • Time. Waiting is not real. The lab’s FakeClock advances when a call “waits”, so a 30 s provider outage costs no time at all.
  • Scheduling. Which event happens next is decided by the generator too, not by the operating system.

With those three owned, the same seed produces the same world, every time, on every machine. A failure is then a seed, and a seed is a bug report: send the number, and the receiver replays the failure and steps through it. The approach was described and used at scale by the FoundationDB team; Will Wilson’s 2014 talk in the reading list is the best introduction. FoundationDB’s documentation says its simulation runs tens of thousands of simulations every night, each with large numbers of component failures, which is only possible because no simulation waits for anything real.

▶ SIMULATION
NODE A (PRIMARY)
x = 0
last seq applied: 0
SCHEDULER
mode: arrival order
pending: w1 w2
NODE B (FOLLOWER)
x = 0
last seq applied: 0
trace—
✓ when the queue is empty, follower B holds the same value as primary A
SCHEDULE
01[SIM]a quiet network: messages arrive in order
02[SCHED]scheduler: pick event 1 of 4 from the queue
03[SCHED]scheduler: pick event 2 of 4 from the queue
04[SCHED]scheduler: pick event 3 of 4 from the queue
05[SCHED]scheduler: pick event 4 of 4 from the queue
Start of laptop: fifo scenario. 5 steps.
// Follower: apply replication messages in arrival order
function onRepl(msg) {
  this.x = msg.v;        // an older message arriving late overwrites a newer one
}

// Test scheduler: the real network and the OS pick the order
// (so the bad order may appear once in thousands of runs)

Watch the scheduler in the simulation. On a quiet network, with messages delivered in order, the bug never shows. Under a random order, some seeds expose it and some do not, and the same seed always lands on the same side. The simulation proves two things. The bug needs a particular interleaving, which a human rarely writes. And once a seed has found it, the failure stops being luck: you can run seed 7 again and watch the same events happen in the same order. The lesson has the mechanism in full; the lab builds the same shape for place_order.

What the lab’s simulator decides

The lab simulator, tests/sim_checkout.py, replaces the provider with an in-memory model, SimProvider, that dedupes by idempotency key like the real one. For each charge the seed picks a fate:

Fate What happens
ok The charge is made and the reply arrives.
decline, 500 A no, or an error. No charge.
drop_request The request is lost. The clock advances 2 s; the client times out. No charge.
drop_reply The charge is made, the reply is lost. The clock advances 2 s; the client times out.
late The charge is made after a delay of 0.2 to 6.0 s. If the delay is over 2 s the client has already given up.
retry_in_flight While this charge is being handled, the shopper’s retry arrives with the same key.

Four shoppers each try to buy Aso-oke caps (stock 5, so stock can run out), retry up to three times when they get PaymentUnavailable, and are scheduled in an order the seed chooses. The place_order under test is the real one, with a real SQLite file. Only the provider and time are simulated.

The last fate is the one that earns the simulator its place. A single thread cannot run two requests at once, but the simulator does not need two threads. It needs the second request to arrive inside the first one’s call to the provider, which is where the real race window is. The provider model calls place_order again with the same key at that point. Order of events is then decided by the model, not by the scheduler of the operating system, and the interleaving is reproducible.

Assert invariants, not outputs

A simulation produces a different world per seed, and you cannot write the expected result of each. So you do not check outputs. You check invariants: statements that must hold in every world, whatever happened. The lab checks these after every run:

  1. At most one order per idempotency key.
  2. At most one order per charge: a charge pays for one order.
  3. Every order’s charge exists at the provider. No order without money.
  4. Stock taken from the shelf equals the units on the orders. No stock lost, none invented.

Notice what is not on the list: “the shopper always gets an order”. With a provider that drops three replies in a row, a shopper rightly gives up. A charge with no order is then possible, and the simulation allows it, because a reconciliation job and not place_order owns that case. An invariant must be true of correct code in every world, or the simulation fails on a world that is not a bug, and people stop reading it. Choosing the invariants is the real work. The generator is thirty lines.

What a simulation cannot tell you

A simulation finds bugs in your code against the faults you modelled. Three limits follow.

The model can be wrong. SimProvider is a double, with the double’s disease: it is a copy of the provider in somebody’s head. If the real provider sometimes answers 200 and then declines on settlement, the model does not know. Keep it honest the way the fakes chapter taught: hold it to the contract in fake_provider/contract.json, and add a fate every time an incident shows you one you had not imagined.

It is not a proof. Three hundred clean seeds say that 300 worlds were fine. The number of worlds you can explore is a budget, not a guarantee. Look at how it is spent: if 90% of fates are ok, most worlds are boring, so weight the fates toward trouble. Report the seed count with the result.

It sees only what you let it control. Anything outside the seed (a real thread, time.time(), an unseeded random.random()) makes runs differ again and the replay stops working. The simulator’s first test is therefore that the same seed gives the same trace twice. If that test is ever red, nothing else it says can be trusted.

Retries deserve a sentence. The shoppers in the simulation retry, and that is deliberate, because real clients do. The Retries hide the bug lesson showed what a retry does to a test: it turns a failure into a pass and hides the rate. In a simulation the retry is part of the system under test, and the invariants judge the end state after all of it. That is the right place for a retry. Its cousin, eventual consistency in assertions, applies when a check must wait for a system to settle: in a simulation you do not wait, you run the clock until nothing is left to happen, then check.

LAB Make the provider fail, then let a seed find what you did not ~50 MIN
YOU NEEDPython 3.9+ with the lab set up (README, 'Set up')labs/testing, with .venv createda free port: the documented provider port is 8095; if lsof shows it taken, use 8195

You will test place_order against the live fake provider in four modes and in the late-answer case, watch the late charge by hand, then build the simulator, let it find a duplicate-order race, replay the failing seed, fix it, and break the compensation to see what the invariants say. Work from labs/testing. The tests use temporary databases, so data/ is untouched. Check the ports first:

cd labs/testing
lsof -i :8094 -i :8095
export CHECKOUT_DB="$PWD/data/lab-scratch.sqlite"
Nothing from lsof if both are free. If 8095 is taken by another lab or terminal, pick 8195 and use FAULT_PROVIDER_PORT=8195 in every command below, and --port 8195 for the provider in step 2. CHECKOUT_DB is a path the tests never open; it keeps any app that starts by accident away from your real data.

1. Drive the live provider through its modes. Create tests/integration/test_provider_faults.py. It starts the provider as a subprocess, sets its slow delay to 0.6 s, and uses a client that waits only 0.3 s unless a test says otherwise:

"""place_order against the real fake provider, driven through its modes."""

import os
import socket
import subprocess
import sys
import time
from pathlib import Path

import httpx
import pytest

from checkout.orders import PaymentDeclined, place_order
from checkout.payments_client import PaymentsClient, PaymentUnavailable

PORT = int(os.environ.get("FAULT_PROVIDER_PORT", "8095"))
BASE = f"http://127.0.0.1:{PORT}"
ITEMS = [{"product_id": 2, "qty": 3}]  # 3 x Shea butter, stock 100

@pytest.fixture(scope="session")
def provider_process():
    env = dict(os.environ, FAKE_PROVIDER_SLOW_S="0.6")
    cmd = [sys.executable, "-m", "uvicorn", "fake_provider.app:app", "--port", str(PORT), "--log-level", "warning"]
    proc = subprocess.Popen(cmd, cwd=Path(__file__).resolve().parents[2], env=env)
    for _ in range(100):
        try:
            socket.create_connection(("127.0.0.1", PORT), timeout=0.1).close()
            break
        except OSError:
            time.sleep(0.05)
    else:
        proc.kill()
        pytest.fail(f"the fake provider did not start on port {PORT}")
    yield proc
    proc.kill()  # not terminate: a request in timeout mode is still sleeping and would hold a graceful stop for 30 s
    proc.wait(timeout=5)

@pytest.fixture
def provider(provider_process):
    httpx.post(BASE + "/_admin/reset")
    yield
    httpx.post(BASE + "/_admin/reset")

def charges_made():
    return httpx.get(BASE + "/_admin/stats").json()["charges"]

def set_mode(mode):
    httpx.post(BASE + "/_admin/mode", json={"mode": mode}).raise_for_status()

def client(timeout_s=0.3):
    return PaymentsClient(BASE, timeout_s=timeout_s)

def wait_until(condition, timeout_s=3.0, what="condition"):
    deadline = time.monotonic() + timeout_s
    while time.monotonic() < deadline:
        if condition():
            return
        time.sleep(0.02)
    raise AssertionError(f"timed out after {timeout_s} s waiting for {what}")

def test_ok(provider, db, clock):
    order, created = place_order(db, client(), clock, ITEMS, "k-ok")
    assert created and order["status"] == "paid"
    assert db.stock_of(2) == 97
    assert charges_made() == 1

def test_decline_leaves_no_order_and_all_the_stock(provider, db, clock):
    set_mode("decline")
    with pytest.raises(PaymentDeclined):
        place_order(db, client(), clock, ITEMS, "k-decline")
    assert db.stock_of(2) == 100
    assert db.count_orders() == 0
    assert charges_made() == 0

def test_500_leaves_no_order_and_all_the_stock(provider, db, clock):
    set_mode("500")
    with pytest.raises(PaymentUnavailable):
        place_order(db, client(), clock, ITEMS, "k-500")
    assert db.stock_of(2) == 100
    assert db.count_orders() == 0
    assert charges_made() == 0

def test_slow_but_inside_the_timeout_still_succeeds(provider, db, clock):
    set_mode("slow")  # answers after 0.6 s
    order, _ = place_order(db, client(timeout_s=2.0), clock, ITEMS, "k-slow")
    assert order["status"] == "paid"
    assert db.stock_of(2) == 97

def test_timeout_mode_gives_up_and_puts_the_stock_back(provider, db, clock):
    set_mode("timeout")  # the provider hangs for 30 s
    started = time.monotonic()
    with pytest.raises(PaymentUnavailable):
        place_order(db, client(timeout_s=0.3), clock, ITEMS, "k-timeout")
    assert time.monotonic() - started < 2.0
    assert db.stock_of(2) == 100
    assert db.count_orders() == 0

def test_the_provider_answers_after_the_client_gave_up(provider, db, clock):
    set_mode("slow")  # the provider takes 0.6 s; this client waits 0.3 s
    with pytest.raises(PaymentUnavailable):
        place_order(db, client(timeout_s=0.3), clock, ITEMS, "k-late")
    assert db.stock_of(2) == 100 and db.count_orders() == 0   # our side: nothing happened
    wait_until(lambda: charges_made() == 1, what="the late charge")  # their side: a charge exists

    set_mode(None)  # the retry, with the same key, finds a healthy provider
    order, created = place_order(db, client(timeout_s=2.0), clock, ITEMS, "k-late")
    assert created
    assert db.count_orders() == 1
    assert db.stock_of(2) == 97
    assert charges_made() == 1  # the provider recognised the key: still one charge
FAULT_PROVIDER_PORT=8095 .venv/bin/pytest tests/integration/test_provider_faults.py -v
lsof -i :8095
6 passed in 2.19s, in whatever order the shuffle chose, with every test on its own line as PASSED. The whole file takes about two seconds, not the thirty the timeout mode would suggest, because the client’s deadline is 0.3 s. lsof prints nothing: the fixture killed the provider. The wait_until helper is the polling wait from the flaky tests chapter, because the late charge appears on the provider about 0.3 s after the client gave up, and a sleep would be a guess.

2. Watch the late charge by hand. The test asserts that the provider holds a charge the client never heard about. See it yourself with two terminals. In the first:

FAKE_PROVIDER_SLOW_S=0.6 .venv/bin/uvicorn fake_provider.app:app --port 8095

In the second:

curl -s localhost:8095/_admin/stats; echo
curl -s -X POST localhost:8095/_admin/mode -H 'Content-Type: application/json' -d '{"mode":"slow"}'; echo
curl -s --max-time 0.3 -X POST localhost:8095/v1/charges -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: late-1' -d '{"reference":"late-1","amount_kobo":902500}'; echo "curl exit: $?"
curl -s localhost:8095/_admin/stats; echo; sleep 1; curl -s localhost:8095/_admin/stats; echo
curl -s -X POST localhost:8095/_admin/mode -H 'Content-Type: application/json' -d '{"mode":null}'; echo
curl -s -X POST localhost:8095/v1/charges -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: late-1' -d '{"reference":"late-1","amount_kobo":902500}' -w ' [%{http_code}]\n'
curl -s localhost:8095/_admin/stats; echo
{"charges":0}, then {"mode":"slow"}. The charge request prints nothing and curl exit: 28 (curl’s code for its own timeout). Straight after, {"charges":0}: the provider has not finished. A second later, {"charges":1}: it did the work anyway. After clearing the mode, the same key returns the existing charge with [200] and the stats still say {"charges":1}. That is the idempotency key doing its job. Stop the provider with Ctrl-C in the first terminal.

3. Build the simulator. Create tests/sim_checkout.py. It is about 110 lines and every line is on this page:

"""A deterministic simulation of checkout against a misbehaving provider.

One seed decides everything: which shopper goes next, what the provider does to each
charge, how long it takes. FakeClock stands in for waiting, so a 30 s outage costs nothing.
"""

import random
import sys
import tempfile
from datetime import datetime, timezone
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from checkout.clock import FakeClock  # noqa: E402
from checkout.db import Database  # noqa: E402
from checkout.inventory import OutOfStock  # noqa: E402
from checkout.orders import PaymentDeclined, place_order  # noqa: E402
from checkout.payments_client import ChargeResult, PaymentUnavailable  # noqa: E402

TIMEOUT_S = 2.0
SAFE_FATES = ["ok", "ok", "ok", "decline", "500", "drop_request", "drop_reply", "late"]
ALL_FATES = SAFE_FATES + ["retry_in_flight"]

class SimProvider:
    """An in-memory provider. The seeded rng picks each call's fate; it dedupes by key like the real one."""

    def __init__(self, rng, clock, log, fates):
        self.rng, self.clock, self.log, self.fates = rng, clock, log, fates
        self.by_key = {}  # idempotency key -> charge id
        self.in_flight = None  # set by the world: what a retry arriving mid-call does

    def _charge_once(self, key):
        if key not in self.by_key:
            self.by_key[key] = "ch_%04d" % (len(self.by_key) + 1)
        return self.by_key[key]

    def charge(self, reference, amount_kobo, idempotency_key):
        fate = self.rng.choice(self.fates)
        self.log.append(f"{self.clock.now():%H:%M:%S} {idempotency_key}: provider fate {fate}")
        if fate == "decline":
            return ChargeResult("", "declined", "insufficient_funds")
        if fate == "500":
            raise PaymentUnavailable("provider returned 500")
        if fate == "drop_request":  # the request never arrives; the client waits out its timeout
            self.clock.advance(seconds=TIMEOUT_S)
            raise PaymentUnavailable("provider timed out")
        if fate == "drop_reply":  # the charge happens; the answer is lost
            self._charge_once(idempotency_key)
            self.clock.advance(seconds=TIMEOUT_S)
            raise PaymentUnavailable("provider timed out")
        if fate == "late":  # the charge happens after a delay; maybe longer than the client waits
            delay = round(self.rng.uniform(0.2, 6.0), 1)
            charge_id = self._charge_once(idempotency_key)
            self.clock.advance(seconds=min(delay, TIMEOUT_S))
            if delay > TIMEOUT_S:
                raise PaymentUnavailable("provider timed out")
            return ChargeResult(charge_id, "succeeded")
        if fate == "retry_in_flight" and self.in_flight:  # the shopper's retry arrives while we are working
            hook, self.in_flight = self.in_flight, None
            hook(idempotency_key)
        return ChargeResult(self._charge_once(idempotency_key), "succeeded")

def run_world(seed, fates=ALL_FATES, shoppers=4, attempts=3):
    """Run one world to the end. Returns (violations, trace)."""
    rng = random.Random(seed)
    clock = FakeClock(datetime(2026, 11, 23, 9, 0, tzinfo=timezone.utc))
    log = [f"seed {seed}"]
    with tempfile.TemporaryDirectory() as tmp:
        db = Database(str(Path(tmp) / "sim.sqlite"))
        db.seed()
        start_stock = db.stock_of(3)  # Aso-oke cap: 5 in stock, so stock can run out
        provider = SimProvider(rng, clock, log, fates)
        wanted = {f"shopper-{i}": rng.randint(1, 2) for i in range(shoppers)}
        done = set()

        def attempt(key):
            try:
                _, created = place_order(db, provider, clock, [{"product_id": 3, "qty": wanted[key]}], key)
                log.append(f"{clock.now():%H:%M:%S} {key}: order {'created' if created else 'replayed'}")
                return True
            except PaymentDeclined:
                log.append(f"{clock.now():%H:%M:%S} {key}: declined")
                return True  # an answer, so the shopper stops
            except OutOfStock:
                log.append(f"{clock.now():%H:%M:%S} {key}: out of stock")
                return True
            except PaymentUnavailable as exc:
                log.append(f"{clock.now():%H:%M:%S} {key}: {exc}; shopper will retry")
                return False

        keys = list(wanted)
        provider.in_flight = attempt  # the first call that draws retry_in_flight uses it, once
        tries = {k: 0 for k in keys}
        while len(done) < len(keys):
            key = rng.choice([k for k in keys if k not in done])
            tries[key] += 1
            if attempt(key) or tries[key] >= attempts:
                done.add(key)
            clock.advance(seconds=rng.randint(1, 30))

        return check_invariants(db, provider, wanted, start_stock), log

def check_invariants(db, provider, wanted, start_stock):
    orders = []
    for key in wanted:
        order = db.find_order_by_key(key)
        if order:
            orders.append(order)
    problems = []
    with db._tx() as conn:  # every order row, not only the first per key
        rows = [dict(r) for r in conn.execute("SELECT idempotency_key, charge_id FROM orders")]
    per_key, per_charge = {}, {}
    for row in rows:
        per_key[row["idempotency_key"]] = per_key.get(row["idempotency_key"], 0) + 1
        per_charge[row["charge_id"]] = per_charge.get(row["charge_id"], 0) + 1
    for key, n in per_key.items():
        if n > 1:
            problems.append(f"{n} orders for key {key}")
    for charge_id, n in per_charge.items():
        if n > 1:
            problems.append(f"{n} orders paid by the one charge {charge_id}")
    if db.stock_of(3) < 0 or db.stock_of(3) > start_stock:
        problems.append(f"stock {db.stock_of(3)} outside 0..{start_stock}")
    for order in orders:
        if order["charge_id"] not in provider.by_key.values():
            problems.append(f"order {order['id']} has a charge the provider never made")
    sold = sum(ln["qty"] for o in orders for ln in o["lines"])
    kept = start_stock - db.stock_of(3)
    if kept != sold and not problems:  # units taken from stock equal units on orders
        problems.append(f"stock taken {kept} but {sold} units on orders")
    return problems

if __name__ == "__main__":
    n = int(sys.argv[1]) if len(sys.argv) > 1 else 500
    bad = [(s, v) for s in range(n) for v in [run_world(s)[0]] if v]
    print(f"{n} seeds, {len(bad)} failed")
    for seed, problems in bad[:5]:
        print(f"  seed {seed}: {problems[0]}")

Read three things before you run it. rng is passed to the provider and used by the scheduler: one generator, so one seed. clock.advance is the only way time moves. And place_order is the real function, unchanged. Then create tests/test_sim_checkout.py:

import pytest

from tests.sim_checkout import SAFE_FATES, run_world

SEEDS = range(300)

def test_the_same_seed_replays_the_same_world():
    first, trace_a = run_world(7)
    second, trace_b = run_world(7)
    assert trace_a == trace_b and first == second

def test_drops_delays_500s_and_declines_never_break_the_invariants():
    for seed in SEEDS:
        problems, trace = run_world(seed, fates=SAFE_FATES)
        assert not problems, f"seed {seed}: {problems}\n" + "\n".join(trace)

@pytest.mark.xfail(strict=True, reason="a retry that arrives while the first call is in flight")
def test_a_retry_arriving_mid_call_makes_one_order():
    for seed in SEEDS:
        problems, trace = run_world(seed)
        assert not problems, f"seed {seed}: {problems}\n" + "\n".join(trace)
.venv/bin/pytest tests/test_sim_checkout.py -q
.venv/bin/python tests/sim_checkout.py 500
2 passed, 1 xfailed (about 8 s for the three). The determinism test is green. The drops, delays, 500s and declines never break an invariant across 300 worlds, which is the result of step 1 at scale. The one that adds retry_in_flight fails, so it is marked as an expected failure; strict=True makes it go red the moment it starts passing. The second command prints 500 seeds, 85 failed and then the first five, beginning seed 0: 2 orders for key shopper-1, seed 3: 2 orders for key shopper-3. The run takes about ten seconds here. The count may differ on another Python or SQLite version, but the failing seeds on one machine are the same every run.

4. Replay one failing seed. A seed is a bug report. Print the world for seed 0:

.venv/bin/python - <<'EOF'
from tests.sim_checkout import run_world
problems, trace = run_world(0)
print(problems)
print("\n".join(trace))
EOF
['2 orders for key shopper-1', '2 orders paid by the one charge ch_0003']
seed 0
09:00:00 shopper-3: provider fate drop_reply
09:00:02 shopper-3: provider timed out; shopper will retry
09:00:32 shopper-2: provider fate late
09:00:34 shopper-2: provider timed out; shopper will retry
09:01:03 shopper-1: provider fate retry_in_flight
09:01:03 shopper-1: provider fate ok
09:01:03 shopper-1: order created
09:01:13 shopper-0: out of stock
...

Read the trace as a story. shopper-1’s first call draws retry_in_flight. While the provider handles it, the retry arrives with the same key, looks up the key, finds no order (the first has not saved), reserves stock, charges (the provider dedupes: the same charge ch_0003) and saves an order. The first call then resumes and saves a second. The log shows the second order created for the same key at the same second, then both orders are in the database. The trace has more lines after out of stock; run it yourself for all of them. Run the command again: the same trace, to the character. That is determinism.

You have found, without threads or luck, the check-then-act race the flaky tests chapter showed with a retry plugin hiding it: place_order looks the key up, then charges, then saves, and nothing stops two requests from passing the first step together. The simulation also shows what the race costs: two orders for one charge, stock taken twice, and the customer billed once.

5. Close the race, and let the seeds confirm. This is the fix you made in step 8 of the concurrency chapter, where it owns the explanation: a unique index on orders_key, and place_order handling the conflict by giving its stock back and returning the winner’s order. That chapter’s last step put the lab back to the starter state, so you apply it again here, with the same code. If you kept the fix, or your place_order already has the except sqlite3.IntegrityError branch, skip the edit; step 3’s xfail test will then fail as unexpectedly passing, which is the confirmation. Otherwise, in checkout/db.py change CREATE INDEX IF NOT EXISTS orders_key to CREATE UNIQUE INDEX IF NOT EXISTS orders_key in the SCHEMA string. In checkout/orders.py, add import sqlite3 as the first import line and replace the last two lines of place_order (order = db.save_order(...) and return order, True):

    try:
        order = db.save_order(idempotency_key, quote.total, charge.id, clock.now(), lines)
    except sqlite3.IntegrityError:
        # A request with this key saved first. Put our stock back and return its order.
        release_all(db, lines)
        return db.find_order_by_key(idempotency_key), False
    return order, True

Then remove the xfail line from the third test and run everything:

.venv/bin/python tests/sim_checkout.py 500
FAULT_PROVIDER_PORT=8095 .venv/bin/pytest -q
500 seeds, 0 failed, and then 32 passed, 1 skipped, 1 deselected on a clean lab (the skip is the browser test without Chromium; files you added in earlier chapters raise the count). The loser of the race now hits the unique index, hands back its stock and returns the first request’s order. The unique index is what stops two real threads too; the simulation only proves the code path. A database that already holds duplicate keys cannot build the index, so on a live system you clean up duplicates before the migration, with the care of the migrations chapter.

Break the compensation, which is the line every test in this chapter depends on. In checkout/orders.py change the finally block so the cleanup does not run:

    finally:
        if not paid:
            pass  # release_all(db, lines)

Run .venv/bin/python tests/sim_checkout.py 500 and FAULT_PROVIDER_PORT=8095 .venv/bin/pytest tests/integration/test_provider_faults.py -q. The simulator reports 500 seeds, 472 failed with stock taken 5 but 2 units on orders for seed 0: stock is taken for shoppers who never got an order, until the shelf is empty and every later shopper meets out of stock. The live-provider file fails four tests (decline, 500, timeout and late), each on assert db.stock_of(2) == 100. Both catch it; notice what each gives you. The live tests name the mode that broke. The simulator names a seed and a story. Put the line back before you go on.

6. Put the lab back. Later chapters count tests from the starter state. After the break above, restore the two source files and remove what you added:

git checkout checkout/db.py checkout/orders.py
rm -rf tests/sim_checkout.py tests/test_sim_checkout.py tests/integration/test_provider_faults.py data/lab-scratch.sqlite .hypothesis
.venv/bin/pytest -q
23 passed, 1 skipped, 1 deselected, the starter state. The race is open again, as the lab’s README says it should be on the clean code.
DECIDE

After the Friday incident Tshepiso's team has three proposals for the provider timeout. The checkout client waits 2 seconds today. The provider's own p99 is about 1.5 seconds on a normal day and 3 to 6 seconds on a bad one. Idempotency keys are already sent on every charge. Boitumelo has written the late-answer test from this chapter and it passes. What do you recommend?

READING
  1. DOC
    Jepsen: analyses Kyle Kingsbury

    Fault injection against real distributed databases, written up as findings with the faults, the histories and the checkers. Read two or three analyses of systems you have heard of and look at which faults found each bug. Skip the protocol detail on a first pass.

  2. DOC
    FoundationDB documentation: Simulation and Testing FoundationDB project

    A short primary account of deterministic simulation as the central way a database is tested: what is simulated, why determinism matters and how many simulations run each night. Read the Simulation section. Skip the C++ unit-test and Circus sections.

  3. TALK
    Testing Distributed Systems w/ Deterministic Simulation Will Wilson, 2014

    The talk that made the technique known: why distributed bugs resist ordinary tests, and how owning randomness and time makes them replayable. Watch it all; it is the model for the lab's seed and replay.

  4. PAPER
    FoundationDB: A Distributed Unbundled Transactional Key Value Store Zhou et al., 2021

    How the database team built the simulator into the system from the start, and how that shaped the design. The DOI was confirmed through Crossref; the ACM page blocks automated fetches, so open it in a browser. Read: the section on simulation testing; skip the storage and recovery design on a first read.

  5. PAPER
    Chaos Engineering Basiri et al., 2016

    The contrast to simulation: injecting faults into a real system, in production, as an experiment with a hypothesis and a steady state. Read it to decide which of the two your risk calls for. Read: the definition of the discipline and the experiment steps; skip the Netflix tooling details.

  6. PAPER
    Elle: Inferring Isolation Anomalies from Experimental Observations Kingsbury and Alvaro, 2020

    A checker that turns the histories a fault-injection run records into a verdict. It is the clearest example of asserting invariants over the outcome and not over each output. Read: the introduction and the examples of anomalies found; skip the graph-theory proofs.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Performance and load tests as part of the suite →