# Atlas from serverless functions
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, at: new Date() });
return { ok: true };
};
```
## Rules
- Create the client outside the handler so warm invocations reuse it. Creating it inside the handler is the bug.
- Keep `maxPoolSize` small (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 `serverSelectionTimeoutMS` so a cold start with a bad network path fails fast instead of burning the whole invocation timeout.
## Verify
Load-test with concurrent invocations and watch the Atlas Connections metric. It should plateau near instances x maxPoolSize, not climb without bound.