Repository navigation
Description
Prerequisites
- I have written a descriptive issue title
- I have searched existing issues to ensure the feature has not already been requested
🚀 Feature Proposal
I'd like to propose adding first-class TracingChannel support to mongoose, following the pattern established by undici in Node.js core.
Motivation
Mongoose already has a powerful pre/post middleware (hook) system that covers document, query, aggregate, and model operations.
However, APM instrumentation libraries cannot use these hooks for span-based tracing today. Instead, they resort to monkey-patching Query.prototype.exec, Aggregate.prototype.exec, Model.prototype.save, and 12+ other methods via IITM/RITM. Here's why:
-
No async context propagation. Mongoose hooks run in the middleware chain's execution context, not the caller's
AsyncLocalStoragecontext. This is a documented pain point: #10020 reported post-hooks not working withAsyncLocalStorage, and #10478 identified the root cause as an underlying library issue where async context is lost across the hook chain. While these issues have been resolved, they illustrate that async context propagation through the middleware system has been a persistent challenge, and it's exactly the problemTracingChannelwas designed to solve at the platform level. -
Per-schema registration. Hooks must be registered on each schema individually. APM tools need global instrumentation that covers all models without requiring user configuration. There's no single attachment point for cross-cutting tracing concerns.
-
No lifecycle correlation. Pre and post hooks are separate middleware functions. To build a span, APM tools would need to correlate the pre-hook (span start) with the post-hook (span end) and manage span storage manually.
TracingChannelprovides a unified lifecycle for the operation, so correlation is built-in.
Beyond these APM-specific gaps, the current monkey-patching approach has broader ecosystem concerns:
- Runtime lock-in: RITM and IITM rely on Node.js-specific module loader internals (
Module._resolveFilename,module.register()). They don't work on Bun or Deno, which implement the Node.js API surface but not the module loader internals. - ESM fragility: IITM is built on Node.js's module customization hooks, which are still evolving and have been a persistent source of breakage in the OTEL JS ecosystem.
- Initialization ordering: Both require instrumentation to be set up before
mongooseis firstrequire()'d /import'd. - Bundling: Users must ensure instrumented modules are externalized, which is increasingly difficult as frameworks bundle server-side code into single executables or deployment files.
TracingChannel solves all of these. It provides structured lifecycle events (start, end, asyncStart, asyncEnd, error) with built-in async context propagation, zero-cost when no subscribers are attached, and a standardized subscription model that requires no monkey-patching.
Example
I propose implementing the following tracing channels:
| TracingChannel | Tracks | Context fields |
|---|---|---|
mongoose:query |
All Query.exec() operations — find, update, delete, count, distinct, etc. |
operation, collection, query, fields, options, database, serverAddress, serverPort |
mongoose:aggregate |
Aggregate.exec() pipeline execution |
pipeline, collection, options, database, serverAddress, serverPort |
mongoose:save |
Model.prototype.save() — document insert or update |
operation, collection, database, serverAddress, serverPort |
mongoose:model |
Model-level statics — insertMany, bulkWrite |
operation, collection, database, serverAddress, serverPort |
The usage will look something like this:
const dc = require('node:diagnostics_channel');
// Subscribe to query operations, covers ALL find/update/delete/count variants
dc.tracingChannel('mongoose:query').subscribe({
start(ctx) {
// TracingChannel automatically propagates this span as the active context
// through the entire async operation, no manual context.with() needed
ctx.span = tracer.startSpan(`${ctx.operation} ${ctx.collection}`, {
attributes: {
'db.system': 'mongodb',
'db.operation.name': ctx.operation,
'db.collection.name': ctx.collection,
'db.query.text': sanitize(ctx.query),
'db.namespace': ctx.database,
'server.address': ctx.serverAddress,
'server.port': ctx.serverPort,
},
});
},
asyncEnd(ctx) {
// asyncEnd fires after the promise resolves — this is where the span ends
ctx.span?.end();
},
error(ctx) {
ctx.span?.setStatus({ code: SpanStatusCode.ERROR, message: ctx.error?.message });
ctx.span?.recordException(ctx.error);
},
});The context payload can match what OTEL currently has.
I'm happy to help spec this out in a PR and see what you folks think.
Prior Art
This approach follows the same pattern already adopted or in progress by other major libraries:
undici(Node.js core) shipsTracingChannelsupport since Node 20.12:undici:requestnode-redisredis/node-redis#3195 (node-redis:command,node-redis:connect)ioredisredis/ioredis#2089 (ioredis:command,ioredis:connect)pg/pg-poolbrianc/node-postgres#3624 (pg:query,pg:connection,pg:pool:connect)mysql2sidorares/node-mysql2#4178 (mysql2:query,mysql2:execute,mysql2:connect,mysql2:pool:connect)
Full Disclosure, I'm driving the adoption process in some of these projects
Activity
vkarpov15 commentedon Apr 28, 2026
I'd say my one major concern about TracingChannel is that it is marked as Experimental in the Node docs:
Building on top of an unstable API is concerning, although the fact that undici supports TracingChannel alleviates my concern somewhat.
logaretm commentedon Apr 28, 2026
@vkarpov15 Thanks for considering.
It's marked as experimental because I think there is not enough adoption. But I'm working with @Qard (creator of diagnostic and tracing channels) on helping the ecosystem adopt it and he can confirm their level of stability. The interesting thing here is that tracing channels are implemented in all server-runtimes.
Since I created this issue, we worked with a few other notable projects that are adopting tracing/diag channels:
Other frameworks like fastify also ship it and have been for a while. Happy to discuss more and address/sketch how it would work if you would like.
Also it's not a deadend API, there is ongoing work to improve it and add features to it while fully being backward compatible with existing "experimental" API.
Qard commentedon Apr 28, 2026
Hi, I'm the creator and maintainer of diagnostics_channel. 👋🏻
Yes, it has mainly been left as experimental due to a lack of adoption, but also as a signal that we may make improvements as we learn from uses of it. That learning has largely already been absorbed and applied via recent PRs at this point. There are several improvements incoming, but none of those change the existing code, which will be left as-is, they add some additional systems to handle some more specific cases such as async iterators.
The TracingChannel API will be left as-is, likely forever at this point as it is very important to us to retain compatibility essentially indefinitely, because APM vendors have many customers using old Node.js versions even well beyond the EOL of Node.js itself. The core of diagnostics_channel though is actually explicitly designed to never change, tracing channel is simply sugar on top of the core channel model, so tracing can also be implemented directly with the core channels, which is what undici did to avoid the closures involved in the tracing channel API. The model is designed such that there are channels as a sort of atom of structural expression and then we can build abstractions over those to express groups of events as patterns. We can define new patterns of events to express new things like async iterators, but the underlying event system remains the same.
I'd like to just re-emphasize: diagnostics channel almost certainly has an even longer scale need for stability than basically any ecosystem module, so you can trust that nothing in that API surface is going to disappear on you any time soon. You can hold me personally accountable for ensuring that continues to work for your full support cycle.
vkarpov15 commentedon Apr 29, 2026
Ok, that's all very good to hear. In that case, we will experiment with tracing channel support in May 2026
logaretm commentedon Apr 30, 2026
Cool, happy to help with an exploratory PR or answer any questions to drive this forward 🙏
vkarpov15 commentedon May 3, 2026
If you're willing to do an exploratory PR that would be very helpful
logaretm commentedon May 5, 2026
Will do, saw some slop attempts already since I created this issue lol
logaretm commentedon May 7, 2026
created #16275
feat: add TracingChannel support for native APM instrumentation