How does Nodejs MongoDB connection pool work?

1.7k Views Asked by At

In the following code, the mongoClient.connect call (by default) opens a pool of 5 connections. Since Node is single threaded, only one call (either func1 or func2 can be processed at any time (The second call waits till the first completes). So only one of the five connections from the pool is ever used.

Using Nodejs cluster, if we fork multiple instances, each instance opens it's own connection pool (5 connections per instance).

The question is - how does MongoDB connection pool work in the Node environment. How can we test this to demonstrate the use of multiple connections from the same pool at the same time?

mongoClient.connect('mongodb://localhost', function(err, db){
  app.get('/func1', function(req, res){
    for (var i=0; i<100000; i++){
      db.collection('test').insert({a:i});
    }
    res.end();
  });

  app.get('/func2', function(req, res){
    for (var i=0; i<100000; i++){
      db.collection('test').insert({a:i});
    }
    res.end();
  });
});
1

There are 1 best solutions below

3
On

insert is async so the /func1 and /func2 handlers both just queue up 100000 inserts and then return. The connection pool then operates in the background to execute those inserts no more than 5 at a time (1 per connection in the pool).