Race conditions

suggest change

A race condition is a bug where the result depends on the timing of operations that run concurrently. The program works when operations happen in one order and breaks when they happen in another.

People often assume Node.js can't have race conditions because JavaScript runs on a single thread. That's only half true. A single thread means two pieces of synchronous code never run at the same time. But every await, callback and event is a point where your function pauses and other code runs. If another task changes shared state in that window, you have a race.

Kind of race Typical fix
Read, await, then write shared state Do it synchronously, use a mutex, or let the database do it atomically
Check if something exists, then create it Create it and handle "already exists" ('wx' flag, unique keys)
Several callers start the same slow load Cache the promise, not the result
Slow old response overwrites a newer one Ignore stale results or cancel with AbortController
Event fires before you listen Check state first, or attach the listener earlier
Worker threads share memory Atomics
Several processes or servers Atomic database operations, optimistic locking

The examples are ES modules (save them as .mjs) and were run with Node.js 24.

Lost update: read, await, write

This is the classic race. A function reads a value, awaits something, then writes a new value computed from what it read:

import { setTimeout as sleep } from 'node:timers/promises';

// pretend this is a database
const db = { balance: 100 };

async function getBalance() {
  await sleep(10);
  return db.balance;
}

async function setBalance(value) {
  await sleep(10);
  db.balance = value;
}

async function withdraw(amount) {
  const balance = await getBalance();
  if (balance < amount) {
    throw new Error('insufficient funds');
  }
  await setBalance(balance - amount);
  return balance - amount;
}

const results = await Promise.allSettled([withdraw(80), withdraw(80)]);
console.log(results.map((r) => r.value ?? r.reason.message));
console.log('final balance:', db.balance);
[ 20, 20 ]
final balance: 20

We withdrew 160 from an account holding 100. Both calls read 100 before either of them wrote, so both checks passed and the second write overwrote the first.

The same thing happens in a web server: two HTTP requests for the same user arrive close together and both run the handler concurrently. In tests with one request at a time it never shows up.

Synchronous code is atomic

What matters is whether there's an await between the read and the write. Code between two awaits runs to completion without interruption:

import { setTimeout as sleep } from 'node:timers/promises';

let a = 0;
let b = 0;

async function incrementSafe() {
  await sleep(1);
  a++; // read and write happen in one synchronous step
}

async function incrementUnsafe() {
  const value = b; // read
  await sleep(1); // other tasks run here
  b = value + 1; // write based on a stale read
}

const tasks = [];
for (let i = 0; i < 100; i++) {
  tasks.push(incrementSafe(), incrementUnsafe());
}
await Promise.all(tasks);
console.log({ a, b });
{ a: 100, b: 1 }

All 100 unsafe tasks read 0 before any of them wrote, so 99 increments were lost.

So the first fix to look for: move the read next to the write so nothing is awaited in between. With in-memory state that's often all you need. When the state lives somewhere you must await (a database, a file, another service), you need one of the techniques below.

Serializing with a mutex

A mutex (mutual exclusion lock) lets only one task at a time run a critical section. Others wait their turn. In Node.js a mutex is a few lines: keep a promise for the tail of the queue and chain each new task onto it:

import { setTimeout as sleep } from 'node:timers/promises';

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

  run(fn) {
    const result = this.#tail.then(() => fn());
    // the next caller waits for this one, whether it succeeds or fails
    this.#tail = result.catch(() => {});
    return result;
  }
}

const db = { balance: 100 };
const getBalance = async () => { await sleep(10); return db.balance; };
const setBalance = async (v) => { await sleep(10); db.balance = v; };

const accountLock = new Mutex();

function withdraw(amount) {
  return accountLock.run(async () => {
    const balance = await getBalance();
    if (balance < amount) {
      throw new Error('insufficient funds');
    }
    await setBalance(balance - amount);
    return balance - amount;
  });
}

