skip to content

In a Node.js HTTP service, how does `AsyncLocalStorage` keep a request id available to every log line and to an error thrown several awaits deep?

level: middleimportance: must knowfreq 62%

answer

  1. a store per async chain
  2. run wraps the request handler
  3. getStore anywhere below it
  4. module variable: overwritten by concurrency
  5. AsyncContextFrame in 24

basics

~10 s

Wrap each request in asyncLocalStorage.run(store, handler). Timers, I/O callbacks and awaits started inside inherit that store, so logging and error code read it with getStore() instead of passing the id through every call.

solid answer

~40 s

`AsyncLocalStorage` from `node:async_hooks` gives each asynchronous call chain its own value. In the request handler you call `als.run({ requestId }, () => handle(req, res))`; the store is visible inside that callback and in every async operation created from it, so a logger or an error handler three modules away calls `als.getStore()` and gets this request's id, even after five awaits. A module-level variable cannot do this, because concurrent requests interleave on the one thread and overwrite it between awaits. Outside any `run()`, `getStore()` returns `undefined` (or the `defaultValue` passed to the constructor, an option added in Node 24). Prefer `run()` to `enterWith()`, which leaks the store into the rest of the current synchronous execution. In Node 24 the class is backed by `AsyncContextFrame` by default rather than `async_hooks`.

code

javascript · 15 lines
javascript
import { AsyncLocalStorage } from 'node:async_hooks';
import { setTimeout as sleep } from 'node:timers/promises';

const ctx = new AsyncLocalStorage();

async function deep() {
  await sleep(5);
  await sleep(5);
  return ctx.getStore();
}

const a = ctx.run({ requestId: 'a' }, deep);
const b = ctx.run({ requestId: 'b' }, deep);
console.log(await a, await b, ctx.getStore());
// { requestId: 'a' } { requestId: 'b' } undefined

go deeper

for a junior

Recall that AsyncLocalStorage carries a value through callbacks and awaits, and that run() sets it and getStore() reads it.

for a middle

Explain why a global variable breaks under concurrent requests, what run() scopes, why enterWith() leaks, and what getStore() returns outside a context.

for a senior

Discuss where the id lands on errors, storing mutable objects rather than primitives, the Node 24 AsyncContextFrame switch and the opt-out flag if context flow differs.

for a principal

Weigh ambient request context against explicit parameters for a large codebase: decide which fields belong in the store, and make every boundary crossing, workers and downstream calls, send the id explicitly.

