GenClass is open source.Star on GitHub

Race conditions in JavaScript, and how to fix them.

JavaScript runs one piece of code at a time, but every await pauses your function, and other code can run before it continues. When the result depends on which async step finishes first, you have a race condition. The fix is to decide the order yourself: ignore responses that are no longer the latest, and run writes to the same data one at a time.

Why single-threaded JavaScript has race conditions

JavaScript processes one job at a time and finishes it before the next one starts, so a running function is never interrupted (MDN: JavaScript execution model). An await ends that guarantee: control goes back to the caller, and the rest of your function runs later as a new microtask (MDN: await). In between, any other job can run, such as a click handler or another response, and change the data your function is about to use.

So a race condition in JavaScript is a bug where the outcome depends on the order in which async work finishes. Ordinary code has no data races between threads, because each worker has its own memory unless you share a SharedArrayBuffer. The logic still races, because the network and the user decide when each piece of async work completes.

On localhost each response takes a few milliseconds, and responses usually arrive in the order you sent them, so these bugs rarely show up on your machine. The race condition simulator lets you set each request's latency and watch the orders play out.

Out-of-order responses: let the latest request win

A search box sends a request on each keystroke. If the request for "pa" is slower than the one for "paris", its results land last and replace the results for "paris". Both requests succeed, so nothing throws.

box.addEventListener("input", async () => {
  const res = await fetch(`/search?q=${encodeURIComponent(box.value)}`);
  render(await res.json()); // whichever response arrives last wins
});

Number each request and drop any answer that is no longer the latest:

let latest = 0;
box.addEventListener("input", async () => {
  const id = ++latest;
  const res = await fetch(`/search?q=${encodeURIComponent(box.value)}`);
  const data = await res.json();
  if (id === latest) render(data); // drop answers to older searches
});

The counter fits any async call. With fetch you can also abort the previous request with an AbortController, which stops the request and the reading of its body; the aborted fetch rejects with an AbortError, which you catch and ignore. The guide to out-of-order responses shows that version, and race conditions in React covers effects.

Check, then act across an await: share one promise

A check and the action that depends on it stop being atomic when an await sits between them. Two API calls start at the same moment, both find the token expired, and both start a refresh:

let token = null;
async function getToken() {
  if (!token || isExpired(token)) {
    token = await refreshToken(); // a second caller gets past the check too
  }
  return token;
}

That is two refresh calls where you wanted one. With refresh token rotation, both calls send the same refresh token, and the first call uses it up. To the server the second call looks like a replayed token, and RFC 9700 says the server then revokes the active refresh token, which forces a fresh authorization, usually a new sign-in. Keep the refresh in flight as one promise and hand the same one to every caller:

let token = null;
let refreshing = null;

async function getToken() {
  if (token && !isExpired(token)) return token;
  refreshing ??= refreshToken()
    .then((fresh) => { token = fresh; return fresh; })
    .finally(() => { refreshing = null; });
  return refreshing; // every caller shares the same refresh
}

This is often called single flight. The token is stored before refreshing is cleared, so a caller that arrives in between never starts a second refresh. Use the same shape for any async function that must not run twice at once. More on the auth case in token refresh race conditions.

Double submits: one intent, one key

An async click handler does not stop a second click while the first request is in flight, so a double click sends two orders. A flag or a disabled button stops the second click. It does not stop a retry after a timeout when the first request already reached the server. For that, send an idempotency key: one per user intent, the same on every retry.

const orderKey = crypto.randomUUID(); // one key per checkout
let sending = false;

payButton.addEventListener("click", async () => {
  if (sending) return; // ignore clicks while the order is in flight
  sending = true;
  try {
    await fetch("/api/orders", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Idempotency-Key": orderKey, // the same key on every retry
      },
      body: JSON.stringify(cart),
    });
  } finally {
    sending = false;
  }
});

The server stores the first result for each key and answers a repeat with it instead of creating a second order. Stripe's v1 API works this way (Stripe: idempotent requests), and an IETF draft defines the Idempotency-Key request header. The server side is in preventing duplicate submissions.

Lost updates: run read-modify-write one at a time

Read a record, change it, write it back. When two of these overlap, both read the same version, and the later write drops the earlier change:

async function addTag(id, tag) {
  const note = await api.getNote(id); // both calls read the same version
  note.tags.push(tag);
  await api.saveNote(id, note); // the later save drops the other tag
}

addTag(7, "work");
addTag(7, "urgent"); // one of the two tags is lost

Inside one page, a small async mutex fixes it. Each task waits for the one queued before it, and each caller still gets its own result or error:

function createMutex() {
  let tail = Promise.resolve();
  return (task) => {
    const run = tail.then(() => task());
    tail = run.catch(() => {}); // a failed task must not block the next
    return run;
  };
}

