Why shouldn't we keep the db connection open all time

At the moment we create one connection from our node server to the db just once at server start and keep it open all time. Why is this approach bad? When should connections be opened/closed to minimize latency and maximize performance?

Thank you very much for your good advises in advance.

Hi @max_matinpalo,

There is more overhead in establishing new connections than reusing an existing connection, so the general advice is actually to have a pool of established ready-to-use connections where possible per Connection Pool Overview. Connection pooling support is included in most of the official MongoDB drivers.

Connection options and defaults may vary by driver and version so I recommend consulting the relevant version of driver documentation. For more information see Connection Options in the Node.js driver.

Each open connection consumes at least 1MB of RAM on the MongoDB server, so a large number of connections can impact the amount of available RAM for your working set. Related discussion: Memory allocated per connection - #2 by Stennie.

For some suggestions around managing connections, please see Tuning Your Connection Pool Settings.

Regards,
Stennie

3 Likes

Thank you Stennie for a detailed and very clear answer :+1:

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.