Read Preference Use Cases¶
Read Preference Modes¶
Read Preference Mode
Operations read from a random eligible replica set member, irrespective of whether that member is a primary or secondary, based on a specified latency threshold. The operation considers the following when calculating latency:
Indications to Use Non-Primary Read Preference¶
The following are common use cases for using non-
read preference modes:
Running systems operations that do not affect the front-end application.
Providing local reads for geographically distributed applications.
If you have application servers in multiple data centers, you may consider having a geographically distributed replica set and using a non primary or
nearestread preference. This allows the client to read from the lowest-latency members, rather than always reading from the primary.
Maintaining availability during a failover.
primaryPreferredif you want an application to read from the primary under normal circumstances, but to allow stale reads from secondaries when the primary is unavailable. This provides a "read-only mode" for your application during a failover.
Counter-Indications for Non-Primary Read Preference¶
- All members of a replica have roughly equivalent write traffic; as a result, secondaries will service reads at roughly the same rate as the primary.
Replication is asynchronous and there is some amount of delay between a successful write operation and its replication to secondaries. Reading from a secondary can return stale data; reading from different secondaries may result in non-monotonic reads.
Changed in version 3.6: Starting in MongoDB 3.6, clients can use Client Sessions and Causal Consistency Guarantees to ensure monotonic reads.
- Distributing read operations to secondaries can compromise availability if any members of the set become unavailable because the remaining members of the set will need to be able to handle all application requests.
Sharding increases read and write capacity by distributing read and write operations across a group of machines, and is often a better strategy for adding capacity.
See Server Selection Algorithm for more information about the internal application of read preferences.
To avoid stale reads, use
primary read preference and
readConcern. If the primary is
unavailable, e.g. during elections or when a majority of the replica
set is not accessible, read operations using
preference produce an error or throw an exception.
In some circumstances, it may be possible for a replica set to
temporarily have two primaries; however, only one primary will be
capable of confirming writes with the
- A partial network partition may segregate a primary (