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.
Horizontal Sharding, mongos Router & Chunk Balancer
Observe mongos single-shard routing vs scatter-gather queries and automatic chunk migration across replica sets.
Stateless routing daemon. Caches routing table from Config DB. Clients connect directly to mongos on port 27017.
Stores cluster catalog, database mappings, and chunk range boundaries in config.chunks with two-phase commit lock.
Background round-robin process. Triggers migration when chunk difference between shards exceeds the migration threshold.
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.
{
"mode": "secondaryPreferred",
"tagSets": [
{
"datacenter": "east-reporting"
}
]
}Reports run against dedicated reporting secondaries, keeping the primary 100% dedicated to client writes.
4. MQL Implementation Steps
db.orders.find().readPref("secondaryPreferred");db.orders.find().readPref("nearest", [
{ "region": "us-east", "purpose": "analytics" }
]);5. Critical Engineering Rules
| Rule / Constraint | Underlying Reason & Impact |
|---|---|
| primary (Default) | Guarantees strictly fresh data (Read-Your-Own-Writes consistency). |
| secondary / secondaryPreferred | Subject to Replication Lag: clients may read stale data. |
| nearest | Measures 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
7. Architectural Trade-offs
- •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
- •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
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?