Which reads does a MongoDB driver's retryReads retry after a failover, how many times, and what still reaches the application?
answer
- on by default, client level
- first attempt, not the cursor's next batch
- one retry, one fresh selection
- network, not-primary, pool cleared
- transactions opt out
basics
~20 sWith retryReads, on by default, a MongoDB driver retries a supported read once after a retryable error, such as a network error or a not-primary reply. getMore, reads in a transaction and generic runCommand stay outside that policy.
solid answer
~40 s`retryReads` defaults to true in the specification, PyMongo and the Node.js driver, and it is set on the client. It covers the first attempt of `find`, `aggregate` without `$out` or `$merge`, `distinct`, `countDocuments`, `estimatedDocumentCount`, the `watch` helpers and the list commands. After a retryable error, meaning a network error, a listed code such as `NotWritablePrimary`, or a `PoolClearedError`, the driver updates its topology, runs server selection again and retries once. If that selection fails, it raises the earlier error. Outside the policy are `getMore`, because the driver cannot tell whether the cursor advanced, `mapReduce`, a generic `runCommand` helper and any read in a transaction. So a cursor that breaks halfway still reaches the application, which must restart it. Where a driver honours `timeoutMS`, retries repeat until the deadline instead of stopping at one.
go deeper
Recall that retryReads is on by default and that the driver repeats a failed read by itself, once, after errors such as a dropped connection or a not-primary reply.
List what is covered and what is not, and explain why getMore is excluded: the driver cannot know whether the cursor advanced. Describe the fresh server selection that makes one retry enough for an election.
Say what the application must still handle: cursor errors mid-stream, a second failure, and selection timeouts. Point out that socket timeouts count as retryable, so a tight socketTimeoutMS can double the load on a slow member.
Decide what retries mean in your service's latency budget. The hidden second attempt and its selection wait can consume a whole deadline, so agree how long a read may take in total before anyone tunes individual settings.
## What the option is A **retryable read** is a read the driver repeats by itself, without the application doing anything, when the first attempt fails in a way that says nothing about the data. `retryReads` turns this on. The specification requires it to default to true and requires it to be set only on the client, never per database, collection or operation. PyMongo and the Node.js driver both default it to true. The point is failover: a read sent to a primary that has just gone away can succeed on its replacement with no error shown to the user. Which writes `retryWrites` covers is a separate subject with its own rules. ## What is covered | Operation | Retried under `retryReads` | Why | |---|---|---| | `find`, and helpers built on it such as `findOne` | yes | no results received yet | | `aggregate` without a write stage | yes | read-only | | `aggregate` with `$out` or `$merge` | no | it writes | | `distinct`, `countDocuments`, `estimatedDocumentCount` | yes | read-only | | `watch` on a collection, database or client | yes | the opening command only | | `listDatabases`, `listCollections`, `listIndexes` | yes | read-only | | `getMore` on an open cursor | no | the driver cannot tell whether the cursor advanced | | `mapReduce` | no | excluded by the specification | | generic `runCommand` helper | no | the helper does not know what the command does | | any read inside a transaction | no | sent exactly once | The `getMore` case is the one to understand. If the network fails while fetching a batch, the server may already have moved the cursor on, so repeating the request could skip a batch without anyone noticing. Cursors only go forwards, so the driver lets the error through. ## What counts as retryable - Any **network exception**, including a socket timeout. - A server reply with a listed code, such as `NotWritablePrimary`, `PrimarySteppedDown`, `InterruptedDueToReplStateChange`, `ShutdownInProgress` or `ReadConcernMajorityNotAvailableYet`. - A **`PoolClearedError`**, which a driver raises when a pool is cleared while an operation is waiting for a connection or tries to use a paused pool. - Any of those during a connection handshake, including authentication. ## The retry, step by step 1. The driver selects a server. If this first selection fails, the error goes straight to the application, because no attempt was made. 2. It sends the command. A retryable error starts a retry; any other error is raised. 3. It updates its topology following the monitoring rules and keeps the original error. 4. It runs **server selection again**. On a replica set the failed address is not excluded for ordinary errors, so the same member can be chosen if it is still suitable. On a sharded cluster the failed `mongos` is deprioritized. 5. It rebuilds an equivalent command for the selected server and sends it. If selection fails, or the server cannot support the command, it raises the original error. 6. If the second attempt fails too, it raises an error. Without `timeoutMS`, an ordinary retryable error gets no third attempt. One retry is enough for failover because of step 4. Selection may block for up to `serverSelectionTimeoutMS`, which is long enough for a typical election. If no server appears in that time, the specification assumes a lasting outage, where more attempts would waste time. ## What still reaches the application - An error during `getMore`, partway through a long result. The application must start the query again or resume from its last position. - A second failure after the retry, or a selection timeout during the retry. - Errors outside the list, such as a query that is simply invalid. - `MaxTimeMSExpired`, code 50, because that code is not on the list. A socket timeout deserves a thought. Since it counts as a network exception, a read that overruns `socketTimeoutMS` is sent a second time, adding load to a server that may already be slow. ## Two things that change the count - **`timeoutMS`**, in drivers that honour it: the driver keeps retrying until the deadline passes or a non-retryable error comes back. PyMongo honours it, while the Node.js driver 7.8 has made the option a no-op. - **The overload policy**, a separate specification: an error carrying the `SystemOverloadedError` and `RetryableError` labels may be retried with backoff up to `maxAdaptiveRetries`, default 2. It reaches operations that the read policy excludes, such as `getMore`, and it applies only if `retryReads` is enabled for reads.
- Why does the specification retry a read only once by default?Because the retry already includes a fresh server selection, which can wait up to `serverSelectionTimeoutMS`, 30 seconds by default, for a new primary. A transient failure is covered by that wait. If selection still fails, the specification assumes a lasting outage, where further attempts only waste time.
- A read overruns socketTimeoutMS. Does retryReads help or hurt?It can do either. A socket timeout counts as a retryable network exception, so the read is sent once more. If a member was briefly stalled, that rescues the request. If the query is simply slow, it doubles the load on a struggling server and the application waits twice as long before seeing an error.
- How do overload errors change what you have just described?The client backpressure specification adds a separate policy. Errors labelled `SystemOverloadedError` and `RetryableError` may be retried with jittered backoff up to `maxAdaptiveRetries`, default 2, even for `getMore` and `runCommand`, provided the relevant retry option is on. Ordinary network and not-primary errors still follow the retryable-reads rules.
- retryReads is off by default, so you have to enable it for failover to be transparent.
- A retryable read picks up a broken cursor by repeating getMore from where it stopped.
- The retry always goes to a different replica set member than the one that failed.
- You can turn retryReads on for one collection or one query.
- retryReads also repeats reads inside a multi-document transaction.
- With retryReads on and default settings, the driver keeps retrying reads until the failover has finished.