MongoDB Too Many Connections in Serverless Node.js: The Fix

MongoDB too many connections in serverless Node.js? Fix it with a cached client, a sized maxPoolSize, idle timeouts and Atlas rate-limit math for Lambda.

TL;DR

  • What: “MongoDB too many connections” in serverless Node.js usually means a new MongoClient per request, per hot reload, or per cold instance.
  • Why it matters: Atlas caps connections per node and, on smaller tiers, how many new connections it accepts per second.
  • What to do: Create one client at module scope, cache it on globalThis, size maxPoolSize from concurrency, and close idle sockets before suspension.
  • Key stat: An Atlas M10 node accepts at most 1,500 connections and 15 new connections per second.

To fix MongoDB too many connections in serverless Node.js, never call new MongoClient() inside a handler. Create one client at module scope, cache it on globalThis so dev hot reloads reuse it, set maxPoolSize from instances × per-instance concurrency, set a short maxIdleTimeMS, and on Vercel Fluid call attachDatabasePool(client).

The MongoDB too many connections problem is when an application opens more sockets than a MongoDB node allows, so new connections queue, time out or are dropped. In serverless Node.js it is caused by connection lifecycle mistakes: clients created per invocation, duplicated by hot module reloading, or left idle in suspended function instances.

MongoDB too many connections is one of the most repeated complaints from teams running Next.js, Express-on-Lambda or Vercel Functions against Atlas. The MongoDB community forum has threads titled “Vercel + MongoDB just killed my website” and “AWS Lambda Invocations Trigger MongoDB Connection Spikes”. The symptoms vary: the Atlas connections chart climbs to the tier limit, requests fail with MongoServerSelectionError, or a deploy makes everything slow for a minute. The usual advice (“cache the client”) is correct but incomplete. It does not explain pool sizing, the per-second connection rate limit on small Atlas tiers, or why suspended functions keep sockets open. This post shows the broken code, the fixed code for Next.js, Lambda and Mongoose, and the arithmetic to check whether your cluster can survive a traffic spike. We also ran the hot-reload scenario in a sandbox so you can see the difference in numbers.

Why does MongoDB hit too many connections in serverless Node.js?

Serverless MongoDB connection problems come from multiplication: every client owns a pool, and serverless platforms create many clients. In the Node.js driver, every MongoClient has its own pool per server, and maxPoolSize defaults to 100. Each client also opens up to two monitoring sockets per server. The same MongoDB page says a client on a three-node replica set can hold 106 open sockets when it only reads from the primary.

Three code paths create extra clients:

  1. Client inside the handler. Each invocation builds a new pool. MongoDB’s Lambda guide warns this “can result in your application exceeding database connection limits”.
  2. Hot module reloading in development. Next.js re-evaluates your lib/mongodb.ts on edits. A module-level client is rebuilt each time, and the old one is never closed.
  3. Many warm instances. Even with a correct singleton, 200 instances means 200 pools. The worst case is instances × maxPoolSize.

Vercel’s CTO makes a useful point here: the steady-state math is the same for servers and serverless. In Vercel’s analysis, 1,000 concurrent requests need 1,000 pool clients in every compute model. The serverless-specific bug is leaked idle connections, covered below.

What does the broken MongoDB connection code look like?

The broken pattern creates the client where the request is handled. It works in a demo and fails under load.

// app/api/users/route.ts — BROKEN
import { MongoClient } from 'mongodb';

export async function GET() {
  const client = new MongoClient(process.env.MONGODB_URI!); // new pool every request
  const users = await client.db('app').collection('users').find().limit(20).toArray();
  return Response.json(users); // client never closed; sockets linger
}

A subtler version puts the client at module scope but without a global cache. That is fine in production, but in next dev every edit creates another client:

// lib/mongodb.ts — LEAKS IN DEV
import { MongoClient } from 'mongodb';
export const client = new MongoClient(process.env.MONGODB_URI!);

Closing the client at the end of each request “fixes” the count but pays for a new TCP and TLS handshake plus authentication every time. Vercel’s write-up calls this trade-off out: closing after every request “would stop leaks but introduce significant latency”.

How do you fix MongoDB too many connections in Next.js?

Fix MongoDB too many connections in Next.js by creating the client once and storing it on globalThis, so module re-evaluation reuses the same instance. The driver connects lazily on the first operation, so you do not need to cache a connect() promise.

// lib/mongodb.ts — FIXED
import { MongoClient } from 'mongodb';
import { attachDatabasePool } from '@vercel/functions';

const uri = process.env.MONGODB_URI;
if (!uri) throw new Error('MONGODB_URI is not set');

const globalForMongo = globalThis as unknown as { _mongoClient?: MongoClient };

export const client =
  globalForMongo._mongoClient ??
  new MongoClient(uri, {
    maxPoolSize: 10,          // sized from per-instance concurrency, not the default 100
    maxIdleTimeMS: 5_000,     // close idle sockets quickly
    serverSelectionTimeoutMS: 5_000,
    appName: 'web-api',       // shows up in Atlas logs
  });

