Skip to content

Async Context in Node.js: AsyncLocalStorage, async_hooks and diagnostics_channel

How to carry request-scoped context such as request ID, user and trace through deep asynchronous call chains without threading it through every function signature – with AsyncLocalStorage, the underlying async_hooks and diagnostics_channel for decoupled tracing.

≈ 13 min readSoftwareNode.jsBackend

AsyncLocalStorage is not a global variable with a better name. Every run call holds its own store, and two concurrent requests don’t get in each other’s way – exactly where the global variable you would otherwise reach for by reflex fails. The confusion persists anyway, because from the outside both look the same: put something down at the top, pick it up again far below.

What this is good for shows in operations, not in the code. Whether finding a root cause takes minutes or hours depends on whether you can follow a single request seamlessly through logs, services and traces. Node.js ships three building blocks for this: AsyncLocalStorage, the underlying async_hooks and diagnostics_channel. In the post on debugging and observing Node.js, I saved async context for later; I’m catching up on that here.

This is not a niche problem. As soon as an application has more than a few endpoints, you want to know which log line belongs to which request. You want to see the logged-in user in the error report. You want to hold a trace together across several services. And all these values simply belong to the request, not to whatever function happens to be running.

The problem: threading context through the depths#

Let’s look at what this looks like without any help. I have a handler that calls a service that calls a repository that, at the end, wants to log something. The request ID is created at the very top – it is needed at the very bottom.

function handler(req, res) {
  const requestId = randomUUID();
  serviceA(req.body, requestId);
}

function serviceA(input, requestId) {
  // serviceA doesn't need requestId itself
  return repository(input, requestId);
}

function repository(input, requestId) {
  // repository doesn't either
  log('writing record', requestId);
}

function log(message, requestId) {
  console.log(`[${requestId}] ${message}`);
}

That works – but it’s unpleasant. Every function in between gets a parameter forced on it that it never uses itself. It just passes it along. If a user object comes along tomorrow and a trace ID the day after, every signature grows with it. And the one library function you can’t change will, of course, not pass the parameter along – that’s where the chain breaks.

You can work around it: attach the context to a class instance, pass along an object that collects all the extra data, or even set a global variable. The class instance route forces you into an object model you may not want at all. The context object is just a more nicely packaged version of the same passing along. And the global variable is simply wrong with concurrent requests – the next request overwrites it while the first one is still running. None of these variants really holds up.

For exactly this “context threading” problem, Node.js has a clean answer.

AsyncLocalStorage: the practical way#

AsyncLocalStorage lives in the node:async_hooks module and has been stable since Node v16.4.0. The idea is simple: you run a callback in a so-called store, and this store is preserved for all asynchronous operations created inside that callback. You read it back as deep down as you like – without a single extra parameter.

An honest note up front: there is no example from a specific project codebase for this post. The following code blocks are generic Node.js examples that I checked against the official documentation.

import { AsyncLocalStorage } from 'node:async_hooks';
import { randomUUID } from 'node:crypto';

const als = new AsyncLocalStorage();

function handler(req, res) {
  const store = { requestId: randomUUID(), user: req.user };
  als.run(store, () => {
    serviceA(req.body);
  });
}

function serviceA(input) {
  return repository(input);
}

function repository(input) {
  log('writing record');
}

function log(message) {
  const { requestId } = als.getStore() ?? {};
  console.log(`[${requestId}] ${message}`);
}

The difference is clear. serviceA and repository no longer know anything about the request ID. They know their actual job and nothing else. Only at the very top is the store set – with als.run(store, callback) – and only where it is really needed is it read with als.getStore().

Two details matter. First, run is synchronous: the callback’s return value is passed through, and if the callback throws, the error is passed on as well and the context is exited again. Second, outside a run call, getStore() simply returns undefined. That’s why the example has the ?? {} – you should never assume a store is always there.

Any object works as a store. In practice, I like to use a Map when values should be added during a request, or a plain object when the content is fixed from the start. The only thing that matters is that every run call gets its own store – then concurrent requests are cleanly separated from each other without you having to take care of the separation yourself. That is exactly the gain over the global variable from before.

The following diagram shows this level. The store is set at the top, the deep calls read it, and no parameter is ever passed along.

flowchart TD
  Req["HTTP Request"] --> Run["als.run(store)"]
  Run --> A["serviceA()"]
  A --> R["repository()"]
  R --> L["log()"]
  Store[("Store<br/>requestId, user")]
  Run -.-> Store
  L -.->|"reads store"| Store