## The problem: one thread, many requests A Node.js HTTP server handles many requests concurrently on a single JavaScript thread. Request A starts, awaits a database call, and while it waits request B runs. If the code stores "the current request id" in a module-level variable, B overwrites it, and when A resumes its log lines carry B's id. Threaded runtimes solve this with **thread-local storage**; Node needs storage that follows an **asynchronous call chain** instead of a thread. The alternative, passing a `context` argument through every function, works but touches every signature between the HTTP layer and the logger, including library code you do not own. ## How `AsyncLocalStorage` works `AsyncLocalStorage` lives in `node:async_hooks` and has been stable since v16.4.0. The core API is three calls: - **`new AsyncLocalStorage()`** creates an independent store. Several instances can coexist without interfering. - **`als.run(store, callback, ...args)`** runs `callback` synchronously with `store` as the current value and returns its result. The store is visible inside the callback and **in every asynchronous operation created within it**: promises and awaits, timers, `setImmediate`, I/O callbacks. Once `run()` returns, or throws, the context is exited for the caller. - **`als.getStore()`** returns the current store, or `undefined` when called outside any `run()` or `enterWith()` context. Because propagation happens at the moment an async operation is created, an `await` five calls deep resumes with the same store that was active when the request entered `run()`. ```js import http from 'node:http'; import { randomUUID } from 'node:crypto'; import { AsyncLocalStorage } from 'node:async_hooks'; const requestContext = new AsyncLocalStorage(); export function log(msg) { const ctx = requestContext.getStore(); console.log(JSON.stringify({ requestId: ctx?.requestId ?? '-', msg })); } async function loadOrder(id) { await new Promise((r) => setTimeout(r, 10)); // stands in for real I/O log(`loading order ${id}`); if (id === '0') throw new Error('order not found'); return { id }; } http.createServer((req, res) => { const requestId = req.headers['x-request-id'] ?? randomUUID(); requestContext.run({ requestId }, async () => { try { const order = await loadOrder(new URL(req.url, 'http://x').searchParams.get('id')); res.end(JSON.stringify(order)); } catch (err) { log(`failed: ${err.message}`); // still tagged with this request's id res.statusCode = 500; res.end(); } }); }).listen(3000); ``` ## Getting the id onto errors The store travels with the async chain, not with the `Error` object, so attach it where the error is handled or created: 1. In the request-level `catch`, read `getStore()` and log the id with the error, as above. 2. Or have your error classes copy `requestContext.getStore()?.requestId` onto a property in their constructor, so the id survives if the error is rethrown or serialised later. Either way, no function between the handler and the throw site has to know the id exists. ## `run()` versus `enterWith()` `enterWith(store)` (Stability 1, experimental) switches the current context for **the rest of the current synchronous execution** and everything it schedules. Called inside an event listener, it also changes the context seen by later listeners of the same event. `run()` scopes the store to one callback, which is why the documentation says to prefer it unless there is a strong reason not to. Node 24.20.0 also added an experimental `withScope()` that restores the previous store when a `using` block ends. ## What Node 24 changed | Aspect | Node 22 | Node 24 | |---|---|---| | Implementation | built on `async_hooks` | **`AsyncContextFrame`** by default | | Opt-out flag | not applicable, the old model is the default | `--no-async-context-frame` restores the old model | | Constructor options | none | `defaultValue` and `name` (added in 24.0.0) | The 24.0.0 release notes describe the new implementation as more efficient and more robust; the old one is kept for compatibility and for cases where context flow differs. ## Common mistakes - Using a module-level variable or a property on a shared singleton for "the current request". - Calling `getStore()` at module load time, outside any request, and caching the `undefined` it returns. - Storing a primitive and expecting later code to change it: store an object (or a `Map`) and mutate its fields instead. - Reading the store inside a callback handed to a callback-only library and finding it `undefined`: some libraries lose the context, and wrapping their API with `util.promisify()` is the usual first fix. - Assuming the store crosses process or thread boundaries: a `worker_threads.Worker`, a child process or a downstream service gets nothing unless you send the id explicitly.

  • Why does the documentation steer you to `run()` rather than `enterWith()`?
    `enterWith()` changes the context for the whole remaining synchronous execution, not just one callback. Called inside an event listener, the next listener for the same event also sees the new store, and code after the call keeps it too. `run()` limits the store to its callback and the async work created inside it, then exits the context, so one request cannot leak its store into unrelated code.
  • Does the store follow work into a `worker_threads.Worker`?
    No. A worker is a separate thread with its own JavaScript environment, and the docs note each thread has an independent async_hooks interface. To keep a request id across that boundary, send it explicitly in `workerData` or in the posted message, and have the worker open its own `run()` with it.

A module-level variable is a whiteboard at the departure gate: whoever passed last wrote their name on it, so it is wrong for everyone else. AsyncLocalStorage is a tag tied to each suitcase, which travels with it through every transfer and is read wherever the suitcase turns up.

  • Keeping the current request id in a module-level variable
  • Saying getStore() throws when called outside run()
  • Preferring enterWith() inside listeners because it needs no callback
  • Claiming AsyncLocalStorage in Node 24 is still built on async_hooks by default
  • Expecting the store to reach a worker thread automatically

Assumes Node 24, where AsyncLocalStorage is backed by AsyncContextFrame by default (changed in 24.0.0, opt out with --no-async-context-frame) and the constructor accepts defaultValue and name.