Skip to content

TracingChannel Proposal for observability #16105

Closed

Description

@logaretm

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:

  1. No async context propagation. Mongoose hooks run in the middleware chain's execution context, not the caller's AsyncLocalStorage context. This is a documented pain point: #10020 reported post-hooks not working with AsyncLocalStorage, 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 problem TracingChannel was designed to solve at the platform level.

  2. 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.

  3. 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. TracingChannel provides 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 mongoose is first require()'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:

Full Disclosure, I'm driving the adoption process in some of these projects

Activity

  1. added
    new featureThis change adds new functionality, like a new method or class
    enhancementThis issue is a user-facing general improvement that doesn't fix a bug or add a new feature
    on Mar 17, 2026
  2. added this to the 9.7 milestone on Apr 28, 2026
  3. added
    discussionIf you have any thoughts or comments on this issue, please share them!
    on Apr 28, 2026
  4. vkarpov15 commented on Apr 28, 2026

    @vkarpov15
    Collaborator

    I'd say my one major concern about TracingChannel is that it is marked as Experimental in the Node docs:

    Image

    Building on top of an unstable API is concerning, although the fact that undici supports TracingChannel alleviates my concern somewhat.

  5. logaretm commented on Apr 28, 2026

    @logaretm
    ContributorAuthor

    @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.

  6. Qard commented on Apr 28, 2026

    @Qard

    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.

  7. vkarpov15 commented on Apr 29, 2026

    @vkarpov15
    Collaborator

    Ok, that's all very good to hear. In that case, we will experiment with tracing channel support in May 2026

  8. logaretm commented on Apr 30, 2026

    @logaretm
    ContributorAuthor

    Cool, happy to help with an exploratory PR or answer any questions to drive this forward 🙏

  9. vkarpov15 commented on May 3, 2026

    @vkarpov15
    Collaborator

    If you're willing to do an exploratory PR that would be very helpful

  10. logaretm commented on May 5, 2026

    @logaretm
    ContributorAuthor

    Will do, saw some slop attempts already since I created this issue lol

  11. logaretm commented on May 7, 2026

    @logaretm
    ContributorAuthor

    created #16275

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    discussionIf you have any thoughts or comments on this issue, please share them!enhancementThis issue is a user-facing general improvement that doesn't fix a bug or add a new featurenew featureThis change adds new functionality, like a new method or class

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions