MongoDB Atlas: connect from AWS Lambda and Vercel without pool exhaustion
Shows how to fix mongoDB Atlas: connect from AWS Lambda and Vercel without pool exhaustion. Use it when you hit this exact problem. Skip it when your error message or symptom looks different.
TL;DR
For "serverSelectionTimeoutMS": the failure mode: every invocation creates a client, each client opens a pool, and the cluster hits its connection cap under load. ``js // client created ONCE per function instance, outside the handler const { MongoClient } = require('mongodb'); const client = new MongoClient(process.env.MONGODB\_URI, { maxPoolSize: 5, // small: one instance needs few concurrent ops serverSelectionTimeoutMS: 5000, }); const ready = client.connect(); exports.handler = async (event) => { await ready; const col = client.db('mydb').collection('events'); await col.insertOne({...event
serverSelectionTimeoutMSSteps
- - Create the client outside the handler so warm invocations reuse it. Creating it inside the handler is the bug.
- Keep
maxPoolSizesmall (1 to 5). Total connections = instances x pool size; hundreds of instances x 100 pool = outage. - Do not
close()the client at the end of the handler. Let the frozen instance keep it for the next warm invocation. - Await the initial connect once (a module-level promise) so concurrent warm invocations do not race multiple connects.
- Set a short
serverSelectionTimeoutMSso a cold start with a bad network path fails fast instead of burning the whole invocation timeout.
When to use
You are seeing this: Creating it inside the handler is the bug. - Keep maxPoolSize small (1 to 5). Use this skill when you run into "MongoDB Atlas: connect from AWS Lambda and Vercel without pool exhaustion".
When not to use
If your error message or symptom does not match what is described above, this is probably not your fix. Search for your exact error text instead of forcing this one to fit.
Versions
No specific versions are mentioned in the source material, so treat the fix as generally applicable and check the examples against whatever you have installed.
Variants
Other phrasings of the same problem that show up in reports:
// client created ONCE per function instance, outside the handler
// client created ONCE per function instance, outside the handler
const { MongoClient } = require('mongodb');
const client = new MongoClient(process.env.MONGODB_URI, {
maxPoolSize: 5, // small: one instance needs few concurrent ops
serverSelectionTimeoutMS: 5000,
});
const ready = client.connect();
exports.handler = async (event) => {
await ready;
const col = client.db('mydb').collection('events');
await col.insertOne({ ...event, at: new Date() });
return { ok: true };
};Why this happens
The original report does not dig into a root cause. It documents the symptom and the fix that resolved it.