Node.js + MongoDB
Connection Management and Pooling
One client for the process, a pool behind it, and what happens if you connect per request.
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);
});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
globalThisso 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?
One MongoClient for the process. It owns the connection pool. I connect at startup, reuse it in every handler, and close on SIGTERM. A new client per request exhausts server connections. maxPoolSize is sockets per process; I keep it modest under Atlas limits. Serverless caches that client across invocations.