症状
在负载下驱动报出 Timed out while waiting for a connection 或服务器选择错误。流量下降后即恢复,说明是连接池容量或泄漏问题。
诊断
观察连接池事件并结合并发评估容量:
const client = new MongoClient(uri, {
maxPoolSize: 50,
waitQueueTimeoutMS: 5000,
});
client.on('connectionPoolCreated', (e) => console.log(e));
若等待者始终多于空闲连接,说明池过小或连接被占用未释放。
修复
调整池容量并及时释放资源:
const cursor = coll.find({});
for await (const doc of cursor) { /* ... */ }
await cursor.close(); // return the connection
await session.endSession(); // close sessions
保持 maxPoolSize × 实例数 的总和低于服务器上限。
验证
重跑压测;连接池统计显示连接在回收,等待队列超时消失,延迟保持稳定而不再先升后崩。