Question 45 / 50
Must KnowMediumDebuggingNode.js
A Node.js API creates new MongoClient() inside the request handler and closes it at the end. Latency is high and the cluster shows connection spikes. What is wrong?
Think about it first.
Short answer
Each request pays handshake and pool setup, and you can exhaust the server's connection limit. Create one MongoClient for the process, connect once at startup, and reuse the pool on every request.
Why?
MongoClient owns the connection pool. In serverless, you still cache the client in the global scope across invocations when the runtime allows it. Closing per request destroys the pool's whole purpose.
Example
const client = new MongoClient(process.env.MONGO_URI);
await client.connect();
const db = client.db("app");Interview tip
This is a very common backend interview question. Be blunt: one client per process.
Common mistake
Blaming MongoDB 'being slow' without looking at how many clients the app opens.
How did you do?