const results = await Promise.allSettled([withdraw(80), withdraw(80), withdraw(10)]);
console.log(results.map((r) => r.value ?? r.reason.message));
console.log('final balance:', db.balance);
[ 20, 'insufficient funds', 10 ]
final balance: 10

Tasks run in the order they called run(). The .catch(() => {}) on the tail matters: without it one failed task would reject the chain and every later task would fail too. The caller still gets the rejection through result.

One lock per key

A single lock for all accounts makes unrelated users wait for each other. Usually you want one queue per key (user id, file name, order id). Delete the entry when the queue drains so the map doesn't grow forever:

import { setTimeout as sleep } from 'node:timers/promises';

class KeyedMutex {
  #tails = new Map();

  run(key, fn) {
    const prev = this.#tails.get(key) ?? Promise.resolve();
    const result = prev.then(() => fn());
    const tail = result.catch(() => {});
    this.#tails.set(key, tail);
    // forget the key once nothing is queued behind us
    tail.then(() => {
      if (this.#tails.get(key) === tail) {
        this.#tails.delete(key);
      }
    });
    return result;
  }

  get size() {
    return this.#tails.size;
  }
}

const locks = new KeyedMutex();
const start = Date.now();
const log = (msg) => console.log(`${String(Date.now() - start).padStart(3)}ms ${msg}`);

async function update(user, n) {
  return locks.run(user, async () => {
    log(`start ${user} #${n}`);
    await sleep(50);
    log(`end   ${user} #${n}`);
  });
}

await Promise.all([update('alice', 1), update('alice', 2), update('bob', 1)]);
console.log('keys left:', locks.size);
  0ms start alice #1
  4ms start bob #1
 65ms end   alice #1
 66ms start alice #2
 66ms end   bob #1
130ms end   alice #2
keys left: 0

Bob runs in parallel with Alice, but Alice's second update waits for her first.

A few warnings about in-process locks:

On npm, async-mutex provides Mutex and Semaphore with timeouts and cancellation.

Duplicate work: cache the promise

Lazy initialization is a check-then-act race that wastes work instead of corrupting data:

import { setTimeout as sleep } from 'node:timers/promises';

let loads = 0;
async function loadConfig() {
  loads++;
  await sleep(20); // read a file, call a service...
  return { port: 8080 };
}

let config;
async function getConfig() {
  if (!config) {
    config = await loadConfig();
  }
  return config;
}

await Promise.all([getConfig(), getConfig(), getConfig()]);
console.log('loads:', loads);
loads: 3

All three callers see config as undefined because the first load hasn't finished yet. With a cache in front of an expensive database query this is called a cache stampede: when a popular entry expires, hundreds of requests hit the database at once.

The fix is to store the promise synchronously, before awaiting. Later callers get the same in-flight promise. Remove it on failure, or a single error gets cached forever:

import { setTimeout as sleep } from 'node:timers/promises';

let loads = 0;
async function loadConfig() {
  loads++;
  await sleep(20);
  if (loads === 1) throw new Error('service unavailable');
  return { port: 8080 };
}

let configPromise;
function getConfig() {
  configPromise ??= loadConfig().catch((err) => {
    configPromise = undefined; // allow a retry after a failure
    throw err;
  });
  return configPromise;
}

const first = await Promise.allSettled([getConfig(), getConfig(), getConfig()]);
console.log(first.map((r) => r.status), 'loads:', loads);

const second = await Promise.all([getConfig(), getConfig()]);
console.log(second, 'loads:', loads);
[ 'rejected', 'rejected', 'rejected' ] loads: 1
[ { port: 8080 }, { port: 8080 } ] loads: 2

The same idea works per key, which deduplicates concurrent requests for the same resource:

import { setTimeout as sleep } from 'node:timers/promises';

function memoizeAsync(fn) {
  const cache = new Map();
  return (key) => {
    let promise = cache.get(key);
    if (!promise) {
      promise = fn(key).catch((err) => {
        cache.delete(key);
        throw err;
      });
      cache.set(key, promise);
    }
    return promise;
  };
}

