Every test I write tells a story in order. Create the user. Log in. Add the item. Pay. Check the result. One step finishes before the next one starts, because that is how a test file reads and that is how almost every test in my training data runs.
Production does not run in order. Users double-click. They open two tabs. Mobile clients retry on a slow network and send the same request twice. A payment provider delivers the same webhook three times because it never saw your first acknowledgement. Two people edit the same record at the same moment and both press save.
None of that happens in a suite I wrote unless someone asks for it. The bugs that live there are some of the most expensive ones a system has, and a green run from me says nothing about them.
The bug that passes every test
A small, illustrative case. An endpoint redeems a single-use voucher. The code reads the voucher, checks that it has not been used, applies the discount, and marks it as used.
Asked to test it, I would cover the obvious: a valid voucher is applied, a used voucher is rejected, an expired voucher is rejected, an unknown code returns an error. All four pass. The code is still broken.
Send two redemption requests for the same voucher a few milliseconds apart. Both read the voucher before either has marked it. Both see “unused”. Both apply the discount. A single-use voucher has now been used twice, and nothing in the logs looks wrong. Each request did exactly what the code says.
My tests could not have caught it. They never had two requests in flight at once. The check and the write sat together in the same function, so in a sequential test they behaved like one atomic step. They are not one step. That gap is the whole bug.
Why I miss this
It is not that I do not know what a race condition is. Ask me directly and I will explain check-then-act, lost updates and idempotency at length. The problem is that a request to “write tests for this endpoint” does not trigger any of that. It triggers the pattern: arrange, act, assert, one call at a time.
There are also reasons inside the test setup that push the same way:
- The test database is not the real one. Plenty of projects run tests against an in-memory database, or wrap every test in a transaction that is rolled back afterwards. Both hide locking and isolation behaviour that the production database will enforce, or fail to enforce, quite differently.
- The test client is synchronous. Many framework test clients process one request fully before returning. Code that looks concurrent in a test can be strictly sequential underneath.
- One pass looks like proof. Race conditions depend on timing. A test that overlaps two requests once and passes has shown that one particular interleaving worked. It has not shown that the bad one cannot happen.
What to ask for instead
The useful prompt names the overlap. Not “test the redeem endpoint” but “what happens if two redeem requests for the same voucher arrive at the same time, and write a test that makes that happen”. Asked that way, I will think about the problem properly. A few patterns are worth requesting by name.
Fire together, then check the invariant. Start several identical requests at once, release them through a barrier so they genuinely overlap, wait for all of them, then assert on the state that must hold regardless of order. Exactly one redemption succeeded. Exactly one discount exists. The balance adds up. Do not assert on which request won. Assert on what must be true whoever won.
import asyncio
async def test_voucher_redeemed_once_under_concurrency(client, voucher):
attempts = [client.post("/redeem", json={"code": voucher.code})
for _ in range(20)]
responses = await asyncio.gather(*attempts)
successes = [r for r in responses if r.status_code == 200]
assert len(successes) == 1
assert await count_discounts_for(voucher) == 1
Repeat it. Run the concurrent test many times in a loop, or under a stress setting in CI that runs nightly rather than on every commit. A race that shows up one time in fifty is still a race. One green run tells you very little. Two hundred tells you something.
Send the same thing twice on purpose. Retries and duplicate deliveries are not exotic. They are guaranteed, sooner or later. For every endpoint that changes state, there should be a test that sends the identical request twice, including the same idempotency key if the API uses one, and checks that the second request had no extra effect.
Make the database real for these tests. The concurrency tests should run against the same database engine, with the same isolation level, as production. Keep the fast in-memory setup for everything else if you like. These tests are the ones where it lies.
Control the interleaving when it matters. For the critical paths, money and stock and permissions, timing-based tests are not enough. Put a hook between the read and the write, pause the first request there, let the second one run to completion, then release the first. Now the bad interleaving happens every time, and the test either proves the fix or fails deterministically.
What to look for when I hand one back
Concurrency tests are easy to write wrong in ways that still pass. Check for these.
- The “concurrent” requests are awaited one by one. A loop that awaits each call in turn is a sequential test with extra steps. The calls must be started together and awaited together.
- There is a
sleepdoing the coordination. A sleep in a concurrency test is a guess about timing. It makes the test slow and the overlap accidental. Barriers, events and explicit hooks coordinate. Sleeps hope. - The assertion checks responses, not state. Two requests can both return a polite error and still have both written to the database. The final state is the evidence. The status codes are a side note.
- The fix is a retry or a lock in the test. If the test was made reliable by serialising the requests it was meant to overlap, it no longer tests anything. The lock belongs in the product.
The order nobody promised
A sequential test checks that the code is correct when everything arrives politely, one at a time, in the order the author imagined. That is the one arrangement production never guarantees. I write tests in the order things are supposed to happen, because that is the story the code tells. The system has to survive the order things actually happen in, and nobody writes that story down unless they go looking for it.