mongoose: possible memory leak with #connection.useDb

Hello guys,

In my work, I need to switch through various different databases. I faced a memory leak warning when using .useDb several times with the same dabatabase name.

The following code demostrates this issue.

var mongoose = require('mongoose');

var db1 = mongoose.createConnection('mongodb://localhost/my_database');

for (var i = 0; i <= 11; i++){
  var db2 = db1.useDb('test')
}
$ node -v 
v0.10.28

mongoose version - latest (3.8.9)

Possible fix

I could fix it locally, by looping through db1.otherDbs object, and returning the connection if it already exists, otherwise it triggers the memory leak. Maybe , useDb function should return an existing db instance, if it already exists in the caller caller_db.otherDbs ? If so, I can pull request that.

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Comments: 18 (1 by maintainers)

Most upvoted comments

Hi @vkarpov15,

Meanwhile, we have identified the “real” cause of our leaks. It was related to the mongoose connections but they were not the root cause of the issue.

It all comes down to Domains in nodejs and the following:

If domains are in use, then all new EventEmitter objects (including Stream objects, requests, responses, etc.) will be implicitly bound to the active domain at the time of their creation. from https://nodejs.org/api/domain.html#domain_implicit_binding

We were using “Raven” to send logs to Sentry. As it happens, this module was creating a domain for each request in which all the request information was being tied to the domain object.

Because Mongoose connections inherit from EventEmitter, they were also using the same Domain object. Therefore, because all Mongoose connections are cached, the domain and consequent request information was never collected.

We have removed the “Raven” module for now, and memory is now controlled.

Either way, thank you for considering this. I had also noticed that there was some “connection state” that was being propagated across all Mongoose Connections and I was not sure if we could simply remove BDs from memory.

Best Regards, Bruno.