let fetches = 0;
const getUser = memoizeAsync(async (id) => {
  fetches++;
  await sleep(10);
  return { id, name: `user${id}` };
});

const users = await Promise.all([getUser(1), getUser(2), getUser(1), getUser(1)]);
console.log(users.map((u) => u.name), 'fetches:', fetches);
[ 'user1', 'user2', 'user1', 'user1' ] fetches: 2

In a real cache, also add expiry or a size limit.

Stale responses arriving out of order

Requests don't finish in the order they were started. A search-as-you-type feature, a poller or a proxy can show old data if a slow early response arrives after a fast later one:

import { setTimeout as sleep } from 'node:timers/promises';

// a slow search service: shorter queries happen to take longer
async function search(query, { signal } = {}) {
  await sleep(100 / query.length, undefined, { signal });
  return `results for "${query}"`;
}

let shown;
async function onInput(query) {
  shown = await search(query);
}

await Promise.all([onInput('n'), onInput('no'), onInput('node')]);
console.log('shown:', shown);
shown: results for "n"

The user typed node but sees results for n. One fix is to number the requests and only accept the latest (search() is the same as above):

let shown;
let latest = 0;
async function onInput(query) {
  const id = ++latest;
  const results = await search(query);
  if (id !== latest) {
    console.log(`dropping stale "${query}"`);
    return;
  }
  shown = results;
}

await Promise.all([onInput('n'), onInput('no'), onInput('node')]);
console.log('shown:', shown);
dropping stale "no"
dropping stale "n"
shown: results for "node"

Better still, cancel the old request so it stops using resources. fetch(), timers, fs and child processes accept an AbortSignal:

let shown;
let controller;
async function onInput(query) {
  controller?.abort(); // cancel the previous request
  controller = new AbortController();
  try {
    shown = await search(query, { signal: controller.signal });
  } catch (err) {
    if (err.name !== 'AbortError') throw err;
    console.log(`canceled "${query}"`);
  }
}

await Promise.all([onInput('n'), onInput('no'), onInput('node')]);
console.log('shown:', shown);
canceled "n"
canceled "no"
shown: results for "node"

File system races

Files are shared with other processes, so file races happen even between separate programs.

Check-then-create

Checking whether a file exists and then creating it is a time-of-check to time-of-use (TOCTOU) bug:

import { access, writeFile, readFile, rm } from 'node:fs/promises';

const file = 'owner.txt';
await rm(file, { force: true });

async function claim(name) {
  try {
    await access(file); // check...
    return `${name}: already claimed`;
  } catch {
    await writeFile(file, name); // ...then act
    return `${name}: claimed it`;
  }
}

console.log(await Promise.all([claim('worker-1'), claim('worker-2')]));
console.log('file contains:', await readFile(file, 'utf8'));
[ 'worker-1: claimed it', 'worker-2: claimed it' ]
file contains: worker-2

Both believe they won. Instead, just try the operation and let the operating system decide atomically. The 'wx' flag creates the file and fails with EEXIST if it's already there:

import { writeFile, readFile, rm } from 'node:fs/promises';

const file = 'owner.txt';
await rm(file, { force: true });

async function claim(name) {
  try {
    // 'wx' = create the file, fail with EEXIST if it already exists
    await writeFile(file, name, { flag: 'wx' });
    return `${name}: claimed it`;
  } catch (err) {
    if (err.code !== 'EEXIST') throw err;
    return `${name}: already claimed`;
  }
}

console.log(await Promise.all([claim('worker-1'), claim('worker-2')]));
console.log('file contains:', await readFile(file, 'utf8'));
[ 'worker-1: claimed it', 'worker-2: already claimed' ]
file contains: worker-1

This works across processes too, which makes an exclusively created file a simple lock file (remember to delete it when done). The same rule applies to directories: call mkdir() and handle EEXIST, or use mkdir(path, { recursive: true }), which doesn't fail if the directory exists. See Avoiding race conditions when creating or using an existing directory.