globalForMongo._mongoClient = client;

// Vercel Fluid compute: close idle sockets before the instance suspends
attachDatabasePool(client);

export const db = client.db('app');

We store the client in all environments, not only in development. In production the module is evaluated once per instance anyway, so the global cache costs nothing and protects against bundler duplication.

What we ran to check the hot-reload fix

We simulated Next.js hot reloading in a sandbox: Node.js 22.23.5, mongodb driver 7.9.1 and @vercel/functions 3.11.3. A script imported each module 20 times with a cache-busting query string, which forces re-evaluation like HMR does, and counted distinct client objects.

$ node hmr.mjs
{ moduleEvaluations: 20, brokenClients: 20, cachedClients: 1 }
attachDatabasePool(MongoClient): ok (no throw)

The plain module created 20 clients, each with its own pool. The globalThis version created one. attachDatabasePool accepted a MongoClient without error outside Vercel. Vercel’s reference lists MongoDB among supported pool types. We had no MongoDB server binary in the sandbox, so we did not measure live socket counts.

How should you set maxPoolSize for serverless MongoDB?

Set maxPoolSize from how many operations one instance runs at once, then multiply by your peak instance count and compare with your Atlas tier. The default of 100 assumes a long-running server handling many requests.

Atlas limits are per node. The Atlas limits page lists 1,500 connections for M10, 3,000 for M20 and M30, and 6,000 for M40. Atlas also reserves 10 connections per node. We used those limits in a short Node script. It ignores monitoring sockets, so real numbers are slightly higher.

maxPoolSize=100 instances=50   worst-case=5000   M10:OVER M20:OVER M30:OVER M40:fits
maxPoolSize=100 instances=200  worst-case=20000  M10:OVER M20:OVER M30:OVER M40:OVER
maxPoolSize=10  instances=50   worst-case=500    M10:fits M20:fits M30:fits M40:fits
maxPoolSize=10  instances=200  worst-case=2000   M10:OVER M20:fits M30:fits M40:fits

On Lambda, one instance handles one request at a time, so a small pool is enough. Don’t go to 1 by reflex, though. Vercel argues that a max pool size of 1 does not reduce total connections and hurts Fluid compute, where one instance serves concurrent requests. My recommendation: start at 5–10 on Fluid, 2–5 on Lambda when a handler fires parallel queries, and set waitQueueTimeoutMS so overload fails fast. The driver’s waitQueueTimeoutMS defaults to 0, meaning no limit.

Why do idle MongoDB connections leak when functions suspend?

Idle connections leak because pool timers do not run while a function instance is frozen. The Vercel explanation is clear. A pool closes idle sockets with a timer. A suspended instance never fires it, so the socket stays open until the VM is deleted or the server times it out. After a deploy, every old instance suspends at once and leaks its pool together.

There are two mitigations, depending on platform:

  1. Vercel Fluid compute: call attachDatabasePool(client). It uses waitUntil to keep the instance alive just long enough to close idle connections. Vercel suggests an idle timeout of around 5 seconds.
  2. AWS Lambda: there is no pre-suspend hook. MongoDB recommends maxIdleTimeMS of 60000 so sockets close after 1 minute of idle time once the instance thaws.

Check your driver version too. MongoDB’s docs note that before driver 6.18.0, idle connections were not closed when minPoolSize was 0. If you are on an older 6.x release, idle timeouts may not behave as you expect. Our Node.js 24 LTS upgrade guide covers bumping runtime and dependencies together.

What is the Atlas connection rate limit most guides miss?

The Atlas connection rate limit caps how many new connections a node accepts per second, separately from the total connection cap. Most “too many connections” guides only discuss the total. According to the Atlas limits page, M10 and M20 accept 15 new connections per second per node, M30 accepts 24 and M40 accepts 85. The limit is always on for M10 and M20. For M30 and above it applies on MongoDB 9.0 or later. When a node hits it, Atlas queues new attempts and drops some if the overload lasts.

This matters for cold starts. A deploy or traffic spike can start hundreds of instances, each opening fresh sockets. We did the arithmetic for a burst:

cold burst 100 new conns on M10: >= 6.7s to admit at 15/s/node
cold burst 300 new conns on M10: >= 20.0s to admit at 15/s/node
cold burst 300 new conns on M40: >= 3.5s to admit at 85/s/node

A 300-connection burst on M10 is below the 1,500 total cap, yet it needs at least 20 seconds to be admitted. That looks like random MongoServerSelectionError timeouts after deploys. Fixes: keep pools small so each instance opens fewer sockets, use gradual traffic shifting such as Vercel rolling releases, and retry with jitter rather than in lockstep. Our retry storm prevention guide shows how to stop retries amplifying the burst.

How do you fix MongoDB connections on AWS Lambda and with Mongoose?

On Lambda, define the client outside the handler so warm invocations reuse it. This is MongoDB’s own Lambda best practice.

