{"id":"4fdb2fbfb25d235d","repo":"mongodb/node-mongodb-native","slug":"timed-out-during-server-selection","errorCode":null,"errorMessage":"Timed out during server selection","messagePattern":"Timed out during server selection","errorType":"exception","errorClass":"MongoOperationTimeoutError","httpStatus":null,"severity":"error","filePath":"src/sdam/topology.ts","lineNumber":660,"sourceCode":"        if (\n          this.client.mongoLogger?.willLog(\n            MongoLoggableComponent.SERVER_SELECTION,\n            SeverityLevel.DEBUG\n          )\n        ) {\n          this.client.mongoLogger?.debug(\n            MongoLoggableComponent.SERVER_SELECTION,\n            new ServerSelectionFailedEvent(\n              selector,\n              this.description,\n              timeoutError,\n              options.operationName\n            )\n          );\n        }\n\n        if (options.timeoutContext?.csotEnabled()) {\n          throw new MongoOperationTimeoutError('Timed out during server selection', {\n            cause: timeoutError\n          });\n        }\n        throw timeoutError;\n      }\n      // Other server selection error\n      throw error;\n    } finally {\n      abortListener?.[kDispose]();\n      if (!options.timeoutContext || options.timeoutContext.clearServerSelectionTimeout) {\n        timeout?.clear();\n      }\n    }\n  }\n  /**\n   * Update the internal TopologyDescription with a ServerDescription\n   *\n   * @param serverDescription - The server to update in the internal list of server descriptions","sourceCodeStart":642,"sourceCodeEnd":678,"githubUrl":"https://github.com/mongodb/node-mongodb-native/blob/3366c21a6311e02f1be91da982f9b93d3cce99a0/src/sdam/topology.ts#L642-L678","documentation":"Thrown when CSOT (Client-Side Operation Timeout, `timeoutMS`) is enabled and server selection cannot find a suitable server within the operation's remaining time budget; it wraps the underlying `MongoServerSelectionError` as the cause (topology.ts:659). It signals that no server matching the read preference / write requirements became available before the deadline.","triggerScenarios":"An operation with `timeoutMS` set runs while the cluster is unreachable, has no primary (for writes), or has no secondaries (for secondary reads); network partition; all matching servers are deprioritized or unknown.","commonSituations":"Replica set with no elected primary during failover; secondary read preference but only a primary exists; firewall/DNS blocking the hosts; load-balanced mode with no ready service nodes; timeoutMS too small for a slow-starting cluster.","solutions":["Verify cluster connectivity and health (mongosh, network, DNS) and wait out any failover.","Ensure a server exists for your read preference (use 'primary'/'primaryPreferred' if only a primary is available).","Raise `timeoutMS` / `serverSelectionTimeoutMS` to survive transient outages.","Confirm the hosts in the connection string are reachable and not firewalled."],"exampleFix":"// before\nconst client = new MongoClient(uri, { timeoutMS: 1000 });\n// after\nconst client = new MongoClient(uri, { timeoutMS: 30000 });","handlingStrategy":"retry","validationCode":null,"typeGuard":null,"tryCatchPattern":"try {\n  await coll.insertOne(doc, { timeoutMS: 5000 });\n} catch (e) {\n  if (e instanceof MongoOperationTimeoutError && /server selection/i.test(e.message)) {\n    await new Promise(r => setTimeout(r, 1000));\n    return retry();\n  }\n  throw e;\n}","preventionTips":["Set a timeoutMS/serverSelectionTimeoutMS large enough to survive failover (>= 10s).","Use a read preference that matches available servers during incidents.","Monitor cluster health and trigger failover-aware retries.","Verify DNS/firewall reachability of all hosts before deploying."],"tags":["server-selection","timeout","network","csot"],"analyzedSha":"3366c21a6311e02f1be91da982f9b93d3cce99a0","analyzedAt":"2026-08-04T13:40:15.335Z","schemaVersion":2}