Skip to content
jshacks.dev
Async

Race Conditions in Single-Threaded JavaScript

Learn how race conditions happen in single-threaded JavaScript through await gaps, out-of-order responses and double submits, with fixes using locks and tokens.

7 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the JavaScript, Redis and Apache Kafka logos.

JavaScript runs your code on one thread, so two lines never execute at the same instant, and yet race conditions are everywhere in JavaScript programs. The reason is that every await is a gap. The function stops, other code runs, and the function resumes later into a world that may have changed. A race condition is any bug whose outcome depends on the order in which those interleaved pieces finish. They show up as a stale search result that overwrites a fresh one, a counter that loses an update, a button that submits an order twice and a cache that is filled by two requests at once. This post explains where the gaps are on Node.js 24 with printed output, shows five concrete races, and gives the fixes that work: sequence numbers, abort signals, in-flight deduplication, a promise-based mutex and idempotent operations.

The gap is the await

Code between two await expressions runs without interruption. Code on either side of one can be interleaved with anything else. A read-modify-write that spans an await is therefore not atomic.

JavaScript
let balance = 100;

async function withdraw(amount) {
  const current = balance;                  // read
  await new Promise((r) => setTimeout(r, 10)); // some async check
  balance = current - amount;               // write based on a stale read
}

await Promise.all([withdraw(30), withdraw(50)]);

console.log("expected: 20, got:", balance);
Text
expected: 20, got: 50

Both calls read 100 before either wrote. The first wrote 70, the second wrote 50, and the first withdrawal vanished. No threads were involved, and the bug is purely the order of interleaving. Move the read after the await, or better, make the whole sequence exclusive, and the problem disappears.

Race 1: out-of-order responses

A user types in a search box. Each keystroke starts a request, and the responses can arrive in any order.

JavaScript
let displayed = null;

async function search(query, latency) {
  await new Promise((r) => setTimeout(r, latency));
  displayed = `results for "${query}"`;
}

const first = search("ja", 40);   // slow
const second = search("jav", 10); // fast

await Promise.all([first, second]);

console.log(displayed);
Text
results for "ja"

The newer query finished first and was overwritten by the older, slower one. The screen shows results for text the user has already changed. The fix is to tag each request with a sequence number and ignore any response that is not the latest.

JavaScript
let latest = 0;
let shown = null;

async function searchSafely(query, latency) {
  const mine = ++latest;
  await new Promise((r) => setTimeout(r, latency));

  if (mine !== latest) return; // a newer request exists, discard this one

  shown = `results for "${query}"`;
}

await Promise.all([searchSafely("ja", 40), searchSafely("jav", 10)]);

console.log(shown);
Text
results for "jav"

For network calls, an AbortController is stronger, since it cancels the stale request and not just its result. The sequence number is the portable version, and it also works for work that cannot be aborted.

Race 2: check then act

Testing a condition, awaiting something and acting on the result assumes the condition still holds.

JavaScript
const seats = new Set();

async function book(seat, user) {
  if (seats.has(seat)) return `${user}: seat taken`;

  await new Promise((r) => setTimeout(r, 5)); // payment call

  seats.add(seat);
  return `${user}: booked ${seat}`;
}

console.log(await Promise.all([book("12A", "ada"), book("12A", "linus")]));
Text
[ 'ada: booked 12A', 'linus: booked 12A' ]

Both users passed the check before either added the seat. The fix is to claim the resource before the slow step and release it on failure.

JavaScript
const claimed = new Set();

async function bookSafely(seat, user) {
  if (claimed.has(seat)) return `${user}: seat taken`;
  claimed.add(seat); // claim synchronously, before any await

  try {
    await new Promise((r) => setTimeout(r, 5));
    return `${user}: booked ${seat}`;
  } catch (error) {
    claimed.delete(seat);
    throw error;
  }
}

console.log(await Promise.all([bookSafely("12A", "ada"), bookSafely("12A", "linus")]));
Text
[ 'ada: booked 12A', 'linus: seat taken' ]

The check and the claim now happen in the same synchronous stretch, so no other code can run between them. That is the general trick: keep the check and the act together with no await in between.

Race 3: the double submit

A user clicks a button twice, or a retry fires while the first request is still running, and the operation runs twice. The fix is a guard that remembers the operation in flight.

