Picture this: you type "react" into a search box. The results flash "react" for a split second, then silently flip back to "re". No error in the console. No crash.
You just hit a race condition.
The mental model#
A race condition is two runners writing their name on the same whiteboard.
Your code assumes the runner who started first will finish first. Networks, databases, and threads make no such promise. If the first runner trips and arrives late, they erase the second runner's name — and the whiteboard ends up showing old data.
How it happens#
Every race condition needs two ingredients: shared state (a React state variable, a database row, a file) and overlapping work (two network calls, two requests, two threads) where the final result depends on timing.
Here is the classic frontend version:
useEffect(() => {
fetch(`/api/search?q=${query}`)
.then((r) => r.json())
.then((data) => setResults(data)); // ← whichever finishes last wins
}, [query]);
Type "re", then quickly finish typing "react":
- Request 1 (
"re") leaves first, but the server takes 600ms. - Request 2 (
"react") leaves 50ms later, hits a warm cache, and returns in 100ms. setResultsshows"react".- 450ms later, Request 1 finally arrives and calls
setResultswith"re".
AI-generated illustration. Request 1 starts earlier, finishes later, and overwrites the newer result on screen.
The exact same bug happens on the backend. Two users click "Buy" on the last item in stock at the same millisecond. Both read stock = 1, both see "great, there's one left!", and both write stock = 0 — you just sold the same item twice.
How to find a race condition#
Race conditions are famous for "works on my machine" because localhost is fast and predictable. Three reliable ways to smoke them out:
- Slow down the network on purpose. In Chrome DevTools, throttle to Slow 3G (or add a random
setTimeoutdelay in a mock API) and click, type, or switch tabs fast. - Audit every
asyncwrite to shared state. In code review, scan foruseEffectfetches without cleanup, and backend code that does read → check → write in separate queries. - Let tools stress-test timing for you. Turn on React Strict Mode in dev (it double-runs effects to expose missing cleanups), use
go test -racein Go, or fire 20 concurrent requests at the same endpoint in a test.
How to fix it#
The fix depends on where the whiteboard lives.
On the frontend: cancel or ignore stale work#
Use AbortController in your useEffect cleanup so an older request is cancelled the moment a newer one starts:
useEffect(() => {
const controller = new AbortController();
fetch(`/api/search?q=${query}`, { signal: controller.signal })
.then((r) => r.json())
.then((data) => setResults(data))
.catch((err) => {
if (err.name !== "AbortError") throw err;
});
return () => controller.abort(); // ← old runner leaves the track
}, [query]);
If you can't abort the call, use a boolean let ignore = false flag in the effect and flip it to true in the cleanup before calling setResults. Better yet, data-fetching libraries like TanStack Query handle request cancellation and stale responses for you.
On the backend: make the update atomic#
Never check a value in one query and update it in another. Push the check into a single atomic database operation:
-- Before: two queries (race window in between)
-- SELECT stock FROM items WHERE id = 1;
-- UPDATE items SET stock = stock - 1 WHERE id = 1;
-- After: one atomic write
UPDATE items
SET stock = stock - 1
WHERE id = 1 AND stock > 0;
If zero rows are updated, the item is out of stock — no second runner can slip in between. For multi-step workflows (like charging a card), combine a database transaction with an idempotency key so duplicate requests don't double-charge.
Say it in an interview#
"A race condition happens when two operations overlap on the same shared state and the outcome depends on which one finishes last. On the frontend, you fix it by cancelling or ignoring stale requests — like with
AbortControllerin auseEffectcleanup. On the backend, you eliminate the gap between reading and writing using atomic updates, database locks, or idempotency keys."
Cheat sheet#
| Where it happens | How to spot it | How to fix it |
|---|---|---|
React useEffect fetch | Throttle network, type/click fast, enable Strict Mode | AbortController or ignore flag in cleanup (or TanStack Query) |
| Database read-then-write | Send concurrent requests to the same endpoint | Single atomic UPDATE ... WHERE, row locks, or transactions |
| Double-click / retries | Click Submit twice on a slow connection | Disable button + server-side idempotency key |
Advanced · optional
Going deeper#
Everything above is enough to explain this in an interview. This part is for the curious: full numbers, edge cases and what's still unproven.
Wait — isn't JavaScript single-threaded?#
Yes, JavaScript runs one line at a time on the main thread, so two functions never mutate the same variable at the exact same nanosecond (no low-level data race on memory).
What JavaScript does have is async interleaving. Every await pauses your function and hands control back to the event loop. While function A is paused at await fetch(...), function B can run, read the same state, and write to it. When function A resumes, its assumptions are already stale.
TOCTOU: the classic backend pattern#
The "read stock, check > 0, then update" bug has a name: TOCTOU (Time-of-Check to Time-of-Use). Between checking a condition and acting on it, another request changes the world underneath you.
When a single atomic UPDATE isn't enough (for example, checking a balance across two tables), wrap the read and write in a transaction using row-level locking (SELECT ... FOR UPDATE) or optimistic concurrency control (a version column: WHERE id = $1 AND version = $2).



Start the discussion
Questions, corrections, a better approach? I read and reply to every comment.