Request IDs in Node.js with AsyncLocalStorage

A request ID is useful until the interesting log line has somebody else's ID on it.
The server may still return the right response. The damage appears later, when you're trying to follow one request through a busy process and the logs confidently send you down the wrong corridor. Adding more log lines at that point mostly gives you a longer walk.
Passing context explicitly through every function is one way to keep ownership clear. For logging across a Node.js request, AsyncLocalStorage offers another: create a store at the request boundary and read it from the asynchronous work belonging to that scope. It became stable in Node 16.4; my example uses Node 16.6.2.
The useful part of the example is the broken callback queue. Ordinary promises behave correctly, two HTTP requests overlap, and then one deliberately awkward boundary loses the context. That gives us something specific to repair.
Create a Small Store When the Request is Accepted
I generate an internal request ID and enter the handler through run:
context.run(store, async () => {
log({ event: 'start', label });
await handleRequest();
});The store contains a request ID, its kind, and an optional upstream correlation value. It doesn't contain the entire request object, its credentials, or a mutable user record. Small, clearly owned context is easier to reason about and less likely to retain a large object graph accidentally.
A fresh store belongs to each accepted request. Putting a single object outside the handler and changing its requestId property would still be shared mutable state, however reassuring the variable's name looked.
My store is frozen because its identity fields don't need to change during the request. Freezing that object is not a general deep‑immutability mechanism, but it is sufficient for these flat values.
The Node 16.6.2 context documentation describes run, getStore, and the callback bridge used below. I prefer entering through run at an explicit boundary here; the example does not need to leave a new context installed across unrelated synchronous work.
Keep External Correlation Separate from Identity
An incoming X-Request-ID can help join logs across services, but the caller supplied it. Two callers can send the same value. A syntactically tidy identifier does not become trustworthy simply because it passes a regular expression.
My fixture always creates its own internal ID. It keeps the upstream value separately only when it is a string within a small length and character limit. The response returns the internal ID, giving the caller a value which identifies this service's accepted request.
The test sends the same upstream value on two concurrent requests and verifies that the internal IDs differ. It also checks absent, oversized, and malformed values. This is a correlation policy for the example, not a substitute for an organisation's tracing convention or a distributed trace protocol.
None of these fields authorises anything. Permission checks must still use the authenticated principal and the resource being accessed. A log label is a particularly poor place to hide an access‑control decision.
Establish What Already Propagates
Before adding a repair, I want a passing baseline. Each request logs at entry, after a resolved promise, and after setImmediate. Those records retain the accepted request's ID.
The two handlers are deliberately interleaved. The test waits until both have reached the queue, then releases B before A. It does not guess at timing by making one request sleep a little longer.
My event‑loop article explains the scheduling side. Scheduling tells us when work gets a turn; context tracking tells us which asynchronous chain that work belongs to. Concurrent requests do not require a global "current request" variable which changes whenever another handler runs.
Outside an active scope, getStore() returns undefined. My logger handles that explicitly and emits a null request ID. Inventing a fallback from the last request would make an unscoped startup message look helpfully correlated whilst quietly lying about its owner.
Break the Queue on Purpose
The faulty queue stores a callback and later calls it as an ordinary function. It does not preserve the context in which the callback was registered.
When the test drains that queue from outside a request scope, the callback sees no store. When it drains the same queue whilst another request context is active, both queued callbacks see the drainer's ID. The closure still knows its synthetic A or B label, which makes the mismatch obvious in the recorded events.
There is a useful detail here: the handler's continuation after awaiting the queue result still has its original request context. The callback's log is wrong; the later promise continuation is right. Calling the whole request "broken" would obscure the exact boundary which needs attention.
I covered the API distinction in my callbacks and promises article. Returning a promise can make a result convenient to await, but it doesn't retroactively give every callback inside the implementation the right execution context.
Capture Ownership Where the Task Enters the Queue
The corrected queue creates an AsyncResource when accepting the callback, whilst the originating request scope is active. When delivering the result, it uses that resource to invoke the callback:
try {
return resource.runInAsyncScope(callback, null);
} finally {
resource.emitDestroy();
}Creating the resource at delivery time would capture the drainer's context instead. That would add machinery without fixing the ownership problem.
The queue removes the task before delivery and releases its resource even when the callback throws. Its cancellation path also releases the resource without running the callback. My tests observe the asynchronous destroy hooks for both paths, as well as checking that the queue has no remaining task references.
With the repaired queue, every recorded event for A has A's accepted internal ID, and every event for B has B's. The deliberately wrong variants remain in the lab so a future change cannot make the test suite pass merely by ceasing to exercise the failure.
Give Jobs Their Own Starting Point
A worker is another boundary. My worker test begins with no active store, receives a small explicit job context, and enters its own run scope. Its job ID differs from the originating request ID; a separate parent field preserves the relationship.
This makes the ownership decision visible. A job which outlives an HTTP response shouldn't require retaining the request object to explain where it came from. Nor should an unrelated worker be expected to discover the caller's in‑process context automatically.
The logger itself accepts only the small set of fields it needs. A synthetic authorisation header and an extra email field are deliberately passed towards it in the tests and verified absent from the recorded output. An application with a richer logging schema still needs an explicit policy for those fields.
My async‑context lab includes the two HTTP requests, faulty and repaired queues, worker boundary, and assertions. Start with the record whose ID changes unexpectedly, then trace back to the point where that callback was accepted. That is usually a better use of the afternoon than adding a request ID to every function signature in sight.
Postscript
November 2026: I've rerun my lab on Node 22.23.5 and added a small comparison using AsyncLocalStorage.bind() and snapshot(). Both became stable in Node 22.15.0, according to Node's context API history. They can shorten a simple callback adapter; my original AsyncResource example remains useful when the queue also needs an explicit task lifecycle.