JavaScript
let inFlight = null;
let created = 0;

async function createOrder() {
  if (inFlight) return inFlight;

  inFlight = (async () => {
    await new Promise((r) => setTimeout(r, 10));
    created += 1;
    return `order ${created}`;
  })();

  try {
    return await inFlight;
  } finally {
    inFlight = null;
  }
}

const results = await Promise.all([createOrder(), createOrder(), createOrder()]);

console.log(results);
console.log("orders created:", created);
Text
[ 'order 1', 'order 1', 'order 1' ]
orders created: 1

All three callers shared one operation. For operations with side effects on a server, a client-side guard is not enough, because a network retry or a second tab bypasses it. The server needs an idempotency key: a unique id sent with the request, so a repeat with the same id returns the stored result and does not create a second order.

Race 4: a cache stampede

When a cache entry is missing and ten requests arrive at once, each one sees the miss and starts the expensive load.

JavaScript
const cache = new Map();
let loads = 0;

async function getUser(id) {
  if (cache.has(id)) return cache.get(id);

  loads += 1;
  await new Promise((r) => setTimeout(r, 10));

  const user = { id };
  cache.set(id, user);
  return user;
}

await Promise.all(Array.from({ length: 5 }, () => getUser(1)));

console.log("loads for one key:", loads);
Text
loads for one key: 5

Five loads ran for one key. Store the promise instead of the value, so later callers join the first load.

JavaScript
const promises = new Map();
let loads2 = 0;

function getUserOnce(id) {
  if (!promises.has(id)) {
    loads2 += 1;
    promises.set(
      id,
      new Promise((r) => setTimeout(() => r({ id }), 10)),
    );
  }

  return promises.get(id);
}

await Promise.all(Array.from({ length: 5 }, () => getUserOnce(1)));

console.log("loads for one key:", loads2);
Text
loads for one key: 1

If the load can fail, delete the entry on rejection so the next caller retries, rather than caching the failure forever.

Race 5: interleaved read-modify-write on shared state

The withdraw example generalizes: any sequence that reads state, awaits and writes needs to run one at a time. A small promise-based mutex does that.

JavaScript
class Mutex {
  #tail = Promise.resolve();

  run(task) {
    const result = this.#tail.then(task);
    this.#tail = result.catch(() => {});
    return result;
  }
}

const mutex = new Mutex();
let balance = 100;

const withdraw = (amount) =>
  mutex.run(async () => {
    const current = balance;
    await new Promise((r) => setTimeout(r, 10));
    balance = current - amount;
  });

await Promise.all([withdraw(30), withdraw(50)]);

console.log("balance:", balance);
Text
balance: 20

Each task starts only after the previous one has finished, so the read and the write belong to the same exclusive section. The mutex serializes work, which costs concurrency, so keep the protected section as short as possible and do slow, independent work outside it.

How to find races

Races hide because they depend on timing. A few habits expose them. Add artificial delays in tests, with different latencies per call, so that the unlucky ordering happens every time. Search the code for any variable that is read before an await and written after it. Ask of every if that contains an await in its body whether the condition could change while waiting. And be suspicious of module-level state in server code, since concurrent requests share it.

What a fix usually looks like

There are five tools, and each race above used one. A sequence number discards stale results. An in-flight promise shares work between duplicate callers. A synchronous claim makes a check and an action atomic. A mutex serializes a read-modify-write. An idempotency key makes repeating an operation harmless. Choose the lightest one that matches the failure, and prefer redesigns that remove shared mutable state over locks that guard it.

A short checklist for reviews

When reviewing asynchronous code, run through four questions. Does any function read shared state, await, and then write based on what it read? Does any condition get checked, followed by an await, and then acted on as if the condition still held? Can the same operation start twice before the first one finishes, through a double click, a retry or two tabs? And can responses arrive in a different order from the requests that caused them? A yes to any of them marks a place worth a test with controlled delays.

The cheapest defense is to make state changes small and synchronous. Compute the new value from the current one in a single step with no await in the middle, and perform the slow work before or after. When that is not possible, name the invariant the code depends on, such as "a seat is booked at most once", and make a single function responsible for enforcing it. Races are rarely fixed by adding delays or retries, because those only change the odds. They are fixed by removing the window in which the state can change, or by making the outcome the same whatever the order.

Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.