The Node.js documentation warns against calling fs.access() or fs.stat() before opening a file for exactly this reason. Checking first is fine for showing a message to a user, but not for deciding whether an operation is safe.

Concurrent read-modify-write of a file

Using a JSON file as a tiny database has the lost update problem from the start of this article:

import { readFile, writeFile, rm } from 'node:fs/promises';

const file = 'counters.json';
await writeFile(file, '{}');

async function bump(name) {
  const data = JSON.parse(await readFile(file, 'utf8'));
  data[name] = (data[name] ?? 0) + 1;
  await writeFile(file, JSON.stringify(data));
}

await Promise.all(['a', 'b', 'c', 'a', 'b', 'a'].map(bump));
console.log(await readFile(file, 'utf8'));
await rm(file);
{"c":1}

Six increments, one survived (the exact result varies between runs). Worse, concurrent writeFile() calls on the same file can interleave and leave invalid JSON, and a reader may see a half-written file.

Serialize updates with a mutex, and write to a temporary file and rename() it over the original, so readers see either the old or the new content but never a mix:

import { readFile, writeFile, rename, rm } from 'node:fs/promises';

class Mutex {
  #tail = Promise.resolve();
  run(fn) {
    const result = this.#tail.then(() => fn());
    this.#tail = result.catch(() => {});
    return result;
  }
}

const file = 'counters.json';
const fileLock = new Mutex();
await writeFile(file, '{}');

function bump(name) {
  return fileLock.run(async () => {
    const data = JSON.parse(await readFile(file, 'utf8'));
    data[name] = (data[name] ?? 0) + 1;
    // write to a temp file and rename, so readers never see half a file
    await writeFile(`${file}.tmp`, JSON.stringify(data));
    await rename(`${file}.tmp`, file);
  });
}

await Promise.all(['a', 'b', 'c', 'a', 'b', 'a'].map(bump));
console.log(await readFile(file, 'utf8'));
await rm(file);
{"a":3,"b":2,"c":1}

The mutex protects against concurrency within this process only. If several processes write the file, use a lock file ('wx' as above) or switch to a real database. More about the temp-file-and-rename pattern is in Temporary files.

Events that fire before you listen

An EventEmitter doesn't remember past events. If an event is emitted while your code is awaiting something else, a listener added later never fires:

import { EventEmitter, once } from 'node:events';
import { setTimeout as sleep } from 'node:timers/promises';

class Connection extends EventEmitter {
  ready = false;
  constructor() {
    super();
    setTimeout(() => {
      this.ready = true;
      this.emit('ready');
    }, 10);
  }
}

const conn = new Connection();
await sleep(50); // some other async setup happens first

await once(conn, 'ready'); // 'ready' was emitted while we were sleeping
console.log('connected');
Warning: Detected unsettled top-level await at file:///.../ready.mjs:18
await once(conn, 'ready'); // 'ready' was emitted while we were sleeping
^

Nothing keeps the event loop alive, so the process exits with code 13 instead of printing connected. In a server the promise would just hang forever.

Either attach listeners right after creating the object, before any await, or record the state and check it before waiting (imports as above):

class Connection extends EventEmitter {
  ready = false;
  constructor() {
    super();
    setTimeout(() => {
      this.ready = true;
      this.emit('ready');
    }, 10);
  }

  async waitReady() {
    if (!this.ready) {
      await once(this, 'ready');
    }
  }
}

const conn = new Connection();
await sleep(50);
await conn.waitReady();
console.log('connected');
connected

A promise is a good model for one-time events like this, since it remembers its result: store a readyPromise and let anyone await it at any time.

Worker threads and shared memory

With worker_threads and SharedArrayBuffer, JavaScript really does run in parallel on several threads, and you get data races like in C or Java. An ordinary counter[0]++ is three steps (read, add, write), and two threads can interleave them. Atomics operations are indivisible:

import { Worker, isMainThread, workerData } from 'node:worker_threads';

const WORKERS = 4;
const ITERATIONS = 1_000_000;

