Connection closed to mongo after idle time (Node)

Kieran Bester 20 Reputation points
2023-07-01T18:56:57.28+00:00

Howdy :)

We are pretty new in the Azure space, so excuse any ignorance..

We have created a couple of functions, userGet, userCreate etc. We are using CosmosDB (Mongo). The issue is that after some idle time when a request is made we receive:

Exception: {"code":"029","message":"Internal error with creating mongo client. connection 2 to xx.xx.xx.xx:10255 closed"}

We are creating a connection to the mongo client before each function run (would be nice to have singleton, but seems that isn't supported yet for Node?)

Happy to hear ideas on how to improve our setup. In particular the singleton instance as that just makes so much more sense, and maybe that will help with the issue of connections

Thanks

Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
5,912 questions
Azure Cosmos DB
Azure Cosmos DB
An Azure NoSQL database service for app development.
1,902 questions
0 comments No comments
{count} votes

Accepted answer
  1. Sedat SALMAN 14,180 Reputation points MVP
    2023-07-02T05:01:34.8866667+00:00

    You may have several options as follows

    In Azure Functions, it's recommended to reuse client instances rather than creating a new one with each function invocation. You could create a single, static client that every function invocation can use. This also applies to Azure Cosmos DB clients, and you can follow the example provided by Microsoft's official documentation to achieve that.

    You could create a Singleton MongoDB connection that is used across your application. You can check an example of how to achieve this in Node.js on StackOverflow.

    It is also recommended to set server socket options to keep the connection alive. Moreover, you could ping the database at regular intervals to prevent the connection from going idle. This approach is especially useful if your application experiences long periods of inactivity. Here's an example of how to implement this in Node.js.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.