Skip to content
LESSON 46 / 50Intermediatedistributed

Read Preferences: primary vs secondaryPreferred vs nearest

Read Preferences dictate how database client drivers route read operations across members of a replica set: balancing read scalability against data staleness.

Interactive Engine Simulator

Horizontal Sharding, mongos Router & Chunk Balancer

Observe mongos single-shard routing vs scatter-gather queries and automatic chunk migration across replica sets.

mongos Query Router

Stateless routing daemon. Caches routing table from Config DB. Clients connect directly to mongos on port 27017.

Config Replica Set (CSRS)

Stores cluster catalog, database mappings, and chunk range boundaries in config.chunks with two-phase commit lock.

Chunk Balancer

Background round-robin process. Triggers migration when chunk difference between shards exceeds the migration threshold.

Shard 01 (Replica Set: rs-shard-01)3 Chunks
chunk-1Range: [MinKey .. 1000)
450 docs
chunk-2Range: [1000 .. 2000)
820 docs
chunk-3Range: [2000 .. 3000)
610 docs
Shard 02 (Replica Set: rs-shard-02)1 Chunks
chunk-4Range: [3000 .. MaxKey)
390 docs
MONGOS_LOG:Cluster balanced across 2 shards. Shard key: { user_id: 1 }.

1. Formal Definition & Architecture Intent

Read Preference determines which replica set member a client driver directs read queries to. The five modes are: "primary" (default: reads strictly from Primary), "primaryPreferred" (reads Primary; falls back to Secondary if down), "secondary" (reads strictly from Secondaries), "secondaryPreferred" (reads Secondary; falls back to Primary), and "nearest" (reads node with lowest network latency).

2. Explain Like I'm 5 (Mental Model)

When asking a question: "primary" is insisting on asking only the manager. "secondary" is only asking the clerk. "nearest" is asking whoever is standing closest to you in the room.

3. Real-World Architecture Example

Routing heavy reporting queries to secondaries to avoid CPU contention on the primary.

Sample BSON Documents:
Collection: db.analytics_report
{
  "mode": "secondaryPreferred",
  "tagSets": [
    {
      "datacenter": "east-reporting"
    }
  ]
}

Reports run against dedicated reporting secondaries, keeping the primary 100% dedicated to client writes.

4. MQL Implementation Steps

Step 1: Set read preference in mongosh connection string or query
db.orders.find().readPref("secondaryPreferred");
Routes query to a secondary; falls back to primary if no secondaries are reachable.
Step 2: Target specific secondary nodes using tag sets
db.orders.find().readPref("nearest", [
  { "region": "us-east", "purpose": "analytics" }
]);
Driver routes to the lowest-latency member matching tag criteria.

5. Critical Engineering Rules

Rule / ConstraintUnderlying Reason & Impact
primary (Default)Guarantees strictly fresh data (Read-Your-Own-Writes consistency).
secondary / secondaryPreferredSubject to Replication Lag: clients may read stale data.
nearestMeasures ping latency (within a 15ms localThreshold window); optimal for geographically distributed read caching.

6. Deep Dive: The Read-Your-Own-Writes Consistency Trap

A classic bug occurs when a user updates their profile (written to Primary) and is immediately redirected to their profile page. If the web server queries with readPreference: "secondaryPreferred", and the secondary has 200ms of replication lag, the user sees their OLD profile and files a bug ticket! Solution: Route all user-facing post-mutation reads to the Primary, or use Causal Consistency sessions.

// Driver URI read preference configuration:
// mongodb://node1,node2,node3/?replicaSet=rs0&readPreference=secondaryPreferred&maxStalenessSeconds=120
Production Warning: Never use secondary read preferences for financial or transactional validation workflows.

7. Architectural Trade-offs

Advantages
  • •Scales read throughput across multiple secondary servers without beefing up primary hardware
  • •Tag sets allow isolating analytical workloads to dedicated non-voting reporting members
  • •nearest mode minimizes global network latency for geo-distributed read workloads
Disadvantages & Gotchas
  • •Secondaries can serve stale data due to asynchronous replication lag
  • •Does not scale write throughput (all writes must still go to the Primary)

8. Technical Interview Questions

Q1: What is the primary risk of configuring readPreference: "secondary" for application reads?

The primary risk is reading stale or out-of-date data caused by asynchronous replication lag. If a user performs a write and immediately executes a read routed to a lagging secondary, they will observe outdated data ("Read-Your-Own-Writes" inconsistency).

9. Staff-Level Ready Answer

"Read Preferences control client query routing: "primary" guarantees fresh reads; "secondary" / "secondaryPreferred" offload read queries to secondaries at the expense of replication lag staleness; "nearest" routes to the member with lowest network round-trip time. Tag sets allow targeting specific nodes (e.g. analytics)."

10. Quick Knowledge Check

Which Read Preference mode routes queries to the replica set member with the lowest network ping latency?