Race condition

A failure whose outcome changes with timing because concurrent requests, jobs, or tests touch the same state in a different order.

“test only fails when things happen together”“two async jobs step on each other”“two people clicked at the same time and it charged twice”“passes when I add a log”“concurency test bug”“requests finish in the wrong order”“works alone but fails in parallel”“sometimes the slower request wins”

What it is

A race condition makes the result depend on the order or timing of concurrent operations. A test might start two requests that both read the same value, then get a different final value depending on which write lands last. It is the same shape as a double-clicked checkout button charging one card twice. The same bug can hide in the test harness when two cases share a database row, fake clock, or temporary file.

Test one by controlling the interleaving instead of hoping it appears. Use a barrier or deferred promise to pause both operations after the read, release them together, and assert the invariant after Promise.all settles. For database behavior, run against the real transaction and locking setup, because a mock cannot reproduce its scheduler.

Gotcha: repeating the test a thousand times increases the odds but does not prove the race is gone. Fixed sleeps are worse, because faster or slower CI machines change the schedule again. Make the dangerous order deterministic, and give parallel tests separate state so the harness does not manufacture a second race.

Ask AI for it

Write a Vitest integration test that reproduces the race in <functionName> deterministically. Use a deferred Promise barrier to pause two calls after both have read the same record, release both writes together with Promise.all, then assert the database invariant and exact final row count. Do not use setTimeout or repeat-until-fail loops. Run against the real Postgres transaction code, clean the table in afterEach, and prove the test fails before the locking fix and passes after it.

You might have meant

flaky testtest retrytest isolation setup and teardownintegration testrace condition