A Systematic Approach to Debugging Async Race Conditions in Node.js
Every Node.js developer eventually meets the same class of bug: the code looks correct, the tests pass on a laptop, and then production starts returning stale data, double-charging customers, or overwriting records — but only sometimes, and never when you are watching. In my experience, these are rarely "random" bugs. They are race conditions: two or more asynchronous operations whose outcome depends on the order in which they finish, in a program that quietly assumed one particular order.
This article walks through a systematic way to find, reproduce, and fix async race conditions in Node.js 20. I will use a small but realistic example — a cache refresh in an order service — and show the exact steps I use on client projects: stabilize a reproduction, instrument the event loop's interleavings, identify the shared state, and then choose the smallest synchronization primitive that removes the race for good.
Why Async Code Races Even on a Single Thread
Newcomers often assume Node cannot have race conditions because JavaScript runs on a single thread. That is true at the level of individual statements: no two lines of your JavaScript execute at the exact same instant. But races in Node are not about parallel execution. They are about interleaving.
Every await is a potential context switch. When your function awaits a database query, a file read, or an HTTP call, the event loop is free to run other callbacks — including another invocation of the very same function. If two invocations read and write shared state across an await boundary, their operations can interleave in ways the author never intended:
Request A: read cache (miss) ──► await fetch ──► write cache
Request B: read cache (miss) ──► await fetch ──► write cache
Neither request did anything wrong locally. The bug lives in the gap between the read and the write. Once you start looking for that gap — a check, then an await, then an act on the result of the check — you will find most production races within an afternoon.
The Bug: A Cache That Refreshes Twice (and Sometimes Backwards)
Consider this simplified cache from an order-status service. It caches an expensive aggregate query for 30 seconds:
// cache.js
let cachedValue = null;
let expiresAt = 0;
export async function getOrderSummary(db, orderId) {
const now = Date.now();
if (cachedValue !== null && now < expiresAt) {
return cachedValue;
}
// Expensive query: 80–200 ms in production
const fresh = await db.fetchOrderSummary(orderId);
cachedValue = fresh;
expiresAt = Date.now() + 30_000;
return fresh;
}
Two distinct bugs hide in these few lines.
Bug 1: duplicate work. If ten requests arrive while the cache is cold, all ten see cachedValue === null, all ten run the expensive query, and all ten write the cache. This is the classic "cache stampede." It is wasteful, but usually not corrupting.
Bug 2: the stale write wins. Suppose request A starts fetching at t=0 and the query takes 200 ms because the database is loaded. Request B starts at t=150 ms, gets a fast 20 ms query, and writes a fresh summary at t=170 ms. At t=200 ms, request A finishes and overwrites B's fresher value with data that was read from the database earlier. For the next 30 seconds, the service serves a stale summary — and the expiry timestamp was just extended by the stale write, so the wrong value sticks around even longer.
Bug 2 is the dangerous one, and it will never appear in a unit test that runs requests sequentially.
Step 1: Build a Deterministic Reproduction
You cannot fix what you cannot reproduce on demand. "It happens in production about twice a day" is not a reproduction. The trick is to replace real timing with controlled timing: use a fake dependency whose latency you control precisely.
// repro.mjs
import { getOrderSummary } from "./cache.js";
function fakeDb(latencyMs, value) {
return {
async fetchOrderSummary() {
await new Promise((resolve) => setTimeout(resolve, latencyMs));
return value;
},
};
}
// A is slow and returns the OLD summary; B is fast and returns the NEW one.
const slowDb = fakeDb(200, { total: 100, version: "old" });
const fastDb = fakeDb(20, { total: 120, version: "new" });
const a = getOrderSummary(slowDb, "order-42"); // starts first
await new Promise((r) => setTimeout(r, 50)); // let B start while A is in flight
const b = getOrderSummary(fastDb, "order-42");
console.log("B returned:", await b);
console.log("A returned:", await a);
// Read the cache once more — no DB hit, straight from cache.
const cached = await getOrderSummary(fastDb, "order-42");
console.log("Cache now holds:", cached);
Running node repro.mjs prints:
B returned: { total: 120, version: 'new' }
A returned: { total: 100, version: 'old' }
Cache now holds: { total: 100, version: 'old' }
The last line is the smoking gun. B produced the correct, newer answer, yet the cache ends up holding A's stale result. The reproduction is deterministic: it fails the same way on every run, in under a second, with no database and no network. That is the standard I aim for before touching the fix. If your reproduction needs "run it 500 times and hope," wrap the racy section in a loop with randomized delays and log the interleaving — but keep pushing until the failure is boringly reliable.
Step 2: Instrument the Interleaving, Not Just the Outcome
Once the bug reproduces, add tracing that shows order, not just values. A tiny helper that stamps each operation with a sequence number and a request ID turns a confusing log into a timeline:
let seq = 0;
function trace(requestId, event, detail = "") {
console.log(`${String(++seq).padStart(2, "0")} [${requestId}] ${event} ${detail}`);
}
Sprinkle calls at every await boundary — before the fetch, after the fetch, at the write — and rerun the reproduction. You should see B's write at sequence position n, followed by A's write at n+1 with an older payload. I attach this timeline to the bug report: reviewers can see the race instead of taking my word for it.
AsyncLocalStorage (from node:async_hooks) also helps here: it propagates a request ID through awaits without threading it through every function signature — invaluable when the racy code spans several modules.
Step 3: Name the Shared State and the Invariant
Before choosing a fix, write down two things:
-
The shared state. Here:
cachedValueandexpiresAt, mutated by every concurrent caller. - The invariant that was violated. "The cache must never be overwritten by a result whose fetch started before the fetch that produced the current value."
Most failed fixes I review skip this step. The developer adds a lock or a flag, the reproduction stops failing, but a second interleaving — say, an error thrown mid-fetch — still corrupts state, because the fix guarded the code path instead of restoring the invariant.
Step 4: Fix With the Smallest Primitive That Restores the Invariant
For this cache, the cleanest fix is promise memoization: store the in-flight promise, not just the finished value. Concurrent callers then share one fetch instead of racing several.
// cache-fixed.js
let cachedValue = null;
let expiresAt = 0;
let inFlight = null;
export async function getOrderSummary(db, orderId) {
const now = Date.now();
if (cachedValue !== null && now < expiresAt) {
return cachedValue;
}
if (inFlight !== null) {
return inFlight; // join the fetch already in progress
}
inFlight = (async () => {
try {
const fresh = await db.fetchOrderSummary(orderId);
cachedValue = fresh;
expiresAt = Date.now() + 30_000;
return fresh;
} finally {
inFlight = null; // always clear, success or failure
}
})();
return inFlight;
}
Why this works:
-
One writer. Only the invocation that created
inFlightever writescachedValue. Everyone else awaits the same promise, so a slow fetch can no longer overwrite a fast one — there is no second fetch. - The stampede disappears too. Ten concurrent cold-cache requests share a single query.
-
Failure is handled. The
finallyblock clearsinFlighteven when the fetch rejects, so a transient database error does not wedge the cache forever. Every waiter receives the same rejection and can retry or fail the request. Forgetting this cleanup is the most common bug in hand-rolled versions of this pattern.
Note what I did not reach for: a mutex library. Node's single thread means a simple "store the promise" pattern covers a large share of real races. Save locks for cases where the critical section itself must be serialized across different operations — for example, read-modify-write cycles against a file or an external API — and even then, prefer a small promise-chain queue you can read in one sitting over a general-purpose semaphore.
A Note on the await-Then-Act Pattern Elsewhere
The same shape appears in check-then-act business logic:
// Risky: two concurrent calls can both pass the check.
if ((await account.balance()) >= amount) {
await account.debit(amount);
}
Here promise memoization does not apply; the operations are not identical, they are competing. The honest fixes are to push the check into the same atomic operation as the debit (a conditional UPDATE ... WHERE balance >= ? in SQL, checking the affected-row count), or to serialize operations per account with a keyed queue. The principle generalizes: whenever a decision depends on state you read before an await, assume another caller changed that state during the gap, and either re-validate after the await or make check-and-act atomic.
Step 5: Verify the Fix Against the Original Reproduction
Rerun repro.mjs against the fixed module. Expected output:
B returned: { total: 100, version: 'old' }
A returned: { total: 100, version: 'old' }
Cache now holds: { total: 100, version: 'old' }
B now joins A's in-flight fetch and receives A's result — only one fetch happens, so there is exactly one value in play, and the cache matches it. In a real service B's caller might prefer fresher data, but correctness comes first: a consistent, slightly older answer beats an inconsistent newer one, and the 30-second TTL bounds the staleness.
Then promote the reproduction into a regression test. The fake-DB approach maps directly onto node:test:
import { test } from "node:test";
import assert from "node:assert/strict";
// ... import the fixed getOrderSummary and a call-counting fakeDb
test("concurrent cold-cache calls trigger exactly one fetch", async () => {
let calls = 0;
const db = {
async fetchOrderSummary() {
calls++;
await new Promise((r) => setTimeout(r, 30));
return { total: 100 };
},
};
const [a, b] = await Promise.all([
getOrderSummary(db, "order-42"),
getOrderSummary(db, "order-42"),
]);
assert.equal(calls, 1);
assert.deepEqual(a, b);
});
Finally, stress the fix the way production will: a short loop firing a few hundred concurrent calls with randomized fake latencies, asserting the fetch count stays at one per TTL window and the cached value always equals the fetched value. Five minutes of this catches the interleavings your single deterministic case missed.
A Checklist for Your Next Async Race
When a "sometimes wrong" bug lands on my desk, I work through the same list:
- Reproduce deterministically. Control latencies with fakes; never debug against production timing.
-
Trace the interleaving. Sequence-stamped logs at every
awaitboundary; AsyncLocalStorage for request IDs. - Find the shared state. Module-level variables, caches, files, and database rows all count.
- Write the invariant down. One sentence: what must always be true when the dust settles?
- Pick the smallest fix. Share the in-flight promise, make check-and-act atomic, or serialize per key — in that order of preference.
- Keep the reproduction as a test. If the race cannot regress silently, it usually stays fixed.
Race conditions feel mysterious only while their timing is uncontrolled. Once you can make the bug fail on command, it becomes an ordinary engineering problem — and ordinary problems have systematic solutions.
zuan peng is a JavaScript and TypeScript developer who fixes production bugs and builds automation tooling for small teams. Every engagement includes human review of the final code before delivery.
Top comments (0)