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();
});
});
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With