skip to content

During a replica set failover, a MongoDB service with 40 application instances runs out of connections and users see timeouts: what happens inside the driver, and how do you diagnose it?

level: seniorimportance: must knowfreq 52%

answer

  1. first a wait with no pool involved
  2. Unknown server, paused pool
  3. not every primary change clears
  4. a stampede at the new primary
  5. read which error you actually got

basics

~20 s

During a MongoDB failover, requests block in server selection until a new primary is known, then every instance hits an often cold pool limited by maxConnecting, and queue waits with no default limit outlast the application's request timeouts.

solid answer

~40 s

When a primary dies, network errors and failed monitor checks mark it Unknown and clear its pool, which fails queued checkouts with a retryable `PoolClearedError`. New requests block in server selection, for up to `serverSelectionTimeoutMS`, during the election. Once monitoring finds the new primary, that backlog hits its pool, often cold because `minPoolSize` defaults to 0. `maxConnecting`, default 2, gives each of 40 instances two concurrent handshakes, so requests queue well below `maxPoolSize`, and `waitQueueTimeoutMS` has no default limit, so users hit the HTTP timeout first. A clean step-down differs: a not-writable-primary reply marks the server Unknown without clearing its pool. Diagnose from the error type, pool and monitoring events and the server's `connections` counters. Fix with a warm `minPoolSize`, bounded waits and load shedding, not just bigger pools.

code

javascript · 2 lines
javascript
// mongosh, connected to the new primary
db.serverStatus().connections

go deeper

for a junior

Recall that a driver cannot write during an election, so operations wait for a new primary, and that it then has to open new connections to that server. Knowing those two waits is the starting point.

for a middle

Name each stage and its setting: serverSelectionTimeoutMS for the election, maxConnecting and maxPoolSize at the new primary, waitQueueTimeoutMS for checkout. Explain that the defaults allow a checkout wait with no limit.

for a senior

Diagnose from evidence: separate selection errors from checkout errors, use pool and monitoring events for a timeline, and explain which events clear a pool. Show that a clean step-down does not clear it and that raising maxPoolSize can worsen things.

for a principal

Treat failover behaviour as something to test on a schedule. A drill with a planned step-down under real load shows whether the service degrades as designed, and whether the connection budget holds on the new primary.

