When MongoDB throws the “too many open connections” error, it means the number of client connections has reached the maximum allowed limit, and the server can’t handle any more.
🚨 Error Meaning
"too many open connections"
Occurs when MongoDB exceeds the configured limit for simultaneous connections, often due to connection leaks, misconfiguration, or high traffic.
🛠️ Steps to Fix It
✅ 1. Check the Current Connection Count
Use this command to monitor current connections:
You'll see:
✅ 2. Check MongoDB's maxIncomingConnections
Limit
Default is usually 65536, but in some deployments it may be lower.
-
Check the value:
-
Optionally increase it by editing your MongoDB config file (
mongod.conf
) or using the command line:
Restart MongoDB after making changes.
✅ 3. Fix Connection Leaks in Your Application
This is often the root cause.
-
Reuse database connections (especially in web apps).
-
Don't create a new MongoDB client on every request.
-
Close unused or idle connections properly.
Example (Node.js with MongoDB driver):
✅ Good (singleton pattern):
❌ Bad (new connection every call):
✅ 4. Use Connection Pooling
All modern drivers support pooling.
-
Configure reasonable pool sizes:
-
maxPoolSize
(orpoolSize
) -
minPoolSize
(optional)
-
Example (Node.js):
✅ 5. Monitor & Set Alerts
-
Use
MongoDB Atlas
,mongostat
,Cloud Monitoring
, orserverStatus()
to keep an eye on connection spikes. -
Set alerts for connection limits to be proactive.
✅ 6. Kill Stale or Idle Connections (Optional)
Use db.currentOp()
to inspect connections and db.killOp()
to terminate problematic ones (use with caution).
🧠 Bonus: Use ulimit
on Linux
Make sure your OS allows enough file descriptors, or MongoDB won’t be able to open connections even if configured to:
Check MongoDB logs for warnings like Too many open files
.
✅ Summary Table
Action Purpose db.serverStatus().connections
Check live connection count Use connection pooling Prevents connection overload Fix leaks in app logic Prevent new connection on every request Adjust maxIncomingConnections
Raise server's connection limit Monitor with logs/alerts Detect spikes early Adjust ulimit
on OS Prevent low-level limits from blocking
Action | Purpose |
---|---|
db.serverStatus().connections | Check live connection count |
Use connection pooling | Prevents connection overload |
Fix leaks in app logic | Prevent new connection on every request |
Adjust maxIncomingConnections | Raise server's connection limit |
Monitor with logs/alerts | Detect spikes early |
Adjust ulimit on OS | Prevent low-level limits from blocking |