How to Avoid Async Race Conditions
Prevent async races: serialize access to shared state, use a keyed mutex, ignore stale responses, and test the interleavings that break.
On this page
Introduction
Async code yields control at every await, and that yield is where races hide. Two operations read a value, both await something, both write their result, and one update is lost because neither saw the other’s change. The code looks sequential because it is written in order, but the runtime interleaves the awaits, so the sequence the author imagined is not the sequence that runs.
This tutorial covers finding shared state, serializing access with a mutex or a keyed lock, ignoring stale responses in read-modify patterns, and testing the interleavings that break. The examples use a keyed mutex and a request tag, and the reasoning applies to any async runtime.
Find the shared state that races
A race needs shared state and at least one await between a read of it and a write to it. Look for a read-modify-write across an await: reading a counter, then awaiting, then writing the incremented value. Look for a cache that two operations populate, a connection pool that two operations draw from, and a document that two handlers update. The await between the read and the write is the window the race needs.
Not every shared state races, and not every race matters. A read-only cache is safe to read concurrently; the problem is the write path. A counter that only one operation type touches may be safe if it never awaits while holding a partial update. Focus on state that is read, awaited on, and written, where the value written depends on the value read.
// race: two calls read count, await, and both write the same incremented value
async function increment(key) {
const current = await store.get(key); // both read, say 0
await new Promise((r) => setTimeout(r, 1)); // the window
await store.set(key, current + 1); // both write 1: one update lost
}
Serialize access with a mutex
A mutex lets one operation at a time enter a critical section, so the read-modify-write completes before the next begins. Wrap the section that reads and writes the shared state in the mutex, and release it in a finally so a failure does not hold it. The critical section should be as small as possible, covering only the shared-state access, not unrelated awaited work.
For state partitioned by a key, a keyed mutex serializes operations on the same key while letting different keys run in parallel. A cache keyed by user id, a document keyed by an id, a counter keyed by a name all benefit: the contention is only between operations on the same key, so unrelated work does not block. This is the common right shape, because most shared state is partitioned.
class KeyedMutex {
private chains = new Map<string, Promise<unknown>>();
run<T>(key: string, fn: () => Promise<T>): Promise<T> {
const prev = this.chains.get(key) ?? Promise.resolve();
const next = prev.then(fn, fn); // serialise on the same key
this.chains.set(key, next.catch(() => {})); // keep the chain alive on failure
return next;
}
}
const mutex = new KeyedMutex();
await mutex.run('user:42', async () => { /* read-modify-write safely */ });
Ignore stale responses in read-modify patterns
In a client, a newer request must not be overwritten by an older response that arrives later. Tag each request with a sequence number, and when a response arrives, apply it only if its tag is the latest one. This is the last-write-wins problem solved on the read side: the state reflects the latest request, not whichever response happened to arrive last.
This is common with a search box or a filter: request one, request two, response one arrives after response two, and the stale result overwrites the fresh one. A sequence tag, or comparing the request’s parameters to the current ones, discards the stale response. The same idea applies to a cache refresh where an older fetch must not replace a newer value.
let latest = 0;
async function search(query: string, render: (r: unknown) => void) {
const tag = ++latest;
const result = await fetch('/search?q=' + encodeURIComponent(query)).then((r) => r.json());
if (tag !== latest) return; // a newer request superseded this one
render(result);
}
Make writes idempotent and compare-and-set
Where a race cannot be fully serialized, a compare-and-set write makes it safe: write the new value only if the current value is the one you read, and retry if it changed. The database does this with a version column and a conditional update, or with an atomic increment that does not read-then-write. An atomic operation is the cleanest fix because it removes the read-modify-write window entirely.
For a counter, an atomic increment is better than a mutex, because the database does the read and write in one operation. For a document, a conditional update on a version is the optimistic-concurrency pattern. Prefer the atomic or conditional write where the state lives in a store that supports it, and use a mutex for state held in the process, where there is no such primitive.
-- atomic increment: no read-modify-write window in the application
UPDATE counters SET value = value + 1 WHERE name = $1;
-- compare-and-set: only write if the version still matches what we read
UPDATE documents SET body = $1, version = version + 1
WHERE id = $2 AND version = $3; -- zero rows affected means a concurrent writer won
Test the interleaving that breaks
Force the racing order with artificial delays: make operation A await in the middle, start B during that await, and assert the final state is correct. On the unguarded version, the same test should produce the wrong state, which proves the test exercises the race. Then apply the mutex or the atomic write and assert the state is correct under the same interleaving.
Test the stale-response case by making the first request slow and the second fast, and assert the rendered state reflects the second. Test the fail-fast case by making one operation throw while another is waiting on the same key, and assert the mutex is released so the second proceeds. These tests turn timing-dependent bugs into deterministic checks.
node -e '
const { incrementRace, incrementSafe } = require("./counter");
// fire two concurrent increments and await both
Promise.all([incrementRace("k"), incrementRace("k")]).then(() => console.log("race result:", store.get("k"))); // 1, lost
Promise.all([incrementSafe("k"), incrementSafe("k")]).then(() => console.log("safe result:", store.get("k"))); // 2
'
Common pitfalls
A read-modify-write across an await with no guard, a broad lock that serializes unrelated keys and hurts throughput, applying a response without checking whether a newer request superseded it, a mutex not released on failure so it deadlocks, and a hand-rolled counter instead of an atomic increment are the recurring mistakes. A keyed mutex or an atomic write, a request tag, release in finally, and a conditional update address them.
Conclusion
An async race is two operations interleaving on shared state across an await. Find the read-modify-write, serialize the same key with a mutex or use an atomic increment, discard stale responses with a request tag, and make writes conditional where the store supports it. Self-check by forcing the racing order and asserting the state stays correct, and that the unguarded version fails. Then the runtime’s interleaving no longer changes the result.
Sources: MDN: async function and the event loop, MDN: Race condition (Wikipedia), Node.js: async mutex patterns.
FAQ
- What is an async race?
- It is when two async operations interleave on shared state such that the result depends on their timing. The classic is a read-modify-write where both read the old value, both write, and one update is lost. Because awaits yield control, the interleaving is easy to produce accidentally.
- Does a mutex hurt performance?
- Only where it is held. A keyed mutex lets unrelated keys proceed in parallel while serializing the same key, so the contention is limited to operations that actually touch the same state. Broad locks are the ones that hurt.
Report a problem with this articleOpens a pre-filled issue on GitHub.