{"record":{"id":"88b48331da9ca49e","repo":"mongodb/node-mongodb-native","slug":"option-maxstalenessseconds-must-be-at-least-ma","errorCode":null,"errorMessage":"Option \"maxStalenessSeconds\" must be at least ${maxStalenessVariance} seconds","messagePattern":"Option \"maxStalenessSeconds\" must be at least (.+?) seconds","errorType":"exception","errorClass":"MongoInvalidArgumentError","httpStatus":null,"severity":"error","filePath":"src/sdam/server_selection.ts","lineNumber":132,"sourceCode":" * @param readPreference - The read preference providing max staleness guidance\n * @param topologyDescription - The topology description\n * @param servers - The list of server descriptions to be reduced\n * @returns The list of servers that satisfy the requirements of max staleness\n */\nfunction maxStalenessReducer(\n  readPreference: ReadPreference,\n  topologyDescription: TopologyDescription,\n  servers: ServerDescription[]\n): ServerDescription[] {\n  if (readPreference.maxStalenessSeconds == null || readPreference.maxStalenessSeconds < 0) {\n    return servers;\n  }\n\n  const maxStaleness = readPreference.maxStalenessSeconds;\n  const maxStalenessVariance =\n    (topologyDescription.heartbeatFrequencyMS + IDLE_WRITE_PERIOD) / 1000;\n  if (maxStaleness < maxStalenessVariance) {\n    throw new MongoInvalidArgumentError(\n      `Option \"maxStalenessSeconds\" must be at least ${maxStalenessVariance} seconds`\n    );\n  }\n\n  if (maxStaleness < SMALLEST_MAX_STALENESS_SECONDS) {\n    throw new MongoInvalidArgumentError(\n      `Option \"maxStalenessSeconds\" must be at least ${SMALLEST_MAX_STALENESS_SECONDS} seconds`\n    );\n  }\n\n  if (topologyDescription.type === TopologyType.ReplicaSetWithPrimary) {\n    const primary: ServerDescription = Array.from(topologyDescription.servers.values()).filter(\n      primaryFilter\n    )[0];\n\n    return servers.filter((server: ServerDescription) => {\n      const stalenessMS =\n        server.lastUpdateTime -","sourceCodeStart":114,"sourceCodeEnd":150,"githubUrl":"https://github.com/mongodb/node-mongodb-native/blob/dce7939f86fb283e167ad709955abedb7bf23124/src/sdam/server_selection.ts#L114-L150","documentation":"Thrown by maxStalenessReducer() (src/sdam/server_selection.ts:132) as MongoInvalidArgumentError when maxStalenessSeconds is below the dynamic staleness variance floor, computed as (heartbeatFrequencyMS + IDLE_WRITE_PERIOD) / 1000. This floor accounts for clock skew and heartbeat latency per the max-staleness spec. The threshold varies with the topology's heartbeat frequency.","triggerScenarios":"Setting maxStalenessSeconds to a small value (e.g. 10-30s) that is below the per-topology variance floor (~heartbeatFrequencyMS/1000 + 10s).","commonSituations":"Aggressive latency requirements leading developers to set very small staleness windows without accounting for heartbeat overhead.","solutions":["Increase maxStalenessSeconds to at least the value in the error message (the computed variance floor).","Use the absolute minimum of 90 seconds (see error 336) as a safe default.","If heartbeatFrequencyMS is high, lower it to reduce the variance floor."],"exampleFix":"// before\nnew ReadPreference('secondary', undefined, { maxStalenessSeconds: 30 });\n// after\nnew ReadPreference('secondary', undefined, { maxStalenessSeconds: 90 });","handlingStrategy":"validation","validationCode":"const IDLE_WRITE_PERIOD = 10;\nfunction safeMaxStaleness(v, heartbeatFrequencyMS = 10000) {\n  const variance = (heartbeatFrequencyMS / 1000) + IDLE_WRITE_PERIOD;\n  if (v < variance) throw new Error(`maxStalenessSeconds must be >= ${variance}`);\n  return v;\n}","typeGuard":"function isAboveVariance(v, heartbeatFrequencyMS = 10000): v is number {\n  return typeof v === 'number' && v >= ((heartbeatFrequencyMS / 1000) + 10);\n}","tryCatchPattern":"try {\n  await collection.findOne({}, { readPreference: new ReadPreference('secondary', undefined, { maxStalenessSeconds }) });\n} catch (e) {\n  if (e instanceof MongoInvalidArgumentError && /maxStalenessSeconds/.test(e.message)) {\n    // bump staleness and retry\n  }\n  throw e;\n}","preventionTips":["Use at least 90 seconds for maxStalenessSeconds to satisfy both the variance and absolute floors.","Account for heartbeatFrequencyMS when tuning the value.","Document the spec-derived floors for your team."],"tags":["read-preference","max-staleness","server-selection","invalid-argument"],"backgroundTag":null,"analyzedSha":"dce7939f86fb283e167ad709955abedb7bf23124","analyzedAt":"2026-08-11T04:54:53.215Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}