skip to content

Why does Node.js steer tooling away from `async_hooks.createHook` toward `AsyncLocalStorage` and `node:diagnostics_channel`, and what does each replacement provide?

level: seniorimportance: nice to knowfreq 20%

answer

  1. a callback for every async resource
  2. promise tracking is the expensive part
  3. a throwing hook ends the process
  4. named channels, publish only when watched

basics

~10 s

createHook fires callbacks for every async resource, forces costly promise tracking and kills the process if a hook throws. AsyncLocalStorage covers context propagation; diagnostics_channel gives libraries cheap named events that tools subscribe to.

solid answer

~40 s

`async_hooks.createHook` registers `init`, `before`, `after`, `destroy` and `promiseResolve` callbacks that run for every asynchronous resource in the process. Node's docs mark it experimental and ask users to migrate away, citing usability issues, safety risks and performance: an enabled hook switches on V8's promise tracking unless it passes `trackPromises: false`, and the docs call that tracking a significant overhead; a hook that throws exits the process with `'uncaughtException'` listeners removed; and `console.log` inside a hook recurses. For request context use `AsyncLocalStorage`, which in Node 24 runs on `AsyncContextFrame` rather than async hooks. For instrumentation use `node:diagnostics_channel`: a library publishes to named channels, `channel.hasSubscribers` lets it skip the work when no tool listens, and Node itself publishes channels such as `http.server.request.start`.

code

javascript · 20 lines
javascript
import diagnostics_channel from 'node:diagnostics_channel';

// library side: create once, publish only when someone listens
const queryChannel = diagnostics_channel.channel('mylib.query');
export function runQuery(sql) {
  if (queryChannel.hasSubscribers) {
    queryChannel.publish({ sql, startedAt: performance.now() });
  }
  // ... run the query
}

// tool side: subscribe by name, no patching of the library
diagnostics_channel.subscribe('mylib.query', (msg, name) => {
  console.log(name, msg.sql);
});

// built-in channel published by node:http
diagnostics_channel.subscribe('http.server.request.start', ({ request }) => {
  console.log('incoming', request.method, request.url);
});

go deeper

for a junior

Recall that async_hooks is discouraged, that AsyncLocalStorage is the supported way to carry request context, and that diagnostics_channel exists for instrumentation.

for a middle

Explain what createHook's callbacks are and why promise tracking makes them costly, and how a channel's publish and subscribe work.

for a senior

Argue the safety and performance case from the docs, use hasSubscribers on hot paths, and know which built-in channels Node and its bundled fetch client publish.

for a principal

Decide what instrumentation the team allows in production: libraries that publish to diagnostics channels instead of being patched, and no global async hooks without a measured overhead budget.

