{"id":"7d1fc1f639ca5ef5","repo":"mongodb/node-mongodb-native","slug":"connectionpool-clear-called-in-load-balanced-mod","errorCode":null,"errorMessage":"ConnectionPool.clear() called in load balanced mode with no serviceId.","messagePattern":"ConnectionPool\\.clear\\(\\) called in load balanced mode with no serviceId\\.","errorType":"exception","errorClass":"MongoRuntimeError","httpStatus":null,"severity":"error","filePath":"src/cmap/connection_pool.ts","lineNumber":426,"sourceCode":"    queueMicrotask(() => this.processWaitQueue());\n  }\n\n  /**\n   * Clear the pool\n   *\n   * Pool reset is handled by incrementing the pool's generation count. Any existing connection of a\n   * previous generation will eventually be pruned during subsequent checkouts.\n   */\n  clear(options: { serviceId?: ObjectId; interruptInUseConnections?: boolean } = {}): void {\n    if (this.closed) {\n      return;\n    }\n\n    // handle load balanced case\n    if (this.loadBalanced) {\n      const { serviceId } = options;\n      if (!serviceId) {\n        throw new MongoRuntimeError(\n          'ConnectionPool.clear() called in load balanced mode with no serviceId.'\n        );\n      }\n      const sid = serviceId.toHexString();\n      const generation = this.serviceGenerations.get(sid);\n      // Only need to worry if the generation exists, since it should\n      // always be there but typescript needs the check.\n      if (generation == null) {\n        throw new MongoRuntimeError('Service generations are required in load balancer mode.');\n      } else {\n        // Increment the generation for the service id.\n        this.serviceGenerations.set(sid, generation + 1);\n      }\n      this.emitAndLog(\n        ConnectionPool.CONNECTION_POOL_CLEARED,\n        new ConnectionPoolClearedEvent(this, { serviceId })\n      );\n      return;","sourceCodeStart":408,"sourceCodeEnd":444,"githubUrl":"https://github.com/mongodb/node-mongodb-native/blob/3366c21a6311e02f1be91da982f9b93d3cce99a0/src/cmap/connection_pool.ts#L408-L444","documentation":"Thrown by ConnectionPool.clear() when the pool is in load-balanced mode (loadBalanced=true) but no serviceId was supplied. In load-balanced topology the driver tracks a separate generation per service (mongos) id, so clearing the pool must identify which service's connections to invalidate. The absence of a serviceId is an internal-driver invariant violation, not something a typical application triggers directly. It surfaces as a MongoRuntimeError during SDAM pool-clear handling (e.g. after a network error or pool staleness event).","triggerScenarios":"The driver's SDAM layer calls pool.clear({ serviceId }) after events like a network error, server description change, or staleness in a load-balanced deployment. If the code path that invokes clear() omits serviceId while loadBalanced is true, this throws. This is almost exclusively hit when connecting with loadBalanced: true against a load balancer fronting mongos instances, and an internal call site fails to propagate the serviceId from the server's hello response.","commonSituations":"Using the driver behind a Layer-4 load balancer (loadBalanced: true in MongoClientOptions) where the server hello's serviceId was not captured or was dropped by a custom SDAM integration. Encountered after upgrading the driver across versions that changed how serviceId is threaded through clear().-proxy or connection-pool instrumentation that wraps or replaces pool.clear() without forwarding serviceId. Never seen on replica set or standalone topologies.","solutions":["Ensure you are on a current driver patch version; if serviceId propagation is broken it is a driver bug that is fixed in releases, so upgrade `mongodb` and retry.","Verify the deployment is genuinely a load-balanced topology (mongos behind an L4 LB) and that the connection string uses loadBalanced=true only in that case; mismatched topology + flag can confuse SDAM.","If you have custom SDAM instrumentation or a proxy that intercepts clear(), make sure it forwards the serviceId option from ConnectionPoolClearedEvent / server description.","If reproducible, file a driver bug with the connection string (redacted), driver version, server version, and SDAM logging enabled (MONGODB_LOGGING=debug)."],"exampleFix":"// before (incorrect topology flag for a replica set)\nconst client = new MongoClient(uri, { loadBalanced: true }); // wrong for RS\n\n// after - only use loadBalanced behind an L4 LB fronting mongos\nconst client = new MongoClient(uri); // RS/standalone: omit the flag","handlingStrategy":"try-catch","validationCode":null,"typeGuard":null,"tryCatchPattern":"// This is an internal driver invariant in load-balanced mode; callers cannot validate it.\n// Wrap pool-sensitive operations and recycle the client on a persistent MongoRuntimeError.\ntry {\n  await collection.findOne(filter);\n} catch (err) {\n  if (err instanceof MongoRuntimeError && /load balanced mode with no serviceId/.test(err.message)) {\n    // recycle client to reset SDAM/pool state\n    await client.close();\n    client = new MongoClient(uri, { loadBalanced: true });\n  }\n  throw err;\n}","preventionTips":["Only set loadBalanced: true when connecting through an L4 load balancer to mongos.","Keep the driver on current patch versions that fix serviceId propagation in SDAM.","Avoid custom SDAM instrumentation that wraps or replaces pool.clear()."],"tags":["load-balancer","connection-pool","sdam","internal"],"analyzedSha":"3366c21a6311e02f1be91da982f9b93d3cce99a0","analyzedAt":"2026-08-04T13:40:15.335Z","schemaVersion":2}