Sobes.tech
Middle+

Are race conditions possible in single-threaded Node.js?

sobes.tech AI

Answer from AI

In single-threaded Node.js, classic data races like in multithreaded systems are impossible because all JavaScript code runs in a single thread.

However, data races can occur due to asynchronous operations and non-blocking I/O. For example, if two asynchronous calls modify a shared resource without proper synchronization, their execution order can lead to unpredictable states.

Example:

let counter = 0;

async function increment() {
  const current = counter;
  await new Promise(resolve => setTimeout(resolve, 10)); // simulate async operation
  counter = current + 1;
}

async function run() {
  await Promise.all([increment(), increment()]);
  console.log(counter); // might be 1 instead of 2 due to race condition
}

run();

Thus, data races are possible at the level of asynchronous operations even in single-threaded Node.js.