const withNotes = createMutex();
withNotes(() => addTag(7, "work"));
withNotes(() => addTag(7, "urgent")); // starts after the first save ends

Keep one mutex per record, in a Map keyed by id, so unrelated saves still run in parallel. Autosave has the same problem when saves overlap; see lost edits in autosave.

Across tabs: the Web Locks API

Each tab runs its own copy of your code, mutex included, so two tabs can still overlap. navigator.locks works across them: while one tab or worker holds a lock, no other script in the same origin can take a lock with the same name, and the lock is released when your async callback finishes (MDN: Web Locks API).

async function addTag(id, tag) {
  // one holder at a time for this name, across tabs and workers
  await navigator.locks.request(`note-${id}`, async () => {
    const note = await api.getNote(id);
    note.tags.push(tag);
    await api.saveNote(id, note);
  });
}

It works only in secure contexts (HTTPS), and MDN marks it Baseline widely available: it has worked across browsers since March 2022. Use it for anything tabs share, such as a value in localStorage or a token refresh that only one tab should run.

Across devices: versioned writes

A lock in the browser cannot see a second device or another user, so the server has to refuse a write based on an old read. Over HTTP, send the ETag you read back in an If-Match header. A server that checks it must not apply the write when the resource has changed since, and it can answer 412 Precondition Failed (RFC 9110, section 13.1.1). The check uses strong comparison, so a weak ETag (one that starts with W/) never matches (section 8.8.3.2).

const res = await fetch(`/api/notes/${id}`);
const etag = res.headers.get("ETag"); // the version you read
const note = await res.json();
note.tags.push(tag);

const saved = await fetch(`/api/notes/${id}`, {
  method: "PUT",
  headers: { "Content-Type": "application/json", "If-Match": etag },
  body: JSON.stringify(note),
});
if (saved.status === 412) {
  // someone saved first: read again and reapply the change, or ask the user
}

A cross-origin API has to list ETag in Access-Control-Expose-Headers, or res.headers.get("ETag") returns null (MDN). In your own database, a version number does the same job: update the row only where the version still matches, and treat zero updated rows as a conflict.

Where GenClass fits

GenClass Runtime (@genclass/runtime, open source under Apache-2.0) watches fetch, XHR, WebSocket and EventSource traffic in your users' browsers. In its default mode, observe, it reports a stale response written over newer data (diagnosis stale) and the same request sent again without a new intent, such as a double submit (duplicate). It can also report a response that would replace text the user typed or undo a local change still pending (conflict). Each detection prints one plain-English line in the browser console, followed by its evidence. Observe never holds, delays or changes a request, a response or a state write.

Detection is partial. Scored offline on a test set from real apps kept out of training, model 0.2.0 at its default setting reported 75% of the duplicate submits and 30% of the stale overwrites with the right diagnosis, with false detections held to at most 2% of clean decisions (results). The exact false rate is not published, and three observe changes in runtime 0.3.0 can add reports, false ones included, at a rate not yet measured. Conflicts and lost updates have no published rate.

Stale responses are reported only for state it can see: React state, Redux stores set up for Redux DevTools, and Zustand stores with devtools (in production only with enabled: true). It does not find state kept in plain objects or the DOM, as in the examples above, nor Pinia, Svelte stores, signals, MobX or the caches of TanStack Query, SWR and Apollo: register such state with rt.atom or rt.guard. Double submits need no registered state, but in observe the duplicate still reaches your server, so keep the idempotency keys and versioned writes above. To try it, run npx genclass in your app's folder; it walks you through adding the runtime (CLI guide).

Questions

Can JavaScript have race conditions if it is single-threaded?

Yes. Only one piece of code runs at a time, but async work finishes in an order you do not control, and every await lets other code run before your function continues.

Does debounce prevent race conditions?

No. Debounce sends fewer requests, but two of them can still come back out of order, so you still need to drop or cancel stale responses.

Do I need a mutex in JavaScript?

Only when overlapping async calls read and write the same data. A promise queue runs them one at a time inside one page, and navigator.locks does the same across tabs and workers of the same origin.

Does Promise.all cause race conditions?

Not in its results, which come back in the order you passed the promises, whatever order they finish in. The race comes from side effects inside the promises, such as each one writing to the same variable when it resolves.

Why do race conditions only show up in production?

Locally, responses arrive quickly and mostly in the order you sent them. Real networks vary from one request to the next, so a slow early response can land after a newer one.

Related: race conditions in Angular, testing race conditions with Playwright and detecting race conditions in production.

Talk to sales

Tell us about your team and what you need. A person writes back, usually within a day.