Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when connections to MongoDB are not closed?

I have the following PHP script that basically connects to the MongoDB, writes a document and then closes the connection 19000 times:

<?php
for($i=0; $i < 19000; $i++) {
    $con = new Mongo("mongodb://localhost:27017");
    $db = $con->selectDB('test');

    $col = $db->selectCollection('close_wait_test');
    $col->insert(array('Test' => 'Value1'));

    $con->close();
}
?>

Running this script once works fine, but if I run the script a few seconds later, I get the 'Cannot assign requested address' exception, which is understandable as the server system probably ran out of ports.

If however, I remove $con->close(); I can run that script over and over again without any noticeable strain on the database. I'm assuming this is because the connect to the database is persistent and reuses the same initial connection on the script.

What I'd like to know is if 20k+ different users ran 1 loop of this script at the same time, what would happen to the database? e.g. would the available connections simply run out because each user need creates one connections to the database? or would all those users be using the same initial connection created by the first user?

like image 401
Ryan Simms Avatar asked Apr 16 '12 12:04

Ryan Simms


People also ask

Is it necessary to close MongoDB connection?

There is no need for closing the connection explicitly. This way the application avoids creating and closing connections (which is an expensive operation).

Does Mongoose close connection automatically?

You do need to call mongoose. disconnect() to close the connection, but you also need to wait until all save calls have completed their async work (i.e. called their callback) before doing that.

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.


1 Answers

You should not be calling ->close() on every iteration. If you call close, you tell the driver to not reuse a persistent connection. If you run this in a tight loop, then the OS runs out of ports to use, as they are all in TIME_WAIT state.

The PHP driver uses persistent connections, and if (without calling ->close) you run "new Mongo" in a tight loop like in your example, the driver will not make new connections and reuse the already existing one.

like image 152
Derick Avatar answered Oct 13 '22 10:10

Derick