MongoDB connections keep increasing
Asked Answered
S

1

7

I keep hitting my connection limit, but http traffic has remained consistent. I used MMS to profile my mongod process and saw that the number of connections keeps rising:

mongod connections

I'm using the mongoskin wrapper for Node.js (Express). I have a piece of custom route middleware that connects to the mongo db before executing other routes:

var _connect = function(req, res, next) {
  res.db = mongoskin.db(_us.sprintf(
    '%s:%s@localhost:27017/%s?auto_reconnect',
    app.set('mongoDbUser'),
    app.set('mongoDbPw'),
    app.set('mongoDb')
  ));
  next();
};

Am I doing something wrong? How should I be opening and closing connections?

Summer answered 25/8, 2012 at 18:40 Comment(0)
S
7

mongoskin is a wrapper for the node-mongodb-native driver so options for the underlying native driver still apply.

Some suggestions to reduce the number of connections used:

  1. Open your connection before starting the application (you don't want to open a connection in each request):

     var db = new mongoskin.db(...) 
     db.open(function(err, db) { 
         // Application logic
     })
    
  2. Adjust the node-mongo-native connection poolSize. Connection pooling allows a set of connections to be shared in your application rather than always opening new connections. The default poolSize is 1 in older drivers and 5 as of the node-mongo-native 1.1.4 driver which was released Aug 16, 2012.

    So you could try something like:

     var mongoskin = require('mongoskin');
     var serverOptions = {
         'auto_reconnect': true,
         'poolSize': 5
     };
     var db = mongoskin.db('localhost:27017/test', serverOptions);
    
Sundin answered 25/8, 2012 at 23:36 Comment(1)
Thanks Stennie. I connected to the db in each of my Express config sections, then set res.db = app.set('mongoConn') in my first custom middleware. Worked perfectly.Summer

© 2022 - 2024 — McMap. All rights reserved.