Skip to content

Node.js + MongoDB

Connection Management and Pooling

One client for the process, a pool behind it, and what happens if you connect per request.

IntermediateAbout 6 minutes

Module 1 already said one `MongoClient`. The pool is inside that client: a handful of TCP sockets to the replica set, borrowed per operation. You do not open a socket in the route. You do not connect() per request. This lesson is the knobs, shutdown, and what exhausts the pool.

const client = new MongoClient(process.env.MONGO_URI, {
  maxPoolSize: 20,
  minPoolSize: 2,
  maxIdleTimeMS: 60_000,
  serverSelectionTimeoutMS: 5_000,
});
await client.connect();

process.on("SIGTERM", async () => {
  await client.close();
  process.exit(0);
});
Startup. maxPoolSize is 'how many sockets', not 'how many users'.

Default maxPoolSize is 100 — often more than a single Node process needs. Too high: you multiply processes × 100 and hit Atlas connection limits. Too low: requests wait in the wait queue (waitQueueTimeoutMS) and fail while MongoDB is fine. serverSelectionTimeoutMS is 'no primary in this many ms', not query time (maxTimeMS is later).

  • Long-running server — connect once at boot, close on SIGTERM.
  • Serverless / Next.js — cache the client on globalThis so warm invocations reuse the pool (web-apps lesson).
  • Tests — one client per worker, or you leak pools.

Interview question

How should a Node.js process manage MongoDB connections?

Think about it first.