DEV Community

Sasi Kumar T
Sasi Kumar T

Posted on

Tracing the part of Mongoose nobody talks about

I have published an OpenTelemetry plugin that instruments the Mongoose hydration lifecycle.
@sasikumart/mongoose-hydrate-instrumentation

What's the problem?

If you're already using OTEL with Mongoose, you're probably tracing your queries — find, insertOne, updateMany, and so on. That covers a lot, but it misses something that happens after the query returns.

Document hydration.

When Mongoose gets raw BSON/JSON back from MongoDB, it doesn't just hand it to you as-is. It runs it through a whole initialization process, applying defaults, attaching virtuals, setting up getters/setters, populating nested subdocuments. For simple schemas with small result sets this is negligible. But for complex schemas or queries returning hundreds of documents, hydration can be a real cost that's completely invisible in your traces.

That blind spot is what this plugin fixes.

How it works

It patches Mongoose's internal hydration lifecycle and wraps it with OTEL spans, so you get visibility into:

  • mongoose.document.init — which is invoked by mongoose.hydrate to initialize a new Document from raw data

Each span includes attributes like the model name and document count.

Getting started

npm install @sasikumart/mongoose-hydrate-instrumentation
Enter fullscreen mode Exit fullscreen mode

Register it with your Node SDK before your models load:

import { NodeSDK } from '@opentelemetry/sdk-node';
import { MongooseHydrateInstrumentation } from '@sasikumart/mongoose-hydrate-instrumentation';

const sdk = new NodeSDK({
  instrumentations: [new MongooseHydrateInstrumentation()],
});

sdk.start();
Enter fullscreen mode Exit fullscreen mode

That's it. Your existing OTEL backend (Jaeger, Datadog, Honeycomb, OTLP — whatever you use) will start receiving the hydration spans automatically.


The package is on npm and the source is on GitHub. If you run into any issues or have ideas for improvement, PRs and issues are very welcome.


About Me

I’m a backend developer with extensive experience in designing and optimizing scalable backend systems. My expertise includes tackling complex performance challenges. I’ve led numerous database performance initiatives and have also been deeply involved in system design and revamping existing systems. My focus is on enhancing efficiency, ensuring reliability, and delivering robust solutions that scale effectively.

Feel free to connect with me on LinkedIn to learn more about my professional journey and projects.

Top comments (0)