MongoDB: Retryable Reads

Rofl Facts
2 min readDec 8, 2023

--

Retryable reads let MongoDB drivers automatically try a certain read operation again in the event that they run into a particular server or network issue.

Prerequisites

Minimum Driver Version

Retryable readings are supported by official MongoDB drivers for MongoDB Server 4.2 and later.

See MongoDB Drivers for additional details about authorised MongoDB drivers.

Minimum Server Version

Only when a driver is connected to MongoDB Server 3.6 or later may it attempt read operations again.

Enabling Retryable Reads

Retryable readings are enabled by default in official MongoDB drivers that are compatible with MongoDB Server 4.2 and later. You can use retryReads=false in the deployment’s connection string to explicitly prevent retryable reads.

Retryable readings are not supported by mongosh.

Retryable Read Operations

Some read operations can be retried using MongoDB drivers. Each method’s general description is cited in the list. Refer to that method’s driver documentation for details on syntax and usage.

Methods — Descriptions

Collection.aggregate, Collection.count, Collection.countDocuments, Collection.distinct, Collection.estimatedDocumentCount,Collection.find, Database.aggregateCRUD API Read Operations

For Collection.aggregate and Database.aggregate Drivers are limited to retrying aggregation pipelines (like $out or $merge) that do not have write stages.

Collection.watch, Database.watch, MongoClient.watchChange Stream Operations

MongoClient.listDatabases, Database.listCollections, Collection.listIndexes Enumeration Operations

GridFS Operations backed by Collection.find (e.g. GridFSBucket.openDownloadStream) — GridFS File Download Operations

Retryable support for other operations, like helper methods or methods that encapsulate a retryable read operation, may be included in MongoDB drivers. In order to ascertain whether a method expressly supports retryable reads, consult the driver documentation.

Unsupported Read Operations

Retryable reads are not supported by the following operations:

  • db.collection.mapReduce()
  • getMore
  • any read command supplied to a database that is general.The runCommand helper does not care whether commands are written or read.

Behavior

Persistent Network Errors

Retryable reads in MongoDB only attempt retrying once. Replica set elections and momentary network issues are addressed by this, but chronic network errors are not.

Failover Period

Before retrying the read operation, the driver selects the server using the initial read preference specified in the read command. The driver returns the first error if it is unable to choose a server for the retry attempt using the original read preference.

Before choosing a server, the drivers wait serverSelectionTimeoutMS milliseconds. When there are no eligible servers left after waiting serverSelectionTimeoutMS, retryable reads do not handle that situation.

--

--