Checks: concurrency and ownership
Templates for the four concurrency and ownership stories. Each one uses a pause point: a named place in production code where a test can stop a thread or process until it’s released. With pause points, a race that happens one run in a thousand happens on every run, so the wrong design fails every time.
A pause point can be as small as this, compiled out or disabled outside tests:
public final class PausePoints { private static final Map<String, CountDownLatch> reached = new ConcurrentHashMap<>(); private static final Map<String, CountDownLatch> released = new ConcurrentHashMap<>(); private static volatile boolean enabled = false; // tests switch this on
public static void here(String name) throws InterruptedException { if (!enabled || !released.containsKey(name)) return; reached.get(name).countDown(); released.get(name).await(); } public static void arm(String name) { enabled = true; reached.put(name, new CountDownLatch(1)); released.put(name, new CountDownLatch(1)); } public static void awaitReached(String name) throws InterruptedException { reached.get(name).await(); } public static void release(String name) { released.get(name).countDown(); }}import threading
_armed: dict[str, tuple[threading.Event, threading.Event]] = {}
def here(name: str) -> None: if name in _armed: reached, released = _armed[name] reached.set() released.wait()
def arm(name: str) -> None: _armed[name] = (threading.Event(), threading.Event())
def await_reached(name: str) -> None: _armed[name][0].wait()
def release(name: str) -> None: _armed.pop(name)[1].set()C-17: rules that span several rows hold
Section titled “C-17: rules that span several rows hold”- Proves: two concurrent requests that each take a clinician off call leave at least one on call, and the second caller gets a clear refusal.
- Fails for: snapshot isolation without a lock or serializable transactions. Two valid transactions left nobody on call.
- Harness needs: a pause point between the check and the update.
@Testvoid twoConcurrentRequestsLeaveSomeoneOnCall() throws Exception { PausePoints.arm("after-on-call-count"); var rao = executor.submit(() -> onCall.takeOff("night-11-21", "rao")); PausePoints.awaitReached("after-on-call-count"); // Rao has counted 2 var kim = executor.submit(() -> onCall.takeOff("night-11-21", "kim")); Thread.sleep(200); // let Kim reach the same point PausePoints.release("after-on-call-count");
var results = List.of(rao.get(), kim.get());
assertThat(db.onCallCount("night-11-21")).isGreaterThanOrEqualTo(1); assertThat(results).extracting(Result::outcome).containsExactlyInAnyOrder(OFF_CALL, REFUSED_LAST_ON_CALL);}def test_two_concurrent_requests_leave_someone_on_call(on_call, db, pause_points): pause_points.arm("after-on-call-count") with ThreadPoolExecutor() as pool: rao = pool.submit(on_call.take_off, "night-11-21", "rao") pause_points.await_reached("after-on-call-count") # Rao has counted 2 kim = pool.submit(on_call.take_off, "night-11-21", "kim") time.sleep(0.2) # let Kim reach the same point pause_points.release("after-on-call-count") outcomes = sorted([rao.result().outcome, kim.result().outcome])
assert db.on_call_count("night-11-21") >= 1 assert outcomes == ["off_call", "refused_last_on_call"]-- Any shift returned has nobody on call.SELECT shift_idFROM on_callGROUP BY shift_idHAVING count(*) FILTER (WHERE on_call) = 0;With PostgreSQL SERIALIZABLE, one transaction fails with SQLSTATE 40001 and the application retries it. The test above is unchanged: it checks the outcome the caller sees, so it also proves the retry is in place.
C-18: a stale owner is fenced
Section titled “C-18: a stale owner is fenced”- Proves: a worker whose lease expired while it was paused can’t overwrite the new owner’s result, and it learns that it lost ownership.
- Fails for: a lease checked only by the worker. The worker that kept writing after its lease expired.
- Harness needs: a pause point between the lease check and the write; a lock service with a controllable clock.
@Testvoid aWriteFromAnExpiredLeaseIsRejectedAtTheDestination() throws Exception { PausePoints.arm("before-report-write"); var a = executor.submit(() -> workerA.runNightlyReport()); PausePoints.awaitReached("before-report-write"); // A checked its lease (token 33)
lockClock.advance(Duration.ofSeconds(40)); // lease expires workerB.runNightlyReport(); // B gets token 34 and writes
PausePoints.release("before-report-write"); var outcomeA = a.get();
assertThat(storage.read("reports/2026-11-21.json").writtenBy()).isEqualTo("B"); assertThat(outcomeA).isEqualTo(LOST_OWNERSHIP);}def test_a_write_from_an_expired_lease_is_rejected_at_the_destination( worker_a, worker_b, lock_clock, storage, pause_points): pause_points.arm("before-report-write") with ThreadPoolExecutor() as pool: a = pool.submit(worker_a.run_nightly_report) pause_points.await_reached("before-report-write") # A checked its lease (token 33)
lock_clock.advance(seconds=40) # lease expires worker_b.run_nightly_report() # B gets token 34 and writes
pause_points.release("before-report-write") outcome_a = a.result()
assert storage.read("reports/2026-11-21.json").written_by == "B" assert outcome_a == "lost_ownership"C-19: a delayed fill can’t republish an old value
Section titled “C-19: a delayed fill can’t republish an old value”- Proves: a cache fill that read the old value before a write, and finishes after the invalidation, is rejected; the next reader gets the new value.
- Fails for: delete-on-write cache-aside. The cache that went stale right after invalidation.
- Harness needs: a pause point between the database read and the cache write.
@Testvoid aDelayedFillCannotRepublishTheOldPrice() throws Exception { db.setPrice("P-7", "40.00"); // version 1 PausePoints.arm("before-cache-fill"); var reader = executor.submit(() -> catalog.price("P-7")); PausePoints.awaitReached("before-cache-fill"); // reader holds version 1
catalog.updatePrice("P-7", "32.00"); // commit version 2, then invalidate PausePoints.release("before-cache-fill"); reader.get();
assertThat(cache.get("P-7")).satisfiesAnyOf( v -> assertThat(v).isEmpty(), v -> assertThat(v).hasValueSatisfying(e -> assertThat(e.version()).isEqualTo(2))); assertThat(catalog.price("P-7")).isEqualByComparingTo("32.00");}def test_a_delayed_fill_cannot_republish_the_old_price(db, catalog, cache, pause_points): db.set_price("P-7", Decimal("40.00")) # version 1 pause_points.arm("before-cache-fill") with ThreadPoolExecutor() as pool: reader = pool.submit(catalog.price, "P-7") pause_points.await_reached("before-cache-fill") # reader holds version 1
catalog.update_price("P-7", Decimal("32.00")) # commit version 2, then invalidate pause_points.release("before-cache-fill") reader.result()
entry = cache.get("P-7") assert entry is None or entry.version == 2 assert catalog.price("P-7") == Decimal("32.00")C-20: a compensation undoes only its own work
Section titled “C-20: a compensation undoes only its own work”- Proves: compensating a failed saga releases only its own reservation, leaves a concurrent saga’s reservation intact, and is safe to run twice.
- Fails for: restoring a remembered total. The compensation that undid somebody else’s work.
- Harness needs: run saga steps individually.
@Testvoid compensationReleasesOnlyItsOwnReservationEvenTwice() { inventory.setStock("P-3", 10); var w1 = inventory.reserve("W1", "P-3", 2); var w2 = inventory.reserve("W2", "P-3", 3);
sagas.compensate("W1"); sagas.compensate("W1"); // a retried compensation
assertThat(inventory.reservation(w2).status()).isEqualTo(HELD); assertThat(inventory.reservation(w1).status()).isEqualTo(RELEASED); assertThat(inventory.available("P-3")).isEqualTo(7);}def test_compensation_releases_only_its_own_reservation_even_twice(inventory, sagas): inventory.set_stock("P-3", 10) w1 = inventory.reserve("W1", "P-3", 2) w2 = inventory.reserve("W2", "P-3", 3)
sagas.compensate("W1") sagas.compensate("W1") # a retried compensation
assert inventory.reservation(w2).status == "held" assert inventory.reservation(w1).status == "released" assert inventory.available("P-3") == 7-- Available stock must equal stock minus held reservations. Any row returned has drifted.SELECT p.product_id, p.available, p.stock - COALESCE(SUM(r.quantity) FILTER (WHERE r.status = 'held'), 0) AS expectedFROM products pLEFT JOIN reservations r ON r.product_id = p.product_idGROUP BY p.product_id, p.available, p.stockHAVING p.available <> p.stock - COALESCE(SUM(r.quantity) FILTER (WHERE r.status = 'held'), 0);Related pages
Section titled “Related pages”Written and edited by Abhinav Taduka, enterprise software architect.
New pages are added regularly. Follow Abhinav on LinkedIn to see them first.