Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB connections keep increasing

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?

like image 861
Jonathan Drake Avatar asked Aug 25 '12 18:08

Jonathan Drake


People also ask

How many connections MongoDB can handle?

Your M2 cluster has three nodes with a 500 connection limit per node. Atlas reserves 10 connections per node. If you set your read preference to secondary, Atlas can read from the two secondary nodes for a combined 980 connection limit.

Does MongoDB use connection pooling?

Sharded Cluster Connection Poolingmongos routers have connection pools for each node in the cluster. The availability of connections to individual nodes within a sharded cluster affects latency. Operations must wait for a connection to be established.

How do I close all connections in MongoDB?

open(function (err, db) { db. close(); }); // Open another connection db. open(function (err, db) { db. close(); });


1 Answers

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);
    
like image 183
Stennie Avatar answered Oct 03 '22 04:10

Stennie