// handler.ts — AWS Lambda, FIXED
import { MongoClient } from 'mongodb';

const client = new MongoClient(process.env.MONGODB_URI!, {
  maxPoolSize: 5,
  maxIdleTimeMS: 60_000,
});

export const handler = async () => {
  const count = await client.db('app').collection('orders').countDocuments();
  return { statusCode: 200, body: JSON.stringify({ count }) };
};

With async handlers you do not need callbackWaitsForEmptyEventLoop. MongoDB notes it is not applicable for async handlers. For sharded clusters, add srvMaxHosts=3 to the URI. The same guide says a ten-shard cluster otherwise makes the driver connect to all 30 mongos instances.

Mongoose users need one extra detail: cache the promise, not only the result. If two invocations start before the first connect resolves, both call connect(). The Mongoose Lambda guide assigns the variable before awaiting for this reason, with serverSelectionTimeoutMS: 5000.

// lib/mongoose.ts — FIXED
import mongoose from 'mongoose';

const g = globalThis as unknown as { _mongoose?: Promise<typeof mongoose> };

export function connectMongoose() {
  g._mongoose ??= mongoose
    .connect(process.env.MONGODB_URI!, { maxPoolSize: 10, serverSelectionTimeoutMS: 5_000 })
    .then((m) => m);
  return g._mongoose;
}

If you add Redis or another pooled client to the same functions, the same rules apply. Our cache stampede prevention post covers protecting MongoDB when a cache layer expires.

MongoDB serverless connection fixes compared (sources linked in each row)
Platform Client placement Starting maxPoolSize Idle handling Source
Next.js on Vercel Fluid Module scope + globalThis cache 5–10 (not 1) attachDatabasePool, ~5 s idle timeout Vercel KB
AWS Lambda (driver) Outside the handler Small; 1 request per instance maxIdleTimeMS: 60000 MongoDB Atlas docs
Mongoose (any) Cached connect promise Same as driver serverSelectionTimeoutMS: 5000 Mongoose docs
Long-running Node server One client per process Default 100 Optional maxIdleTimeMS Node.js driver docs

The NexGismo verdict: caching the client is necessary but not enough. I’d treat maxPoolSize as a capacity decision, worst case = instances × pool, and check it against both the Atlas connection cap and the per-second rate limit. On Vercel, add attachDatabasePool. On a small tier with spiky traffic, a smaller pool and rolling releases beat buying a bigger cluster first.

  • Every MongoClient in the Node.js driver has its own pool per server, with maxPoolSize defaulting to 100.
  • Creating a MongoClient inside a request handler opens a new pool per invocation and can exhaust Atlas connection limits.
  • Caching the client on globalThis stops Next.js hot reloads from creating a new client on every module re-evaluation.
  • Atlas M10 nodes allow 1,500 connections and accept 15 new connections per second, so cold-start bursts can time out below the total cap.
  • Suspended serverless instances cannot run idle timers, so idle sockets leak until the VM is deleted or the server closes them.
  • On Vercel Fluid compute, attachDatabasePool closes idle MongoDB connections before an instance suspends.

Frequently Asked Questions

How do I fix too many connections in MongoDB?

Create one MongoClient per process at module scope and reuse it for every request. In Next.js, cache it on globalThis so hot reloads reuse it. Then size maxPoolSize so instances × pool size stays under your Atlas tier’s per-node limit, and set maxIdleTimeMS so idle sockets close.

What is the default connection pool size in the MongoDB Node.js driver?

The default maxPoolSize is 100 per server, and minPoolSize defaults to 0. Each MongoClient also opens up to two monitoring sockets per server, so a client on a three-node replica set reading only from the primary can hold 106 open sockets.

Should I close the MongoDB connection after each Lambda invocation?

Usually no. Closing after every invocation stops leaks but adds a new handshake and authentication to each request. MongoDB recommends defining the client outside the handler, reusing it across invocations, and setting maxIdleTimeMS so idle connections close after about a minute.

How many connections can MongoDB Atlas handle?

Atlas limits connections per node by tier. M10 allows 1,500, M20 and M30 allow 3,000, and M40 allows 6,000. Atlas also limits new connections per second: 15 for M10 and M20, 24 for M30 and 85 for M40, with M30 and above limited on MongoDB 9.0 or later.

Why does Next.js create multiple MongoDB connections in development?

Next.js hot module reloading re-evaluates your database module when files change. A module-level new MongoClient() runs again each time and the previous client is not closed. Storing the client on globalThis keeps one instance across reloads, because the dev server process and its global object persist.

MongoDB too many connections is a lifecycle bug, not a driver bug. Move the client out of the handler, cache it on globalThis, and pick a pool size you can defend with arithmetic. Close idle sockets before instances freeze, and remember the per-second rate limit on small Atlas tiers when you plan deploys. Run the worst-case calculation for your own peak instance count before your next launch. If you’re building AI features on the same stack, our guide to semantic caching for LLMs in Node.js uses the same connection rules for its vector store.

Sources