# pymongo.errors.ServerSelectionTimeoutError: connection closed, Timeout: 30s

- **ID:** `database/mongodb-connection-pool-timeout`
- **Domain:** database
- **Category:** connection_error
- **Verification:** ai_generated
- **Fix Rate:** 85%

## Root Cause

MongoDB driver's server selection timeout occurs when all connections in the pool are closed or exhausted, often due to network interruptions, server overload, or connection pool misconfiguration in the application.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| MongoDB 5.0 | active | — | — |
| MongoDB 6.0 | active | — | — |
| MongoDB 7.0 | active | — | — |

## Workarounds

1. **Set MongoClient options: client = MongoClient('mongodb://localhost:27017', maxPoolSize=50, minPoolSize=10, retryWrites=True, retryReads=True). This ensures connections are maintained and operations retry on failure.** (85% success)
   ```
   Set MongoClient options: client = MongoClient('mongodb://localhost:27017', maxPoolSize=50, minPoolSize=10, retryWrites=True, retryReads=True). This ensures connections are maintained and operations retry on failure.
   ```
2. **Use MongoDB drivers' built-in heartbeat monitoring: MongoClient('mongodb://localhost:27017', heartbeatFrequencyMS=10000). This detects closed connections and reconnects automatically.** (80% success)
   ```
   Use MongoDB drivers' built-in heartbeat monitoring: MongoClient('mongodb://localhost:27017', heartbeatFrequencyMS=10000). This detects closed connections and reconnects automatically.
   ```
3. **Wrap database calls in a retry decorator: import time; from pymongo.errors import ServerSelectionTimeoutError; def retry_on_timeout(func): for attempt in range(3): try: return func() except ServerSelectionTimeoutError: time.sleep(2**attempt); raise.** (90% success)
   ```
   Wrap database calls in a retry decorator: import time; from pymongo.errors import ServerSelectionTimeoutError; def retry_on_timeout(func): for attempt in range(3): try: return func() except ServerSelectionTimeoutError: time.sleep(2**attempt); raise.
   ```

## Dead Ends

- **** — This only delays failure; if connections are genuinely closed, the timeout will eventually trigger anyway, and the application remains unresponsive longer. (90% fail)
- **** — The same configuration or network problem persists; the error will reappear shortly after restart. (95% fail)
- **** — This prevents connection reuse, causing new connections for every operation, which increases latency and may exhaust server resources. (70% fail)
