databasesCritical
Fix: MongoDB Connection Pool Exhausted
Application errors: 'MongoTimeoutError: connection timed out'
!Symptoms
- Application errors: 'MongoTimeoutError: connection timed out'
- MongoDB logs showing 'connection accepted' but no available connections
- Spike in application response times
- db.serverStatus().connections.current at or near the limit
?Root Causes
- Connection pool maxPoolSize too small for the workload
- Connection leak — connections opened but never returned to pool
- Slow queries holding connections for too long
- Application instances scaled up without adjusting MongoDB max connections
- MongoDB maxIncomingConnections reached (default 65536)
#Diagnosis Steps
- 1Check current connections: `db.serverStatus().connections`
- 2Check per-app pool stats: look at driver-level connection pool metrics
- 3Find slow queries: `db.currentOp({'secs_running': {$gte: 5}})`
- 4Check mongod log for connection-related messages
- 5Count connections per source: `db.aggregate([{$currentOp: {allUsers: true}}, {$group: {_id: '$client', count: {$sum: 1}}}, {$sort: {count: -1}}])`
>Fix
- 1Increase maxPoolSize in the connection string: `mongodb://host/db?maxPoolSize=100`
- 2Fix connection leaks: ensure every connection is properly returned to the pool
- 3Kill long-running operations: `db.killOp(<opId>)`
- 4Add indexes to speed up slow queries holding connections
- 5Increase MongoDB maxIncomingConnections if server resources allow
*Prevention
- Size connection pool based on: (app instances × maxPoolSize) < MongoDB max connections
- Monitor connection count with Prometheus mongodb_exporter
- Set connection timeout and socket timeout to release stuck connections
- Use connection pool monitoring events in the driver for observability
- Implement query timeouts: `maxTimeMS` on queries to prevent connection hogging
Related Error Messages
MongoTimeoutErrorconnection pool exhaustedunable to acquire connection from pooltoo many open connections