AsyncLocalStorage and context propagation
Carry request-scoped data through async code without passing parameters, using AsyncLocalStorage. How run works, typical uses and the costs.
AsyncLocalStorage and context propagation
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- `AsyncLocalStorage` gives each logical async flow its own store. Code anywhere in that flow calls `als.getStore()` and sees the data set by the code that started it.
- `als.run(store, fn)` makes `store` current for `fn` and every callback, promise continuation and timer it starts, across `await` points.
- Outside any `run`, `getStore()` returns `undefined`, so guard for it. `als.exit(fn)` temporarily clears the store.
- Typical uses are request IDs for logs, per-request database transactions or tenants, and tracing spans. It is a way to avoid threading a `context` parameter through every call.
- It is implicit state: it hides dependencies, costs some performance, and can be lost through code that runs your callback from a different async resource, such as certain pooled or queued callbacks.
Context that has to go everywhere
Say every log line should carry the request ID, so you can follow one request through your logs while two hundred others interleave. The ID is born at the edge, in the HTTP handler. The logging call sits five layers down: controller, service, repository, database client. The honest solution is to pass requestId as a parameter through all of them, which clutters every function signature, including ones that never use it except to hand it on.
Other languages solve this with thread-local storage: a slot that belongs to the current thread. Node has one thread running many requests, so thread-locals mean nothing. What you need is storage tied to the asynchronous flow: the chain of callbacks, promises and timers that one request spawns. That is AsyncLocalStorage.
How it works
import { AsyncLocalStorage } from 'node:async_hooks';
import { createServer } from 'node:http';
import { randomUUID } from 'node:crypto';
import { setTimeout as sleep } from 'node:timers/promises';
const als = new AsyncLocalStorage();
const log = (msg) => console.log(`[${als.getStore()?.id ?? '-'}] ${msg}`);
async function db() {
await sleep(Math.random() * 20);
log('querying'); // no id parameter anywhere
}
createServer((req, res) => {
als.run({ id: req.headers['x-id'] ?? randomUUID().slice(0, 8) }, async () => {
log('start ' + req.url);
await db();
log('done');
res.end('ok');
});
}).listen(3404);
I sent three overlapping requests with ids a, b, c. The output interleaved but each line kept its own id:
[a] start /a
[b] start /b
[c] start /c
[b] querying
[b] done
[c] querying
[c] done
[a] querying
[a] done
als.run(store, fn) sets store as current while fn runs and for everything fn starts, including continuations after await. Under the hood Node tracks the async resources (promises, timers, I/O callbacks) created inside, and restores the right store when each one runs. After the run, getStore() is undefined again, and als.exit(fn) clears it temporarily.
Store a mutable object if you want code deep in the call stack to add to the context, for example a user ID once auth has run. The identity of the object stays the same for the whole flow.
Uses worth knowing
- Log correlation: logger reads the request ID, so none of your functions need to know it. See logging with pino.
- Per-request database transaction or tenant: repository code reads
getStore().tx. - Tracing: libraries such as OpenTelemetry use async context to link spans to their parent.
Frameworks hook it in at one point: a middleware calls als.run and calls next() inside the callback.
Costs and limits
ALS is implicit. A function that reads the store has a hidden dependency that its signature does not show, and tests must set one up. Use it for cross-cutting data many layers read and few decide on, not for core inputs.
It also has a performance cost: Node must track async resources, which adds overhead on every promise and callback. The overhead has dropped across releases, and recent Node versions have changed the implementation, but it is not free. Measure before putting it on a hot path.
Propagation can be lost. If a library stores your callback and calls it later from its own queue, the callback may run in the wrong context. Library authors fix that with AsyncResource.bind(fn) or AsyncLocalStorage.bind(fn). If a store is mysteriously undefined, suspect a pool, a custom queue, or an EventEmitter whose listener fires from a different flow than the one that registered it.
What the video covers
This is James Snell’s Node Congress 2024 talk, “Understanding Async Context”. The description says AsyncLocalStorage is a powerful Node.js API that has since been adopted across other runtimes, and the talk explains it; Snell is a Node.js TSC member who also works on Cloudflare Workers. It is a conference talk about how the API works and where it is going, less hands-on than the example above. I could not read a transcript, so details such as TC39’s async context proposal are not summarised here. The runnable example, the lost-context cases and the guidance on when to avoid ALS are this page’s. The 5-minute DevOnDuty demo under “go deeper” is a quicker first look.
Where this fits
ALS builds on the event loop and promises. It pairs with request lifecycles in HTTP servers and Express middleware, and with structured logging in production.
Check yourself
Three overlapping requests each run `als.run({ id }, handler)`. Inside `handler`, after `await db()`, what does `als.getStore()` return?
The store belonging to that request, not another one's. The store follows the async flow through `await`, so interleaved awaits do not mix requests. Logging `[a] querying`, `[b] querying` with the right ids in each line demonstrates it.
What does `getStore()` return from code running outside any `run`, such as at startup?
`undefined`. Logging helpers should use optional chaining, as in `als.getStore()?.id ?? '-'`, so they work both inside and outside a request.
Why might request context get lost around a connection pool or an internal queue?
The store propagates through promises and callbacks created inside the `run`. If a library parks your callback and later runs it from a different async resource, such as a shared pool's own queue, the callback can see the wrong store or none. Libraries that care wrap callbacks with `AsyncResource.bind`.
When is passing an explicit `context` argument better than `AsyncLocalStorage`?
When the dependency is central to the function's behaviour or you want it visible in signatures and easy to test. ALS suits cross-cutting data like request IDs that many layers read but few decide on.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.