enterWith – the risky shortcut#

Besides run, there is enterWith(store). The appeal is obvious: you don’t have to indent the rest of the code into a callback; you just set the context and carry on normally. But that is exactly the danger. enterWith applies to the entire rest of the synchronous execution plus all following asynchronous calls – there is no natural bracket that closes the context again. If you set it in an event handler, subsequent handlers may end up in the same context.

enterWith is marked as experimental, and the documentation is unusually direct: you should use run() unless there are strong reasons against it. In practice that means: start with run. enterWith is reserved for rare special cases and is not the normal path.

async_hooks: the foundation underneath#

How does AsyncLocalStorage even know which asynchronous operations belong to which run call? Underneath sits async_hooks, the actual low-level layer. It provides lifecycle hooks for asynchronous resources: for each such resource, Node goes through the phases init, before, after and destroy. You can hook into these phases.

import { createHook, executionAsyncId } from 'node:async_hooks';
import { writeSync } from 'node:fs';

const hook = createHook({
  init(asyncId, type, triggerAsyncId) {
    writeSync(1, `init ${type} id=${asyncId} trigger=${triggerAsyncId}\n`);
  },
  destroy(asyncId) {
    writeSync(1, `destroy id=${asyncId}\n`);
  },
});

hook.enable();

Why writeSync instead of console.log? Because console.log itself creates asynchronous resources, and in an init hook you would write yourself into an infinite loop. That alone shows how delicate this layer is to work with directly.

And here I have to be clear: async_hooks is experimental, and the Node documentation explicitly advises against using it directly – because of “usability issues, safety risks, and performance implications.” The destroy hook is especially expensive because it enables tracking of promises through the garbage collector. That costs measurable performance.

So the message is not “learn async_hooks and use it.” The message is: AsyncLocalStorage stands on this foundation, but it is the stable, recommended and practical API. As a rule, you don’t reach for createHook yourself. I only show it here to make clear what happens one level down – not as a recommendation for production code.

diagnostics_channel: decoupled instrumentation#

The third building block solves a different problem. Say a library wants to report that it is starting a request – but it shouldn’t dictate who hears about it or what happens with it. A logger? A tracer? A metric counter? The library shouldn’t have to know.

diagnostics_channel has been stable since Node v18.13.0 and exists for exactly this: a decoupled publish/subscribe channel. Producers publish messages on a named channel, observers subscribe to it. Neither side knows the other.

import diagnostics_channel from 'node:diagnostics_channel';

const channel = diagnostics_channel.channel('app:request:start');

function handleRequest(req) {
  if (channel.hasSubscribers) {
    channel.publish({
      requestId: req.id,
      route: req.url,
      startedAt: Date.now(),
    });
  }
  // ... actual work
}

On the other side, in a completely separate piece of code – maybe in the observability layer, maybe in a plugin – you subscribe to the same channel:

import diagnostics_channel from 'node:diagnostics_channel';

diagnostics_channel.subscribe('app:request:start', (message, name) => {
  console.log(`[${name}] request ${message.requestId} on ${message.route}`);
});

The hasSubscribers guard is not a detail but the heart of the matter. Without subscribers, nothing should cost anything. If you build the message object unconditionally – possibly with expensive fields or serialized payloads – you pay that price even when no one is listening. With the guard, there is practically no overhead at zero subscribers.

A note on the API: the channel object also has channel.subscribe(...), but this variant has been marked as deprecated since v18.7.0. In your own code, use the module-level functions, that is, diagnostics_channel.subscribe(name, onMessage).

Three levels, three jobs#

The three modules sound similar and do fundamentally different things – this is exactly where the confusion comes from. The division of roles:

  • AsyncLocalStorage carries context: stable since v16.4.0, the practical high-level API. Request ID, user and trace through deep async chains – without passing parameters along.
  • async_hooks is the foundation: experimental and explicitly not recommended for direct use. It provides the resource lifecycle that AsyncLocalStorage builds on.
  • diagnostics_channel reports events in a decoupled way: stable since v18.13.0. Producers and consumers don’t know each other – ideal for instrumentation and tracing.

The following diagram arranges the three relative to each other: the context layer on its foundation, and next to it the independent event bus.

