← Back to Node.js, page 3

nodejs-0056 · Hard senior

Can race conditions happen in single-threaded Node.js, and how do you serialize async work with a mutex or queue?

Yes. Between an await and the code after it, other callbacks can run, so a read-modify-write across an await can lose updates. Serialize such sections with a promise-based mutex or a queue, or move the whole update into one atomic operation such as a database transaction or an atomic SQL update.

Full answer

JavaScript runs one piece of code at a time, so a counter++ in plain code is safe. The danger starts when an await sits inside the update:

  1. Task A reads balance = 100.
  2. await something (a database call, a delay).
  3. Meanwhile task B reads balance = 100 too.
  4. A writes 150. B writes 150. One deposit is lost.

The same problem appears with cached files that are read, changed and written back, with "check then create" logic, and with counters in memory shared between concurrent requests.

Solutions, from best to simplest:

  • Make the operation atomic where the data lives: UPDATE accounts SET balance = balance + 50, a Redis INCR, or a database transaction with the right isolation level or row lock.
  • Serialize in the process with a mutex. A promise-based mutex keeps a chain: each caller waits for the previous holder to finish, then runs. Always release in finally.
  • Use a queue with concurrency 1 per key (for example one queue per account id) to keep unrelated work parallel.
  • Avoid shared mutable state. Have one owner function or worker and send messages.

A process mutex protects only one process. With several servers or cluster workers, you need a distributed lock or database-level atomic operations. Also keep critical sections short, since waiting tasks form a line and a slow holder blocks everyone.

javascript
class Mutex {
  #tail = Promise.resolve();
  async run(task) {
    let release;
    const gate = new Promise((resolve) => { release = resolve; });
    const previous = this.#tail;
    this.#tail = previous.then(() => gate); // the next caller waits for this gate
    await previous;                          // wait for the earlier holder
    try {
      return await task();
    } finally {
      release();                             // always let the next caller in
    }
  }
}

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function deposit(account, amount) {
  const current = account.balance;  // read
  await wait(5);                    // a database call, for example
  account.balance = current + amount; // write: may overwrite someone else's update
}

async function main() {
  // Without a lock: three deposits of 50 run at the same time.
  const unsafe = { balance: 100 };
  await Promise.all([deposit(unsafe, 50), deposit(unsafe, 50), deposit(unsafe, 50)]);
  console.log('without lock, expected 250, got:', unsafe.balance);

  // With a mutex: the deposits run one after another.
  const safe = { balance: 100 };
  const mutex = new Mutex();
  await Promise.all([1, 2, 3].map(() => mutex.run(() => deposit(safe, 50))));
  console.log('with mutex, expected 250, got:  ', safe.balance);

  // An error inside the lock does not block later callers.
  const failing = mutex.run(async () => { throw new Error('task failed'); });
  await failing.catch((err) => console.log('first task:', err.message));
  console.log('later task still runs:', await mutex.run(async () => 'ran after the failure'));
}

main();

The unsafe version loses two of the three deposits because every call read the same starting balance. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): without lock, expected 250, got: 150 with mutex, expected 250, got: 250 first task: task failed later task still runs: ran after the failure

Key points

  • An await inside read-modify-write allows interleaving.
  • Atomic operations in the datastore are the best fix.
  • A mutex is a promise chain. Always release in finally.
  • Per-key queues keep unrelated work parallel.
  • A process mutex does not protect several processes.

Common mistakes

  • Believing single-threaded means no race conditions.
  • Forgetting to release the lock when the task throws.
  • Using an in-memory mutex when the app runs on several servers.
  • Holding a lock during a slow network call.

Follow-ups

  • How would you lock per account id instead of globally?
  • How does a database row lock differ from a process mutex?
  • How do optimistic locks with version numbers work?

Tips

  • Walk through the four-step interleaving.
  • Say 'make it atomic in the database' before you offer a mutex.
  • Mention the multi-process limitation.