Production MongoDB
Read Preference, Write Concern, Read Concern
Where a read goes, how many nodes must ack a write, and what 'majority' actually means.
Three knobs people mix up. Write concern — how many replica set members must ack the write before the driver reports success. Read preference — which members are allowed to serve the read. Read concern — how committed the data you read must be (local vs majority vs snapshot).
await orders.insertOne(doc, { writeConcern: { w: "majority", wtimeout: 5000 } })
await orders.find({ userId }).toArray() // default: primary, readConcern local| Knob | Typical choice |
|---|---|
| w: 1 | Primary has it. Fast. Can be rolled back on failover |
| w: "majority" | Majority of voting members. Default on modern servers. The interview answer for durability |
| w: 0 | Unacknowledged. Not for user checkout |
| readPreference: primary | Read-after-write (Rahul just placed an order) |
| readPreference: secondary | Stale OK — reports, not the confirmation page |
| readConcern: majority | You only see majority-committed data; pairs with majority writes |
Replication is asynchronous. A secondary read can miss the write you just got w: 1 for. Causal sessions (driver) make 'read your writes' work across concerns if you opt in — do not assume it. Transaction snapshot isolation is read concern snapshot inside the txn. j: true waits for journal; with majority you already care about committed replica data more than this flag in interviews.
Interview question
What do write concern and read preference control?
Write concern is how many replica set members must acknowledge a write before it is success — w:1 is primary only and can be lost on failover; w:'majority' survives that. Read preference is which members may serve reads. Secondaries add capacity but replication is async, so they are wrong for read-after-write. Read concern is a third knob: how committed the data you read must be.