MongoDB Connection Pool Timeout Fix: Configure Timeouts and Pool Limits Correctly
Quick Answer
- Conclusion: MongoDB connection pool timeouts are almost always caused by misconfigured
connectTimeoutMS,socketTimeoutMS, ormaxPoolSizevalues that don't match your network latency and workload characteristics. - First checks: Verify network latency to your MongoDB instance, confirm the server is reachable, and check whether your application is exhausting the connection pool (look for
connection pool is fullorServer selection timed outerrors). - Minimal fix: Set
connectTimeoutMSto 2–3× your measured network latency,socketTimeoutMSto 2–3× your slowest operation duration, and ensuremaxPoolSizeis large enough for your concurrency (start with 100, increase if you see pool exhaustion). - Environment boundary: These settings apply to all official MongoDB drivers (Node.js, Python, Java, etc.) and are configured either in the connection string or via driver-specific client options. Java driver 3.7+ defaults
connectTimeoutMSto 10ms; most other drivers default to 0 (no timeout).
What Problem It Solves
MongoDB connection pool timeouts manifest as MongoTimeoutError, MongoNetworkError, or connection pool is full errors. These occur when:
- The driver cannot establish a TCP connection within the configured timeout.
- The pool has no available connections and the wait queue exceeds
waitQueueTimeoutMS. - Connections are silently dropped due to idle timeouts or network instability.
Properly configuring pool parameters prevents these failures and ensures your application maintains predictable latency under load.
Parameters and Environment Variables
All connection pool settings are configured either in the MongoDB connection string or via driver-specific client options. The table below lists the parameters that control pool behavior.
| Parameter | Default | Purpose | Recommended Setting |
|---|---|---|---|
connectTimeoutMS | 0 (Java 3.7+: 10) | Max time to establish a TCP connection | 2–3× measured network latency |
socketTimeoutMS | 0 (no timeout) | Max time for socket read/write operations | 2–3× slowest operation duration |
minPoolSize | 0 | Minimum connections kept open in the pool | Match expected baseline concurrency |
maxPoolSize | 100 | Maximum connections in the pool | Based on concurrency and server limits |
maxConnecting | 2 | Max simultaneous connection establishments | Increase for faster pool warm-up |
maxIdleTimeMS | Driver-specific | Remove idle connections after this duration | 10–30 minutes for most workloads |
waitQueueTimeoutMS | 0 (no limit) | Max time a thread waits for a connection | 5000–10000ms for production |
Connection String Example
mongodb://user:pass@host1:27017,host2:27017/?connectTimeoutMS=5000&socketTimeoutMS=30000&maxPoolSize=50&minPoolSize=5&waitQueueTimeoutMS=10000
Driver-Specific Configuration (Node.js)
JAVASCRIPTconst { MongoClient } = require('mongodb'); const client = new MongoClient(uri, { connectTimeoutMS: 5000, socketTimeoutMS: 30000, minPoolSize: 5, maxPoolSize: 50, maxConnecting: 5, maxIdleTimeMS: 600000, waitQueueTimeoutMS: 10000 });
Root Cause Analysis
Why connectTimeoutMS Matters
When a driver attempts to establish a connection, it waits up to connectTimeoutMS for the TCP handshake to complete. If the value is too low (e.g., the Java driver's default of 10ms), connections to remote or cloud-hosted MongoDB instances will fail even when the server is healthy. The timeout must exceed the round-trip time (RTT) to your MongoDB server.
Why socketTimeoutMS Is Not for Query Limits
A common mistake is using socketTimeoutMS to limit long-running queries. This parameter only controls how long the driver waits for a socket read/write to complete. If a query legitimately takes longer than socketTimeoutMS, the driver will abort the connection, potentially leaving the operation in an unknown state on the server. Use maxTimeMS at the query level instead.
Why Pools Exhaust
When maxPoolSize is reached, new operations wait for a connection to become available. If operations are slow or connections leak (not properly closed), the pool fills up and requests queue. The waitQueueTimeoutMS parameter determines how long operations wait before failing with a timeout error.
Common Errors and Fixes
| Error | Root Cause | Fix |
|---|---|---|
MongoTimeoutError: Server selection timed out after 30000 ms | Server unreachable or serverSelectionTimeoutMS too low | Check network/firewall; verify replica set health; adjust serverSelectionTimeoutMS |
MongoNetworkError: connection 5 to 127.0.0.1:27017 timed out | connectTimeoutMS too low for network latency | Increase connectTimeoutMS to 10000ms or higher |
MongoError: pool destroyed | MongoClient closed while operations in flight | Keep MongoClient as a singleton; never close it during application runtime |
MongoError: connection pool is full | maxPoolSize too low or connection leak | Increase maxPoolSize; audit connection release logic |
Production Notes and Security Checks
Calculating Total Connections
When multiple application servers connect to the same MongoDB deployment, calculate total connections to avoid exceeding server limits:
Total connections = app_servers × maxPoolSize × replica_set_members
Example: 4 app servers × 100 maxPoolSize × 3-member replica set = 1200 connections per mongod. MongoDB's default maxIncomingConnections is 65536, but your OS and hardware may impose lower limits.
Operational Guidelines
- Keep MongoClient as a singleton: Creating and destroying clients frequently causes
pool destroyederrors and connection churn. - Monitor pool usage: Use
db.serverStatus().connectionsand driver metrics to track pool utilization. - Change parameters via configuration management: Avoid ad-hoc changes in production; use environment variables or config files.
- Secure connection strings: Store credentials in environment variables or secret managers, never in source code.
- Restrict network access: Use firewall rules and MongoDB's
bindIpsetting to limit which hosts can connect.
When to Adjust Parameters
- Increase
maxConnectingif your application experiences slow cold-start connection establishment. - Increase
maxIdleTimeMSif you see frequent connection re-establishment during traffic spikes. - Set
waitQueueTimeoutMSto a finite value (e.g., 10000) to fail fast under overload rather than hanging indefinitely.
FAQ
Q: How do I set connectTimeoutMS based on network latency?
A: Measure the round-trip time to your MongoDB server using ping or traceroute. Set connectTimeoutMS to 2–3× that value. For example, if RTT is 100ms, use 500ms. If you're unsure, start with 5000ms and reduce gradually while monitoring connection failures.
Q: What's the difference between socketTimeoutMS and maxTimeMS?
A: socketTimeoutMS is a driver-level TCP socket timeout that detects dead connections. It should never be used to limit query execution time. maxTimeMS is a server-side query timeout that cancels operations exceeding the limit. Always use maxTimeMS for query duration limits.
Q: How do I calculate the required maxPoolSize for production?
A: Use the formula: app_servers × maxPoolSize × replica_set_members. For example, 4 app servers with maxPoolSize=100 connecting to a 3-member replica set means each mongod receives 400 connections. Ensure this stays below MongoDB's maxIncomingConnections (default 65536) and your OS connection limits.