Search code examples
node.jsmongodbkeep-alive

How to set keepalive in node js mongo db(outbound connection)


Please help me out how to implement keepalive in nodejs mongodb. As I am using mongo do outbound connections from node js

How to validate the keepalive is working or not.

Please help me if you have any idea.


Solution

  • The official documentation given by MongoDB states about different connection operations. For implementing a keep alive, you need to use the keepAlive option in the connection URI.

    // Connection URI
    const uri = "mongodb+srv://sample-hostname:27017/?keepAlive=true";
    

    This will enable keepAlive on the TCP socket.

    If you want to have a delay before initiating keepAlive on the TCP socket, you can use the keepAliveInitialDelay option in the URI. The keepAliveInitialDelay should be of an integer type.

    // Connection URI
    const uri = "mongodb+srv://sample-hostname:27017/?keepAlive=true&keepAliveInitialDelay=30000";