Hi, thanks for pointing that out @Alex Bevilacqua !
Yes, I’ve reviewed the MongoDB guidance on “managing connections with AWS Lambda”. In our setup is like this:
let mainConnection: mongoose.Connection | null = null;
const clientConnectionCache = new Map<string, CachedConnection>();
const defaultConnectionOptions: mongoose.ConnectOptions = {
maxIdleTimeMS: 30_000,
minPoolSize: 0,
maxPoolSize: 5,
};
And as you see :
-
The connection objects (
mainConnectionandclientConnectionCache) are declared in the global scope**, outside the Lambda handler. -
Our
getMainConnectionandgetClientConnectionfunctions check for existing connections and reuse them if available. -
Inside the handler, we “just call these functions” ; we don’t create new connections there.
-
context.callbackWaitsForEmptyEventLoopis also set tofalseto allow reuse between invocations as below in our db connection source code:
exports.handler = async function(event, context) {
context.callbackWaitsForEmptyEventLoop = false;
const db = await getMainConnection(); // call the global connection function
// … do database operations
};
Despite following this pattern, we are still observing a very high number of concurrent connections (3–4.5K) at peak times. We are trying to understand why connections aren’t being fully reused or cleaned up as expected.
Would you have insights into why thousands of connections still accumulate even with the recommended global scope pattern?