{"id":"352a2a9ab730887a","repo":"mongodb/node-mongodb-native","slug":"service-generations-are-required-in-load-balancer","errorCode":null,"errorMessage":"Service generations are required in load balancer mode.","messagePattern":"Service generations are required in load balancer mode\\.","errorType":"exception","errorClass":"MongoRuntimeError","httpStatus":null,"severity":"error","filePath":"src/cmap/connection_pool.ts","lineNumber":435,"sourceCode":"  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;\n    }\n    // handle non load-balanced case\n    const interruptInUseConnections = options.interruptInUseConnections ?? false;\n    const oldGeneration = this.generation;\n    this.generation += 1;\n    const alreadyPaused = this.poolState === PoolState.paused;\n    this.poolState = PoolState.paused;\n\n    this.clearMinPoolSizeTimer();","sourceCodeStart":417,"sourceCodeEnd":453,"githubUrl":"https://github.com/mongodb/node-mongodb-native/blob/3366c21a6311e02f1be91da982f9b93d3cce99a0/src/cmap/connection_pool.ts#L417-L453","documentation":"Thrown in load-balancer mode after a valid serviceId is supplied to ConnectionPool.clear(), but no generation counter is registered for that service id in the pool's serviceGenerations map. The pool keeps a per-service generation number to invalidate stale connections; finding none means the service was never registered (or was deregistered) before a clear was attempted. This is an internal driver-state inconsistency surfaced as MongoRuntimeError. It indicates the pool's bookkeeping and SDAM's view of available services have diverged.","triggerScenarios":"pool.clear({ serviceId }) is called with a serviceId that the pool has never seen (serviceGenerations.has(sid) === false). Happens if a server description's serviceId differs from what was recorded at connection/hello time, e.g. the load balancer rotated to a backend whose serviceId was not yet registered, or the pool was cleared for a stale/unknown service after a topology change. Internal call path, not user-invoked.","commonSituations":"Load-balanced deployments where the set of backing mongos service ids changes (autoscaling, LB reconfiguration) faster than the driver registers them. Driver version skew after upgrading across a release that changed service-generation registration timing. Custom monitoring that synthesizes clear() calls with fabricated service ids.","solutions":["Upgrade to the latest driver patch; service-generation registration races are fixed in driver releases, so bumping `mongodb` is the first action.","Confirm the load balancer presents a stable set of mongos backends and that service ids from hello are consistent; flapping backends cause registration divergence.","Restart the MongoClient to reset pool state if the error appears once after an infrastructure change and does not recur.","Report a driver bug with SDAM debug logs if it reproduces on the current version against a stable LB/mongos setup."],"exampleFix":null,"handlingStrategy":"try-catch","validationCode":null,"typeGuard":null,"tryCatchPattern":"// Internal state inconsistency; recycle the client if it persists.\ntry {\n  await db.command({ ping: 1 });\n} catch (err) {\n  if (err instanceof MongoRuntimeError && /Service generations are required/.test(err.message)) {\n    await client.close();\n    client = new MongoClient(uri, { loadBalanced: true });\n    await client.connect();\n  }\n  throw err;\n}","preventionTips":["Use stable load-balancer backends so mongos service ids do not flap.","Upgrade the driver to pick up service-generation registration fixes.","Recycle long-lived MongoClients after infrastructure changes."],"tags":["load-balancer","connection-pool","sdam","internal","state-consistency"],"analyzedSha":"3366c21a6311e02f1be91da982f9b93d3cce99a0","analyzedAt":"2026-08-04T13:40:15.335Z","schemaVersion":2}