Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Nodejs MongoDB connection pool work?

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();
  });
});
like image 924
Raj Avatar asked Jun 23 '15 14:06

Raj


People also ask

How does MongoDB connection pooling work?

A connection pool helps reduce application latency and the number of times new connections are created. A connection pool creates connections at startup. Applications do not need to manually return connections to the pool. Instead, connections return to the pool automatically.

How does connection pool work in node JS?

The Node. js driver supports connection pooling. Connection pooling allows your application to reuse existing connections by automatically saving the connection to a pool so it can be reused, rather than repeatedly creating a new connection to the SAP HANA database server.


1 Answers

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).

like image 54
JohnnyHK Avatar answered Oct 12 '22 12:10

JohnnyHK