How to cache Atlas DB connection using ES6 modules

I’ve deployed several sites on Netlify using serverless functions that connect to a MongoDB Atlas account, roughly according to the instructions here: mongoDB tutorial

A couple:
The seldom viewed Porch realtime temperatures
and the never popular word-puzzles

The key point from that tutorial is (edited slightly): “…The area before the handler function will be executed only when the function starts up. We know that the function won’t necessarily shut down after one execution. With this knowledge, we can use the same client for as long as this particular function exists, reducing how many connections exist.”

The code in the tutorial works because the mongoClient.connect() call occurs before the ‘handler’ and thus only is executed once when the function is loaded. Subsequent invocations of the function just execute the ‘handler’ portion of the code. If the function gets unloaded for lack of use, there will be a performance penalty of about 1.2 seconds to re-establish the connection when the function is next invoked, but that (in my experience) happens rarely if it’s use and that’s acceptable.

In migrating to using ES6 modules, however, I find that with essentially identical code the function module is completely reloaded on each invocation and that any logging done before the ‘handler’ area is logged each time the function is called, which means that I have the 1.2 second performance penalty on each request and after 5 minutes the Atlas connection limit is reached.

There are several topics in the forum with phrases like: “1.2s response time” and “run out of connections” which may be related. I’d like to be able to cache a connection for use between serverless function invocations while using ES6 module format. I can continue to use commonJS module format, but I’m worried that one day support for this technology will end.

Thanks in advance.

ESM seems to be working fine in my minimal example: f-136464.netlify.app/.netlify/functions/esm. After each refresh, the count keep going up. CJS works in a similar manner. Code: GitHub - hrishikesh-k/f-136464

Hi,
Thanks for your response and for providing a test case which I had failed to do. I had made two changes in moving from common modules to ES6 modules, and I had changed my function declaration to the new function format mentioned here If you change your function to look like:
esm.mjs

let num = 1

export default async (req, context) => {
num++
return new Response(JSON.stringify(num), {
status: 200
});
}

I think you’ll find it no longer works. ‘num’ is initialized every time the module is loaded. So, perhaps less to do with the module technology and more to do with changes in the function loading?