Search code examples
reactjsmongodbnetlify-function

Minimizing MongoDB connections in Netlify serverless functions


I've been converting a React app with a REST API to use Netlify's serverless functions instead, and it's working, but I'm noticing a lot of connections (hundreds) to my MongoDB Atlas database while it's just me testing everything is working the same.

Mongo says in their video and blog to make a connection to the database in the function itself, because "we can use the same client for as long as this particular function exists, reducing how many connections exist."

In their example there is only one function, so it makes sense, but assuming there are multiple functions, wouldn't it better for all of the functions to share one connection? Wouldn't this reduce the number of connections even further?

What is the optimal way to connect to Mongo in Netlify serverless functions to reduce connections?


Solution

  • wouldn't it better for all of the functions to share one connection?

    Yes, it would, but it's a serverless javascript we are talking about, means each function runs in an isolated javascript thread, with no access to each other variables, clientPromise in this particular case.

    Options to mitigate/workaround the issue from simplest to robust:

    • cap connection pool to 1-2 connections depending on what you are doing within the handler.
    • consider data API instead of native driver.
    • consider atlas functions.
    • introduce statefull component to handle db operations.