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.