{"record":{"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/dce7939f86fb283e167ad709955abedb7bf23124/src/sdam/topology.ts#L642-L678","documentation":"Thrown by the server-selection loop in Topology.selectServer when CSOT (Client-Side Operation Timeout) is enabled and no server matching the read preference becomes available before the timeout expires. It is a MongoOperationTimeoutError whose `cause` is a MongoServerSelectionError, so it surfaces the underlying selection failure while respecting the CSOT contract. Without CSOT the driver instead throws the bare MongoServerSelectionError.","triggerScenarios":"Any operation run on a MongoClient where `timeoutMS` (per-call or client-wide) is set and `selectServer` cannot find a usable server within that window: e.g. `collection.findOne({}, { timeoutMS: 500 })` while the cluster is unreachable, or a `withTransaction(..., { timeoutMS: 1000 })` whose first operation cannot pin a server.","commonSituations":"Network partition or firewall blocking the MongoDB port; replica set down or in the middle of an election with no primary for the read preference; wrong host/port in the connection string; TLS handshake failing; the `serverSelectionTimeoutMS` being overridden by a small `timeoutMS`. Common when migrating to per-operation timeouts (CSOT) introduced in driver v6.","solutions":["Verify the cluster is reachable from the host: connect with `mongosh` using the same URI, or run `nc -vz <host> <port>`.","Increase `timeoutMS` for the operation, or remove it so the default `serverSelectionTimeoutMS` (usually 30s) applies.","Check the read preference: a `secondaryPreferred`/`nearest` call against a single-node standalone will never match; use `primary`.","Inspect driver SDAM logs (set `mongodb:DEBUG`) to see the server descriptions and errors reported by heartbeats.","Confirm TLS/auth credentials in the URI match the server, since failed handshakes leave the server Unknown and unselectable."],"exampleFix":"// before\nawait client.db('app').collection('c').findOne({}, { timeoutMS: 200 });\n\n// after: give selection a realistic window, or fall back to the default\nawait client.db('app').collection('c').findOne({}, { timeoutMS: 5000 });","handlingStrategy":"try-catch","validationCode":"// Before opening the client, sanity-check reachability of the first seed.\nimport { MongoClient } from 'mongodb';\n\nasync function reachable(uri, ms = 2000) {\n  const c = new MongoClient(uri, { serverSelectionTimeoutMS: ms });\n  try {\n    await c.db('admin').command({ ping: 1 });\n    return true;\n  } catch {\n    return false;\n  } finally {\n    await c.close();\n  }\n}\n\nif (!(await reachable(uri))) throw new Error('cluster unreachable');","typeGuard":null,"tryCatchPattern":"try {\n  await collection.findOne({}, { timeoutMS });\n} catch (err) {\n  if (err.name === 'MongoOperationTimeoutError' || err.name === 'MongoServerSelectionError') {\n    // log SDAM state, alert, fall back, or rethrow with context\n    logger.error('cannot reach a suitable server', { cause: err.cause });\n    throw err;\n  }\n  throw err;\n}","preventionTips":["Set realistic `timeoutMS`/`serverSelectionTimeoutMS` based on your network RTT.","Wire SDAM monitoring (`client.on('topologyDescriptionChanged', ...)`) to alert before selection fails.","Keep the connection string's seed list current with the replica-set membership.","Run health pings on a schedule, not only at request time."],"tags":["server-selection","timeout","csot","network","sdam"],"backgroundTag":null,"analyzedSha":"dce7939f86fb283e167ad709955abedb7bf23124","analyzedAt":"2026-08-11T04:54:53.215Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}