## The timeline "Ran out of connections" usually describes several waits in a row, and each has a different setting behind it. 1. **The primary fails.** Operations on it see network errors or, in a clean step-down, a state-change reply such as `NotWritablePrimary`. 2. **The driver marks it Unknown.** Its description in the driver's topology no longer says primary, so no server is suitable for writes or primary reads. 3. **Requests wait in server selection.** They request an immediate check and block for up to `serverSelectionTimeoutMS`, 30,000 ms by default. No pool is involved yet, and threads or pending promises pile up here. 4. **The election ends.** A monitor sees the new primary in a `hello` reply, the topology updates, and waiting selections wake together. 5. **The stampede.** All blocked operations now choose one server. Unless it served reads recently or `minPoolSize` is set, its pool is small or empty. Each pool establishes only `maxConnecting` connections at once, so 40 instances mean 80 concurrent TCP, TLS and authentication handshakes, while the rest queue first come, first served. 6. **Users time out.** `waitQueueTimeoutMS` has no default limit and `socketTimeoutMS` means no timeout, so the driver may raise nothing at all. The service's own HTTP deadline fires first, and the pool grows towards 40 x 100 = 4,000 connections on that member. ## How the driver notices Each server has a **monitor** on a dedicated socket, part of the discovery and monitoring specification, known as **SDAM**. With MongoDB 4.4 or later, a multi-threaded or async driver uses the **streaming protocol**: the server pushes a `hello` reply when its state changes, and `heartbeatFrequencyMS`, 10 seconds by default in those drivers, is only the longest gap between replies. So a change is not necessarily seen 10 seconds late. A host that vanishes without closing its sockets cannot push anything, though: there the read times out only after `connectTimeoutMS + heartbeatFrequencyMS`, unless another signal arrives first. On a FaaS platform, the default `serverMonitoringMode` of `auto` falls back to polling. Application errors also trigger immediate checks, at least 500 ms apart. ## What a pool clear does A **pool clear** increments the pool's generation number, which marks every existing connection stale, and moves the pool to the **paused** state. Consequences: - Operations in the wait queue fail at once with a retryable `PoolClearedError` instead of waiting out a timeout. - Stale connections are closed lazily, when checked in or met at checkout, so in-flight operations normally carry on. - In-use connections are interrupted only if a monitor check failed with a network timeout. - The pool opens nothing new until a successful monitor check marks it **ready** again. Not every primary change does this: | What the driver sees | Marks server Unknown | Clears its pool | |---|---|---| | Monitor check fails | yes | yes | | Non-timeout network error on an established connection | yes | yes | | Network timeout on an established connection | no | no | | `NotWritablePrimary`, `PrimarySteppedDown` | yes | no | | `ShutdownInProgress`, `InterruptedAtShutdown` | yes | yes | | Authentication step fails | yes | yes | | Establishment error labelled `SystemOverloadedError` | no | no | A step-down keeps the pool because the connections may still be useful, for secondary reads for example. A member that is shutting down has its pool cleared because those connections will never work again. ## Diagnosing it - **Read the error first.** A server selection error (`ServerSelectionTimeoutError` in PyMongo, `MongoServerSelectionError` in the Node.js driver) means no suitable server was known: look at the election. A wait queue timeout means the chosen server's pool could not serve in time: look at the pool. - **No driver error at all**, only HTTP timeouts, usually means unbounded waits, which is itself a finding. - **Subscribe to events.** `ServerDescriptionChangedEvent` gives the failover's timeline, `PoolClearedEvent` shows clears, and `ConnectionCheckOutFailedEvent` has a `reason` of `timeout` or `connectionError`. - **Check the server.** `connections.current`, `connections.available` and the growth of `connections.totalCreated` in `serverStatus` on the new primary show whether a storm reached it. - **Compare time spent.** If checkouts queue while the pool is far below `maxPoolSize`, `maxConnecting` is the limit, not the pool size. ## Fixing it - Set `minPoolSize` so that secondaries stay warm, and budget for it: 40 x 10 x 3 is 1,200 connections. - Lower `serverSelectionTimeoutMS` to fit the request budget, and bound checkout with `waitQueueTimeoutMS` or `timeoutMS` where the driver honours it. - Shed load in the service while the primary is missing, because retries from callers make the stampede larger. - Raise `maxConnecting` with care: the manual warns that it connects faster but risks connection storms. - Do not simply raise `maxPoolSize`. It raises the ceiling on the new primary at the worst moment. - On 8.2 and later, `ingressConnectionEstablishmentRateLimiterEnabled`, default `false`, lets the server limit new connections per second.

  • Why does a driver keep the pool after a not-writable-primary reply but clear it when the node is shutting down?
    A not-writable-primary reply means the server is up and the driver was wrong about its role, so the connections may still serve secondary reads. A shutting-down server will close its connections and return errors until then, so those connections can never be used again. The specification therefore clears only for codes 11600 and 91.
  • After the old primary comes back as a secondary, when can operations use its pool again?
    When a monitor completes a successful check. If its pool was cleared, it stayed paused, and any checkout failed fast with a retryable error rather than opening connections to a member that might still be down. A successful check marks the pool ready and updates the topology together, so the server cannot be selected while still paused.
  • Why can raising maxPoolSize from 100 to 500 make the next failover worse?
    All 40 instances may now open up to 500 connections each on the new primary, 20,000 in total, while it is starting to take writes. That costs memory and handshake work at the worst moment and can push it towards `net.maxIncomingConnections`. If the queue was at `maxConnecting`, the pool size was not even the limit.
  • How do server overload labels change what the pool does?
    Under the current specification, a network error or timeout during connection establishment or `hello` gets the `SystemOverloadedError` and `RetryableError` labels, and the driver then does not clear the pool or mark the server Unknown. An overloaded server is therefore not treated as a dead one. Errors in the later authentication step still clear the pool.

  • Any primary change clears the connection pool on every client.
  • A pool clear immediately closes every socket and kills in-flight operations.
  • The driver can only notice a new primary after a full heartbeatFrequencyMS interval.
  • Timeouts during a failover prove maxPoolSize is too small, so double it.
  • A server selection timeout means the connection pool ran out of connections.
  • By default a saturated pool raises an error within a few seconds.

Assumes MongoDB 9.0; ingressConnectionEstablishmentRateLimiterEnabled exists since 8.2, also in 8.1.1 and 8.0.12, and streaming monitors need 4.4 or later, so 8.0 and 9.0 behave alike here.