Locks and synchronization
suggest changeJavaScript runs your code on a single thread, so two statements never execute at the same time. That's why people often assume Node.js programs don't need locks.
They do. Every await is a point where your function pauses and other code runs. If a function reads some state, awaits something and then writes the state back, another call can sneak in between and both will work with stale data. With worker_threads and multiple processes you also get real parallelism.
This article covers the tools for each case:
| Problem | Tool |
|---|---|
| Async functions interleaving in one thread | promise-based mutex, navigator.locks |
| Lock per resource (per user, per file) | keyed mutex, navigator.locks with a name |
| Limit how many operations run at once | semaphore |
| Many callers want the same slow result | single-flight (share one promise) |
| Worker threads sharing memory | SharedArrayBuffer + Atomics |
| Several processes | lock file created with the wx flag |
The examples are ES modules (save them as .mjs) and were run with Node.js 24.
The race condition in single-threaded code
Here is a bank account where withdrawing checks the balance, does some async work, and then updates the balance:
import { setTimeout as sleep } from 'node:timers/promises';
let balance = 100;
async function withdraw(amount) {
const current = balance; // read
await sleep(10); // e.g. a database call
if (current < amount) throw new Error('insufficient funds');
balance = current - amount; // write
return balance;
}
const results = await Promise.allSettled([withdraw(80), withdraw(80)]);
console.log(results.map((r) => r.status));
console.log('balance:', balance);
[ 'fulfilled', 'fulfilled' ]
balance: 20
We withdrew 160 from an account holding 100, and the balance says 20. Both calls read balance as 100 before either wrote it back. This is a classic read-modify-write race, and the only ingredient it needs is an await between the read and the write.
The same bug shows up with a real database (SELECT then UPDATE), with files (read JSON, modify, write), and with caches. If the state lives in a database, use the database's tools first: transactions, SELECT ... FOR UPDATE, atomic updates like UPDATE accounts SET balance = balance - $1 WHERE balance >= $1. Locks in Node.js protect state that only your process touches.
A promise-based mutex
A mutex (mutual exclusion lock) lets only one async function at a time run the critical section. The others wait in line.
The simplest implementation chains promises. Each caller waits for the previous holder's promise and creates a new one for the next caller:
import { setTimeout as sleep } from 'node:timers/promises';
class Mutex {
#last = Promise.resolve();
// Resolves to a release() function once the lock is ours.
lock() {
let release;
const next = new Promise((resolve) => { release = resolve; });
const ready = this.#last.then(() => release);
this.#last = next;
return ready;
}
async runExclusive(fn) {
const release = await this.lock();
try {
return await fn();
} finally {
release();
}
}
}
const mutex = new Mutex();
let balance = 100;
function withdraw(amount) {
return mutex.runExclusive(async () => {
const current = balance;
await sleep(10);
if (current < amount) throw new Error('insufficient funds');
balance = current - amount;
return balance;
});
}
const results = await Promise.allSettled([withdraw(80), withdraw(80), withdraw(10)]);
for (const r of results) console.log(r.status, r.value ?? r.reason.message);
console.log('balance:', balance);
fulfilled 20
rejected insufficient funds
fulfilled 10
balance: 10
Things to notice:
- Waiters are served in FIFO order, because each one waits on the promise of the caller before it.
runExclusive()releases the lock infinally, so a function that throws doesn't block everyone after it. Prefer it over callinglock()andrelease()by hand.- The
nextpromise always resolves (never rejects), so an error in one critical section doesn't break the chain.
Keep critical sections short. While one call holds the lock, every other caller is waiting, so you have turned that piece of code into a sequential queue.
Libraries such as async-mutex on npm offer the same idea with extras (timeouts, tryAcquire, semaphores). But in modern Node.js you often don't need a library at all, see the Web Locks API below.
A lock per key
A single mutex serializes everything. Usually you only need to serialize operations on the same resource: updates to the same user may not overlap, but updates to different users can run in parallel.
A keyed mutex keeps one promise chain per key and removes the entry when the queue for that key is empty, so the map doesn't grow forever:
import { setTimeout as sleep } from 'node:timers/promises';
class KeyedMutex {
#tails = new Map(); // key -> promise that settles when the last holder releases
async runExclusive(key, fn) {
const prev = this.#tails.get(key) ?? Promise.resolve();
let release;
const tail = new Promise((resolve) => { release = resolve; });
this.#tails.set(key, tail);
await prev;
try {
return await fn();
} finally {
release();
// Nobody queued behind us: drop the entry so the map doesn't grow forever.
if (this.#tails.get(key) === tail) this.#tails.delete(key);
}
}
get size() { return this.#tails.size; }
}
const locks = new KeyedMutex();
const start = Date.now();
async function updateUser(id, label) {
return locks.runExclusive(`user:${id}`, async () => {
console.log(`${String(Date.now() - start).padStart(3)}ms start ${label}`);
await sleep(50);
});
}
await Promise.all([
updateUser(1, 'user 1, first'),
updateUser(1, 'user 1, second'),
updateUser(2, 'user 2'),
]);
console.log('entries left:', locks.size);
1ms start user 1, first
3ms start user 2
69ms start user 1, second
entries left: 0
User 2 starts right away. The second update of user 1 waits until the first one finishes (timer precision varies, so you'll see slightly different numbers).
A semaphore to limit concurrency
A semaphore is a lock with N permits instead of one. It's the right tool when parallelism is fine but unlimited parallelism is not: at most 5 requests to an external API, at most 10 open files, at most 2 heavy image conversions.
import { setTimeout as sleep } from 'node:timers/promises';
class Semaphore {
#permits;
#waiters = [];
constructor(permits) { this.#permits = permits; }
async acquire() {
if (this.#permits > 0) {
this.#permits--;
return;
}
await new Promise((resolve) => this.#waiters.push(resolve));
}
release() {
const next = this.#waiters.shift();
if (next) next(); // hand the permit directly to the next waiter
else this.#permits++;
}
async run(fn) {
await this.acquire();
try {
return await fn();
} finally {
this.release();
}
}
}
const sem = new Semaphore(2);
let active = 0;
async function download(n) {
return sem.run(async () => {
active++;
console.log(`start ${n} (active: ${active})`);
await sleep(100);
active--;
return n * 10;
});
}
const results = await Promise.all([1, 2, 3, 4, 5].map(download));
console.log(results);
start 1 (active: 1)
start 2 (active: 2)
start 3 (active: 2)
start 4 (active: 2)
start 5 (active: 2)
[ 10, 20, 30, 40, 50 ]
release() passes the permit straight to the next waiter instead of incrementing the counter. Otherwise a brand new caller could grab the permit before the waiter's promise callback runs, and waiters could starve.
A semaphore with 1 permit is a mutex.
The Web Locks API: navigator.locks
Node.js 24 ships the browser's Web Locks API as the global navigator.locks. It gives you named locks without writing any of the code above:
import { setTimeout as sleep } from 'node:timers/promises';
let balance = 100;
async function withdraw(amount) {
return navigator.locks.request('account', async (lock) => {
console.log(`holding ${lock.name} (${lock.mode}) for ${amount}`);
const current = balance;
await sleep(10);
if (current < amount) throw new Error('insufficient funds');
balance = current - amount;
return balance;
});
}
const results = await Promise.allSettled([withdraw(80), withdraw(80)]);
console.log(results.map((r) => r.value ?? r.reason.message));
holding account (exclusive) for 80
holding account (exclusive) for 80
[ 20, 'insufficient funds' ]
request(name, callback) waits until the lock named name is free, calls the callback, and holds the lock until the promise returned by the callback settles. The result (or the error) of the callback becomes the result of request(). The lock is always released, even when the callback throws.
The name works as a key, so navigator.locks.request(user:${id}, ...) gives you the keyed mutex for free.
Shared and exclusive locks
By default a lock is exclusive. With { mode: 'shared' } you get a readers-writer lock: any number of shared holders at once, but an exclusive request waits for all of them, and shared requests made after it wait for the exclusive one:
import { setTimeout as sleep } from 'node:timers/promises';
const start = Date.now();
const log = (msg) => console.log(`${String(Date.now() - start).padStart(3)}ms ${msg}`);
function read(n) {
return navigator.locks.request('config', { mode: 'shared' }, async () => {
log(`reader ${n} start`);
await sleep(50);
log(`reader ${n} done`);
});
}
function write() {
return navigator.locks.request('config', async () => {
log('writer start');
await sleep(50);
log('writer done');
});
}
const all = [read(1), read(2), write(), read(3)];
await sleep(10);
const state = await navigator.locks.query();
console.log('held:', state.held.map((l) => `${l.name}/${l.mode}`));
console.log('pending:', state.pending.map((l) => `${l.name}/${l.mode}`));
await Promise.all(all);
2ms reader 1 start
3ms reader 2 start
held: [ 'config/shared', 'config/shared' ]
pending: [ 'config/exclusive', 'config/shared' ]
64ms reader 1 done
64ms reader 2 done
65ms writer start
125ms writer done
125ms reader 3 start
185ms reader 3 done
Readers 1 and 2 run together. Reader 3 doesn't jump ahead of the waiting writer, so writers don't starve. navigator.locks.query() returns a snapshot of held and pending locks, which is handy when debugging a lock that never seems to become free.
Not waiting, or not waiting forever
Two options control waiting:
ifAvailable: truetakes the lock only if it's free right now. Otherwise the callback is called withnullimmediately.signaltakes anAbortSignal. If it aborts before the lock is granted,request()rejects and the callback never runs.
import { setTimeout as sleep } from 'node:timers/promises';
// Hold the lock for a while in the background.
const holder = navigator.locks.request('job', () => sleep(200));
// 1. ifAvailable: don't wait, get null instead.
await navigator.locks.request('job', { ifAvailable: true }, async (lock) => {
console.log('ifAvailable got:', lock);
});
// 2. signal: give up waiting after 50 ms.
try {
await navigator.locks.request('job', { signal: AbortSignal.timeout(50) }, async () => {
console.log('never printed');
});
} catch (err) {
console.log('gave up:', err.name);
}
await holder;
console.log('done');
ifAvailable got: null
gave up: TimeoutError
done
ifAvailable is a good fit for "run this periodic job unless the previous run is still going". A timeout turns a silent hang into an error you can log. See AbortSignal and timeouts for more on signals.
Locks across worker threads
navigator.locks is shared by all threads of a process, so it also coordinates worker threads. Here three workers append to the same file, and each one's two lines stay together:
import { Worker, isMainThread, threadId } from 'node:worker_threads';
import { appendFile, readFile, rm } from 'node:fs/promises';
import { setTimeout as sleep } from 'node:timers/promises';
const file = 'log.txt';
if (isMainThread) {
await rm(file, { force: true });
const workers = [1, 2, 3].map(() => new Worker(new URL(import.meta.url)));
await Promise.all(workers.map((w) => new Promise((r) => w.on('exit', r))));
console.log(await readFile(file, 'utf8'));
} else {
// A pending lock request doesn't keep the thread alive, so hold a timer.
const keepAlive = setInterval(() => {}, 60_000);
try {
await navigator.locks.request('log-file', async () => {
await appendFile(file, `thread ${threadId} begin\n`);
await sleep(20);
await appendFile(file, `thread ${threadId} end\n`);
});
} finally {
clearInterval(keepAlive);
}
}
thread 1 begin
thread 1 end
thread 3 begin
thread 3 end
thread 2 begin
thread 2 end
Watch out for the keepAlive timer. A request that is waiting for a lock held by another thread doesn't keep the event loop alive. Without the timer, workers 2 and 3 have nothing else to do, so they exit with a "Detected unsettled top-level await" warning and never write their lines.
Single-flight: share the work instead of locking
Sometimes the goal isn't "one at a time" but "only once". When 100 requests arrive at the same time and all miss the cache, you don't want 100 identical database queries.
Store the promise of the in-progress operation and give the same promise to everyone who asks while it's running:
import { setTimeout as sleep } from 'node:timers/promises';
const inFlight = new Map();
let fetches = 0;
async function loadConfig(name) {
fetches++;
await sleep(50); // pretend this is a slow network call
return { name, loadedAt: Date.now() };
}
function getConfig(name) {
let p = inFlight.get(name);
if (!p) {
p = loadConfig(name).finally(() => inFlight.delete(name));
inFlight.set(name, p);
}
return p;
}
const results = await Promise.all([getConfig('db'), getConfig('db'), getConfig('db')]);
console.log('fetches:', fetches);
console.log('same object:', results[0] === results[1] && results[1] === results[2]);
fetches: 1
same object: true
The check and the set happen with no await in between, so no other code can run between them. That's what makes it safe. The .finally() removes the entry when the operation finishes, including on failure, so the next call retries instead of getting a cached error forever.
Worker threads: SharedArrayBuffer and Atomics
Workers normally communicate by copying messages, which needs no locks. A SharedArrayBuffer is different: several threads see the same memory, and they really do run at the same moment.
Even counter++ is unsafe here, because it's three steps (read, add, write) and another thread can write in between:
import { Worker, isMainThread, workerData } from 'node:worker_threads';
const N = 1_000_000;
if (isMainThread) {
const shared = new SharedArrayBuffer(8);
const counters = new Int32Array(shared); // [0] plain, [1] atomic
const workers = [1, 2, 3, 4].map(
() => new Worker(new URL(import.meta.url), { workerData: shared }),
);
await Promise.all(workers.map((w) => new Promise((r) => w.on('exit', r))));
console.log('expected:', 4 * N);
console.log('plain :', counters[0]);
console.log('atomic :', Atomics.load(counters, 1));
} else {
const counters = new Int32Array(workerData);
for (let i = 0; i < N; i++) {
counters[0]++; // read, add, write: not atomic
Atomics.add(counters, 1, 1); // one indivisible operation
}
}
expected: 4000000
plain : 2857617
atomic : 4000000
The plain counter loses more than a million increments (the number changes from run to run). Atomics.add, Atomics.sub, Atomics.and, Atomics.or, Atomics.exchange and Atomics.compareExchange each do their read-modify-write as one indivisible step. For a single counter or flag, that's all you need.
A mutex for shared memory
When an update touches several values that must stay consistent, individual atomic operations aren't enough. You need a real lock. Atomics.compareExchange builds one, and Atomics.wait / Atomics.notify let waiting threads sleep instead of spinning:
// shared-mutex.mjs
const UNLOCKED = 0;
const LOCKED = 1;
export class SharedMutex {
// `i32` is an Int32Array over a SharedArrayBuffer, `index` is the lock slot.
constructor(i32, index = 0) {
this.i32 = i32;
this.index = index;
}
lock() {
// Try to flip 0 -> 1. If someone else holds it, sleep until notified.
while (Atomics.compareExchange(this.i32, this.index, UNLOCKED, LOCKED) !== UNLOCKED) {
Atomics.wait(this.i32, this.index, LOCKED);
}
}
unlock() {
Atomics.store(this.i32, this.index, UNLOCKED);
Atomics.notify(this.i32, this.index, 1); // wake one waiter
}
}
Atomics.wait(arr, i, LOCKED) sleeps only if the slot still holds LOCKED. If the lock was released between the failed compareExchange and the wait, it returns immediately and the loop tries again, so no wakeup is lost.
Four workers move money between 5 accounts. Each transfer subtracts from one account and adds to another, so the total must stay 5000:
import { Worker, isMainThread, workerData } from 'node:worker_threads';
import { SharedMutex } from './shared-mutex.mjs';
const ACCOUNTS = 5;
const useLock = process.argv[2] === 'lock';
if (isMainThread) {
// slot 0: the lock, slots 1..5: account balances
const shared = new SharedArrayBuffer(4 * (1 + ACCOUNTS));
const view = new Int32Array(shared);
for (let i = 1; i <= ACCOUNTS; i++) view[i] = 1000;
const workers = Array.from({ length: 4 },
() => new Worker(new URL(import.meta.url), { workerData: shared, argv: process.argv.slice(2) }));
await Promise.all(workers.map((w) => new Promise((r) => w.on('exit', r))));
const total = view.slice(1).reduce((a, b) => a + b, 0);
console.log(useLock ? 'with lock ' : 'without lock', 'total =', total);
} else {
const view = new Int32Array(workerData);
const mutex = new SharedMutex(view, 0);
for (let i = 0; i < 200_000; i++) {
const from = 1 + (i % ACCOUNTS);
const to = 1 + ((i * 7 + 3) % ACCOUNTS);
if (useLock) mutex.lock();
try {
view[from] -= 1;
view[to] += 1;
} finally {
if (useLock) mutex.unlock();
}
}
}
$ node transfers.mjs
without lock total = 4641
$ node transfers.mjs lock
with lock total = 5000
Atomics.wait blocks the thread completely. That's fine in a worker, but on the main thread it freezes the event loop: no timers, no I/O, no HTTP requests. On the main thread use Atomics.waitAsync(), which returns a promise instead of blocking, or keep the main thread out of shared-memory locking and let it talk to workers with messages.
Locking across processes
None of the above works between processes: cluster workers, several instances of a CLI tool, or a cron job running next to your server. Each process has its own memory and its own navigator.locks.
A portable way to lock between processes on one machine is a lock file. Opening a file with the wx flag creates it and fails with EEXIST if it already exists. The operating system does the check and the create as one atomic step, so only one process can succeed:
// file-lock.mjs
import { open, rm, stat } from 'node:fs/promises';
import { setTimeout as sleep } from 'node:timers/promises';
export async function withFileLock(lockPath, fn, { staleMs = 10_000, retryMs = 20 } = {}) {
for (;;) {
try {
// 'wx' fails with EEXIST if the file already exists: an atomic test-and-set.
const handle = await open(lockPath, 'wx');
await handle.writeFile(String(process.pid));
await handle.close();
break;
} catch (err) {
if (err.code !== 'EEXIST') throw err;
// Remove the lock if its owner crashed long ago.
const info = await stat(lockPath).catch(() => null);
if (info && Date.now() - info.mtimeMs > staleMs) {
await rm(lockPath, { force: true });
continue;
}
await sleep(retryMs);
}
}
try {
return await fn();
} finally {
await rm(lockPath, { force: true });
}
}
Four child processes each increment a number stored in a file 50 times:
import { fork } from 'node:child_process';
import { readFile, writeFile } from 'node:fs/promises';
import { withFileLock } from './file-lock.mjs';
const COUNTER = 'counter.txt';
const useLock = process.argv[2] === 'lock';
async function increment() {
const n = Number(await readFile(COUNTER, 'utf8'));
await writeFile(COUNTER, String(n + 1));
}
if (process.send === undefined) {
// parent: reset the counter and start 4 child processes
await writeFile(COUNTER, '0');
const children = [1, 2, 3, 4].map(() => fork(import.meta.filename, process.argv.slice(2)));
await Promise.all(children.map((c) => new Promise((r) => c.on('exit', r))));
console.log(useLock ? 'with lock ' : 'without lock', await readFile(COUNTER, 'utf8'));
} else {
for (let i = 0; i < 50; i++) {
if (useLock) await withFileLock(`${COUNTER}.lock`, increment);
else await increment();
}
process.disconnect();
}
$ node counter.mjs
without lock 20
$ node counter.mjs lock
with lock 200
Without the lock, processes read the file while another one is in the middle of rewriting it, and almost all increments are lost.
The hard part of lock files is a process that crashes while holding the lock. The file stays, and everyone waits forever. The code above treats a lock older than staleMs as abandoned, which means staleMs must be longer than the longest critical section. For production use, the proper-lockfile package handles this more carefully: it keeps refreshing the lock's modification time while you hold it and uses mkdir (also atomic) for the lock itself.
For processes on different machines, a local file doesn't help. Use a lock in shared infrastructure: a database row lock, PostgreSQL advisory locks (pg_advisory_lock), or a Redis lock (SET key token NX PX 30000), always with an expiry.
Deadlocks
A lock that is never released, or two pieces of code each waiting for the other, hangs your program. The most common case in Node.js is taking the same non-reentrant lock twice:
async function save(user) {
return navigator.locks.request('db', async () => {
console.log('saving', user);
await audit(`saved ${user}`); // also takes the 'db' lock
});
}
async function audit(msg) {
return navigator.locks.request('db', async () => {
console.log('audit:', msg);
});
}
await save('alice');
console.log('done');
saving alice
Warning: Detected unsettled top-level await at file:///.../deadlock.mjs:14
await save('alice');
^
audit() waits for save() to release 'db', and save() waits for audit() to finish. None of these locks is reentrant: holding a lock doesn't let the same code take it again. In a server the process wouldn't exit, the request would just hang.
Rules that avoid most deadlocks:
- Don't call code that takes a lock while holding the same lock. Split the function into an outer one that locks and an inner one that assumes the lock is already held.
- If you need several locks, always take them in the same order (for example, sorted by name).
- Use timeouts (
signal: AbortSignal.timeout(...)) so a deadlock becomes an error instead of a hang. - Always release in
finally, or use APIs likerunExclusive()andnavigator.locks.request()that do it for you.
Summary
- Any
awaitbetween reading and writing shared state is a potential race, even in single-threaded code. - For locks inside one process,
navigator.locks.request(name, fn)is built in, supports shared mode,ifAvailable, timeouts, and works across worker threads. - A promise-chain mutex or a semaphore is a few lines of code when you want your own.
- To avoid duplicate work, share one in-flight promise instead of locking.
- For
SharedArrayBuffer, useAtomicsoperations, andAtomics.compareExchange+Atomics.wait/notifyfor a full mutex. Never block the main thread withAtomics.wait. - Between processes, use a lock file created with
wx(with stale-lock handling), and between machines, use the database or Redis.