if (isMainThread) {
  const shared = new SharedArrayBuffer(8);
  const counters = new Int32Array(shared); // [plain, atomic]

  const workers = [];
  for (let i = 0; i < WORKERS; i++) {
    const w = new Worker(new URL(import.meta.url), { workerData: shared });
    workers.push(new Promise((resolve) => w.on('exit', resolve)));
  }
  await Promise.all(workers);

  console.log('expected:', WORKERS * ITERATIONS);
  console.log('plain   :', counters[0]);
  console.log('atomic  :', Atomics.load(counters, 1));
} else {
  const counters = new Int32Array(workerData);
  for (let i = 0; i < ITERATIONS; i++) {
    counters[0]++; // read, add, write: three separate steps
    Atomics.add(counters, 1, 1); // one indivisible step
  }
}
expected: 4000000
plain   : 2596435
atomic  : 4000000

The plain counter lost over a million increments, and the number differs on every run. Besides Atomics.add(), there are sub, and, or, exchange and compareExchange() (the building block for lock-free algorithms), plus Atomics.wait() and Atomics.notify() to block a thread until another wakes it.

Most code doesn't need this: if workers communicate only with postMessage(), data is copied and nothing is shared. See Multithreading for worker basics.

Across processes: let the database do it

A web app usually runs as several processes or containers, so an in-memory mutex doesn't protect anything. Push the read-modify-write into the database as one atomic operation instead.

The withdraw example becomes a single conditional UPDATE. The check (balance >= amount) and the change happen together, and the number of changed rows tells you whether it succeeded. This uses the built-in node:sqlite module, but the SQL is the same in PostgreSQL or MySQL:

import { DatabaseSync } from 'node:sqlite';

const db = new DatabaseSync(':memory:');
db.exec(`
  CREATE TABLE accounts (id INTEGER PRIMARY KEY, balance INTEGER NOT NULL);
  INSERT INTO accounts VALUES (1, 100);
`);

// check and update in a single statement: the database makes it atomic
const withdrawStmt = db.prepare(`
  UPDATE accounts SET balance = balance - :amount
  WHERE id = :id AND balance >= :amount
`);

function withdraw(id, amount) {
  const { changes } = withdrawStmt.run({ id, amount });
  return changes === 1 ? 'ok' : 'insufficient funds';
}

console.log(withdraw(1, 80));
console.log(withdraw(1, 80));
console.log(db.prepare('SELECT balance FROM accounts WHERE id = 1').get());
ok
insufficient funds
[Object: null prototype] { balance: 20 }

When the change can't be expressed as one statement (a user edits a document in a form and saves it later), use optimistic locking. Store a version number, and only save if the version hasn't changed since you read it:

import { DatabaseSync } from 'node:sqlite';

const db = new DatabaseSync(':memory:');
db.exec(`
  CREATE TABLE docs (id INTEGER PRIMARY KEY, body TEXT, version INTEGER NOT NULL);
  INSERT INTO docs VALUES (1, 'v1 text', 1);
`);

const load = (id) => db.prepare('SELECT body, version FROM docs WHERE id = ?').get(id);
const save = db.prepare(`
  UPDATE docs SET body = :body, version = version + 1
  WHERE id = :id AND version = :version
`);

// two users open the same document
const alice = load(1);
const bob = load(1);

let r = save.run({ id: 1, body: 'alice edit', version: alice.version });
console.log('alice saved:', r.changes === 1);

r = save.run({ id: 1, body: 'bob edit', version: bob.version });
console.log('bob saved:', r.changes === 1); // conflict: reload and retry

console.log(load(1));
alice saved: true
bob saved: false
[Object: null prototype] { body: 'alice edit', version: 2 }

Bob's save is rejected instead of silently overwriting Alice's work. The app can reload the document and show him the conflict, or retry automatically.

Other tools for the same job:

Finding race conditions

Races hide in development because everything is fast and one request runs at a time. Some ways to flush them out:

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents