database connection_error ai_generated true

pymongo.errors.ServerSelectionTimeoutError:连接已关闭,超时:30秒

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

ID: database/mongodb-connection-pool-timeout

其他格式: JSON · Markdown 中文 · English
85%修复率
82%置信度
1证据数
2023-11-05首次发现

版本兼容性

版本状态引入弃用备注
MongoDB 5.0 active
MongoDB 6.0 active
MongoDB 7.0 active

根因分析

当连接池中的所有连接都已关闭或耗尽时,MongoDB 驱动程序的服务器选择超时发生,通常由网络中断、服务器过载或应用程序中的连接池配置错误引起。

English

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.

generic

官方文档

https://www.mongodb.com/docs/drivers/pymongo/

解决方案

  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.
  2. 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.

无效尝试

常见但无效的做法:

  1. 90% 失败

    This only delays failure; if connections are genuinely closed, the timeout will eventually trigger anyway, and the application remains unresponsive longer.

  2. 95% 失败

    The same configuration or network problem persists; the error will reappear shortly after restart.

  3. 70% 失败

    This prevents connection reuse, causing new connections for every operation, which increases latency and may exhaust server resources.