## What `async_hooks.createHook` does The `node:async_hooks` module can register callbacks for the life cycle of every **asynchronous resource**: an object with a callback that runs later, such as a TCP server's `'connection'` handler, an `fs.open()` request, a timer or a promise. - **`init`** runs when a resource is created, with its id, type and the id of the resource that triggered it. - **`before`** and **`after`** wrap each callback invocation. - **`destroy`** runs when the resource is gone. - **`promiseResolve`** runs when a promise is resolved. APM agents and context libraries were built on this for years. The page now opens with: *Stability 1, Experimental. Please migrate away from this API, if you can.* ## Why Node discourages it The documentation names usability issues, safety risks and performance implications, and its own sections show each: 1. **Promise tracking is expensive.** Without hooks, promises get no async ids because V8's promise introspection is costly. Installing a hook with default options "forces PromiseHooks to be enabled", and the docs say tracking promise execution can cause significant overhead. Node 24.14.0 added a `trackPromises: false` option to opt out, at the price of losing promise context. 2. **`destroy` adds garbage-collector work.** Using the destroy hook enables tracking of promises through the GC, and holding the `resource` object from `init` can stop `destroy` from ever firing, which is a leak. 3. **A throwing hook is fatal.** If any hook callback throws, Node prints the stack and exits; the exit path is that of an uncaught exception but with all `'uncaughtException'` listeners removed, so your crash handler cannot intervene. 4. **Printing recurses.** `console.log()` is itself asynchronous, so calling it in a hook triggers more hooks; the docs suggest `fs.writeFileSync` for debugging output. 5. **Global scope.** A hook sees every resource from every library in the process, so one tool's hook taxes all code. The same warning covers the `AsyncHook` class and `async_hooks.executionAsyncResource()`. If a use case remains beyond context tracking and the data diagnostics channels already provide, the documentation asks for an issue describing it, so that Node can design a purpose-focused API instead. ## Replacement one: `AsyncLocalStorage` For the most common use, carrying a request id or similar value across async work, the docs point to `AsyncLocalStorage`, stable since 16.4.0 and described as performant and memory-safe with non-obvious optimisations. In Node 24 it no longer sits on async hooks at all: it is backed by **`AsyncContextFrame`** by default, and only `--no-async-context-frame` brings back the hook-based model. ## Replacement two: `node:diagnostics_channel` `diagnostics_channel` (stable since 19.2.0 and 18.13.0) is a publish-subscribe bus for diagnostic events: - A library creates a **named channel** once at module top level with `diagnostics_channel.channel('mylib.query')`, using its module name to avoid collisions. - Before preparing a message it checks **`channel.hasSubscribers`**, so an unobserved channel costs almost nothing. - **`channel.publish(message)`** calls subscribers **synchronously**, in the publisher's context. - A tool calls **`diagnostics_channel.subscribe(name, handler)`**; an error thrown in a handler triggers `'uncaughtException'` rather than breaking the publisher's call. Node publishes built-in channels, several still marked experimental: | Area | Example channel names | |---|---| | HTTP | `http.server.request.start`, `http.client.request.start`, `http.server.response.finish` | | Networking | `net.server.socket`, `net.client.socket` | | Processes and threads | `child_process`, `worker_threads` | | Modules | `tracing:module.require:start` | | Console | `console.log`, `console.error` | The bundled `fetch` client, undici, publishes its own channels such as `undici:request:create`. Two experimental additions connect the bus to context. **`TracingChannel`** groups five channels, `start`, `end`, `asyncStart`, `asyncEnd` and `error`, around one traced operation. **`channel.bindStore(store)`** together with `channel.runStores()` sets an `AsyncLocalStorage` value for the duration of a published operation, so a tracer can attach its span context without monkey-patching the library. Turning those events into spans and exporting them is the observability tooling's job, not Node's. ## Other narrow replacements - `process.getActiveResourcesInfo()` (stable since 24.0.0) lists the types of resources keeping the event loop alive, a common reason people reached for `init` and `destroy` hooks. - `AsyncResource` remains the supported way for a library to make its own callbacks keep the right context. ## The rule of thumb Reach for `createHook` only when neither `AsyncLocalStorage` nor a diagnostics channel covers the need, and then measure: the overhead lands on every promise in the process.

  • Why should a channel be created once at module top level rather than per call?
    `diagnostics_channel.channel(name)` returns an object optimised to keep publish cheap, and the docs say acquiring channels at run time is discouraged because of the extra overhead. Holding one `Channel` object also makes the `hasSubscribers` check a property read, so an unobserved hot path pays almost nothing.
  • What happens to the process if an `async_hooks` callback throws?
    Node prints the stack trace and exits. The path resembles an uncaught exception, but every `'uncaughtException'` listener is removed first, so nothing can catch it; `'exit'` listeners still run unless `--abort-on-uncaught-exception` is set, in which case Node aborts and leaves a core file. The docs justify this by the volatile points in an object's life where hooks run.

  • Recommending createHook as the standard way to propagate request context
  • Claiming an enabled async hook is free for promise-heavy code
  • Assuming an uncaughtException handler can rescue a throwing async hook
  • Thinking diagnostics_channel subscribers run later on a separate queue
  • Building channels on every call instead of once at module load

Assumes Node 24: AsyncLocalStorage uses AsyncContextFrame instead of async hooks since 24.0.0, and createHook's trackPromises option arrived in 24.14.0.