Skip to content

Lesson 8 of 9 · 26m

Testing Concurrent Code Until It Deserves Trust

Stress tests, deterministic interleaving explorers, race detectors, sanitizers, and invariant assertions — the layered testing strategy that finds timing bugs before customers do.

A single passing run of a concurrent test is almost meaningless. Concurrent failures live in low-probability interleavings, and the scheduler changes under load, on different hardware, and inside containers with CPU limits. The goal is not to prove correctness by volume. The goal is to shape the test environment so rare interleavings become reproducible and invariants fail loudly.

Assert invariants, not incidental outcomes

Weak tests assert exact ordering where ordering is not contractual. Strong tests assert the properties that must hold under every legal schedule:

  • counts and accepted jobs are conserved exactly once
  • empty queues and partially initialized objects are never observed In a queue test, exact consumer ordering may be nondeterministic while conservation of items is invariant. Encode that difference.

Stress tests need controlled concurrency

A useful stress test uses a fixed number of workers, bounded work, synchronization at start, and a deadline:

start = threading.Barrier(workers + 1)
def worker(seed):
    start.wait()
    for i in range(10_000):
        queue.put((seed, i))
threads = [threading.Thread(target=worker, args=(n,)) for n in range(workers)]
for thread in threads: thread.start()
start.wait()
for thread in threads: thread.join(timeout=30)

Vary worker counts around core count: 1, 2, cores, cores+1, and a heavily oversubscribed value. Some races appear only when threads are preempted; others only when they truly run in parallel.

Race detectors are force multipliers

Use the platform tools that instrument memory access rather than guessing:

go test -race ./...
clang++ -fsanitize=thread -g -O1 app_test.cpp -o app_test
./app_test

Go's race detector and ThreadSanitizer report conflicting accesses with stack traces. They only observe executions that happen, so weak coverage still means weak detection — but when they fire, treat the report as a real bug even if the test output looked correct.

Deterministic interleaving exploration is the next level

Rust's Loom systematically explores permitted interleavings of a small synchronization model:

#[test]
fn counter_model() {
    loom::model(|| {
        let counter = loom::sync::Arc::new(loom::sync::atomic::AtomicUsize::new(0));
        let handles: Vec<_> = (0..2).map(|_| {
            let counter = counter.clone();
            loom::thread::spawn(move || counter.fetch_add(1, loom::sync::atomic::Ordering::SeqCst))
        }).collect();
        for h in handles { h.join().unwrap(); }
        assert_eq!(counter.load(loom::sync::atomic::Ordering::SeqCst), 2);
    });
}

Fault injection exposes hidden assumptions

Concurrency correctness often depends on what happens when a thread pauses at the exact wrong point. Add test hooks that yield or sleep after a load and before a CAS, between lock acquisition and mutation, or after dequeue but before commit. In distributed systems, kill workers mid-operation and verify idempotency.

Field notes

  • Keep stress tests bounded in CI, and record seeds and worker counts so rare failures are reproducible.
  • A sanitizer report with a clean final answer is still a failed test.
  • Test shutdown paths. Half the races in real systems live in startup, cancellation, and teardown.
  • If a bug only reproduces with production traffic, reduce it to a synchronization model rather than adding more production load.

Was this lesson helpful?

Sign in to rate