BitlystBitlyst
PostsNewsSeriesTopicsAbout

Bitlyst

Short, diagram-first posts on JavaScript, React & Next.js. Follow via RSS or the newsletter.

© 2026 Mohsen Fallahnejad

PostsSeriesTopicsLinksAboutSync devicesRSSllms.txtGitHubX
Posts/javascript
AI-generated illustration. Two tasks racing to the same whiteboard — the one that finishes last overwrites the first.
Intermediate5 min read

Race Condition Explained: How to Find and Fix It

A race condition happens when two operations race to update the same state and the slower one wins. Learn how to spot them and fix them in React and backends.

Mohsen Fallahnejad

Mohsen Fallahnejad

Dec 3, 2026Discuss

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:

tsx
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":

  1. Request 1 ("re") leaves first, but the server takes 600ms.
  2. Request 2 ("react") leaves 50ms later, hits a warm cache, and returns in 100ms.
  3. setResults shows "react".
  4. 450ms later, Request 1 finally arrives and calls setResults with "re".

AI-generated illustration. Request 1 starts earlier, finishes later, and overwrites the newer result on screen.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 setTimeout delay in a mock API) and click, type, or switch tabs fast.
  • Audit every async write to shared state. In code review, scan for useEffect fetches 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 -race in 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:

tsx
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:

sql
-- 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 AbortController in a useEffect cleanup. On the backend, you eliminate the gap between reading and writing using atomic updates, database locks, or idempotency keys."

Cheat sheet#

Where it happensHow to spot itHow to fix it
React useEffect fetchThrottle network, type/click fast, enable Strict ModeAbortController or ignore flag in cleanup (or TanStack Query)
Database read-then-writeSend concurrent requests to the same endpointSingle atomic UPDATE ... WHERE, row locks, or transactions
Double-click / retriesClick Submit twice on a slow connectionDisable 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).

Filed under#javascript#react#engineering#debugging

Was this worth your time?

One tap tells me what to write more of.

Mohsen Fallahnejad

Written by

Mohsen Fallahnejad

Frontend engineer explaining JavaScript, React & Next.js internals in posts you can finish over coffee. More about me

X ↗GitHub ↗LinkedIn ↗
← OlderIs AI Really Faster and Cheaper for Building Products?Newer →Why "Works on My Machine" Happens (And How to Fix It)

Start the discussion

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

Read next

Why "Works on My Machine" Happens (And How to Fix It)

Your code passes locally and breaks in CI or production. Here are the 6 most common 'works on my machine' traps — and the quick fix for each.

Dec 3, 20263 min read

AbortController & AbortSignal

Everything you need to cancel async work in JS: fetch, streams, custom tasks, React patterns, Node notes, timeouts, races, and common pitfalls.

Sep 23, 20254 min read

JavaScript Event Bus 🚍 (JS + TypeScript)

A polished, practical event bus pattern with minimal JS, a strongly-typed TS version, wildcards, once-handlers, and React usage tips.

Sep 21, 20254 min read

Get new posts in your inbox

One email when a new post is out: short, diagram-first explanations of JavaScript, React and Next.js. No spam, unsubscribe any time.

5 min left
Discuss👍 React
👍