← Back to Node.js, page 5

nodejs-0093 · Hard senior

What is the diagnostics_channel module, and how do libraries and monitoring tools use it?

diagnostics_channel is a built-in publish and subscribe system for diagnostic events. A library publishes messages on a named channel, and tools subscribe without patching the library. It costs almost nothing when nobody subscribes. TracingChannel adds standard start, end, asyncStart, asyncEnd and error events around an operation.

Full answer

Monitoring tools (APM, tracing, profilers) used to wrap library functions at run time ("monkey patching") to learn about requests and queries. That is fragile. diagnostics_channel gives a clean contract: the library says "something happened" on a named channel, and anyone interested listens.

Core API:

  • const ch = diagnostics_channel.channel('my-lib:query'): get a channel by name. Names are global strings, so use a prefix.
  • ch.publish(message): send an object to subscribers. Check ch.hasSubscribers first, so building the message costs nothing when nobody listens.
  • diagnostics_channel.subscribe(name, handler) or ch.subscribe(handler): listen. Handlers run synchronously inside publish(), so they must be fast and must not throw into the caller.
  • channel.bindStore(als, transform) connects a channel to an AsyncLocalStorage, so a store is set around a traced operation.

TracingChannel (diagnostics_channel.tracingChannel(name)) models an operation with a lifecycle:

  • tracePromise(fn, context), traceSync, traceCallback run the function and publish: start (before), end (sync part finished), asyncStart and asyncEnd (promise settled), and error. The same context object is passed through all events, so a subscriber can store the start time on it and compute the duration in asyncEnd.

Node core publishes channels such as http.client.request.start, http.server.request.start, net.client.socket, undici:request:create and others. Libraries such as undici, and database drivers, publish their own. OpenTelemetry instrumentations can subscribe instead of patching.

Guidelines for library authors: publish stable, documented messages; avoid heavy work when there are no subscribers; never let a subscriber failure break the library call.

The module is marked as experimental in parts of the API, so check the Node documentation for the version you use.

javascript
const dc = require('node:diagnostics_channel');
const { performance } = require('node:perf_hooks');

// --- A "library" that publishes events -------------------------------------
const queries = dc.tracingChannel('marks-db:query');

async function runQuery(sql) {
  // Wrap the real work. The same context object travels through all events.
  return queries.tracePromise(async () => {
    await new Promise((resolve) => setTimeout(resolve, 10));
    if (sql.includes('broken')) throw new Error('syntax error near "broken"');
    return [{ student: 'Asha', marks: 78 }];
  }, { sql });
}

// A simple custom channel too.
const cacheChannel = dc.channel('marks-db:cache');
function cacheLookup(key) {
  if (cacheChannel.hasSubscribers) cacheChannel.publish({ key, hit: key === 'known' }); // free when nobody listens
  return key === 'known';
}

// --- A "monitoring tool" that subscribes, without touching the library -----
const seen = [];
queries.subscribe({
  start(message) { message.startedAt = performance.now(); seen.push('start: ' + message.sql); },
  end() { seen.push('end (synchronous part finished)'); },
  asyncStart(message) { seen.push('asyncStart: ' + JSON.stringify(message.result)); },
  asyncEnd(message) { seen.push('asyncEnd: took at least 10 ms = ' + (performance.now() - message.startedAt >= 9)); },
  error(message) { seen.push('error: ' + message.error.message); },
});
dc.subscribe('marks-db:cache', (message) => seen.push('cache: ' + JSON.stringify(message)));

async function main() {
  cacheLookup('before-subscription-check');
  console.log('cache channel has subscribers:', cacheChannel.hasSubscribers);
  cacheLookup('known');
  await runQuery('SELECT * FROM marks');
  await runQuery('SELECT broken').catch(() => {});
  console.log(seen.join('\n'));
}

main();

The subscriber measures the duration by adding startedAt to the context object that is shared between the events. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): cache channel has subscribers: true cache: {"key":"before-subscription-check","hit":false} cache: {"key":"known","hit":true} start: SELECT * FROM marks end (synchronous part finished) asyncStart: [{"student":"Asha","marks":78}] asyncEnd: took at least 10 ms = true start: SELECT broken end (synchronous part finished) error: syntax error near "broken" asyncStart: undefined asyncEnd: took at least 10 ms = true

Key points

  • Named channels give publish and subscribe for diagnostics.
  • Check hasSubscribers so unused channels cost nothing.
  • TracingChannel adds start, end, asyncStart, asyncEnd and error events.
  • Tools subscribe instead of monkey patching.

Common mistakes

  • Doing slow or blocking work inside a subscriber.
  • Building expensive messages without checking hasSubscribers.
  • Letting a subscriber throw into the library code.
  • Choosing channel names without a prefix and clashing with other libraries.

Follow-ups

  • How would you connect a channel to AsyncLocalStorage?
  • Which core modules publish diagnostics channels?
  • How does this differ from OpenTelemetry?

Tips

  • Contrast with monkey patching in the first sentence.
  • Know hasSubscribers.
  • List the five tracing events.