flowchart TB
  subgraph Context["Kontext tragen"]
    ALS["AsyncLocalStorage<br/>Stable"]
    AH["async_hooks<br/>Experimental"]
    ALS --> AH
  end
  subgraph Bus["Ereignisse entkoppelt melden"]
    Pub["Publisher"] --> Ch["diagnostics_channel"]
    Ch --> S1["Subscriber: Logger"]
    Ch --> S2["Subscriber: Tracer"]
  end

Request correlation as a measurable operational quality#

The three modules are a means, not an end. The end is a property of the running system: can every operation be clearly assigned to a request? Once that is the case, a vague “the system feels slow” turns into a question you can answer. You grab a correlation ID, filter logs, metrics and traces by it and see that one request in all its depth – across service boundaries.

This traceability is measurable, and that is exactly what makes it an operational quality rather than a gut feeling. The share of log lines assigned to a request ID is a metric. The time from the error report to the root cause found – the mean time to resolution – is a metric. Both move noticeably when correlation is complete instead of full of holes. AsyncLocalStorage provides the load-bearing building block for this: the key that reaches the deepest function without passing parameters along. diagnostics_channel provides the second: the decoupling that lets an observability layer pick up this key without the application code having to know who is listening.

The trade-off should be named honestly. Context via AsyncLocalStorage costs a small but real overhead per asynchronous operation – negligible compared to the gain for the vast majority of backends, but in exceptional cases with extremely high throughput, something you measure rather than assume. The bigger price is discipline: the run call has to sit reliably at the entry of every execution chain; otherwise correlation breaks exactly where you need it most.

So the decision isn’t made at the API but at the level of ambition. A handful of endpoints without real operational load can do without all this. But as soon as several services work together, there is an on-call rotation or errors cost money, request correlation goes from nice-to-have to foundation. It is the building block on which logging, tracing and alerting grow together into one picture – the bridge from individual signals to real observability.

Pitfalls from practice#

The most common pain with AsyncLocalStorage is context loss: getStore() suddenly returns undefined even though you’re sure you’re inside a run call. This typically happens with certain callback-based APIs or with your own homegrown “thenable” objects, where Node can’t properly follow the asynchronous chain. The documentation names two remedies: convert such APIs into real promises with util.promisify(), or bind the resource with AsyncResource. A practical debugging trick: log getStore() at suspicious transitions. If the store is gone right after a particular call, you’ve found the transition where the chain breaks.

I already hinted at the enterWith leak above – here it is once more, concretely, as a warning: the context runs through the entire remaining synchronous execution and beyond. Set in an event handler, subsequent handlers can inherit the same context even though they belong to an entirely different request. Those are the bugs you hunt at three in the morning. Prefer run().

And finally, the cost of async_hooks: the overhead is real, especially from promise tracking in the destroy hook. Together with the fact that the API is experimental and, according to the Node team, risky, that gives a clear line – don’t use it as a context mechanism in production. If you need context, use AsyncLocalStorage. async_hooks is something you know in order to understand what happens underneath, and otherwise leave alone.

A side note for the curious: v18.16.0 added AsyncLocalStorage.bind(fn) and AsyncLocalStorage.snapshot() to bind the current context to a function. Both are still experimental and not needed to get started – I only mention them for completeness.

Conclusion#

The common thread is layering. At the very bottom, async_hooks makes it possible for Node to track the lifecycle of asynchronous resources at all – a powerful but experimental and expensive layer that you rarely touch directly. On top of it stands AsyncLocalStorage as the stable, recommended API you use to carry request-scoped context through call chains of any depth without threading it through every signature. And next to it stands diagnostics_channel as a decoupled event bus that libraries and applications use for structured instrumentation without producer and consumer having to know about each other.

The effect shows less in the code than in operations. Where context is carried cleanly, debugging cycles get shorter because every log line knows its request. Friction drops because no signature drags along a parameter it never uses. And quality rises measurably because traceability turns from chance into a property. For daily work, that means: als.run(store, cb) at the top, als.getStore() at the bottom – and you’re rid of the tedious passing of parameters. If you want to decouple observability, reach for diagnostics_channel with a hasSubscribers guard. async_hooks remains the foundation you should understand but don’t operate yourself day to day. The limit is just as clear: no mechanism replaces the discipline of setting the run call reliably – if the chain breaks there, the best API won’t help.

If you want to dig deeper into Node’s event model at this point, the post on EventEmitter and the event model is a good fit. And if you want to understand the architecture around the Event Loop and asynchronous execution from the ground up, the Node.js training gives you the bigger picture.

Further reading#

Revised and translated from German with the help of AI.