Production MongoDB
Replica Sets
Primary, secondaries, elections and failover — the unit of high availability.
Production MongoDB is a replica set, not a lone mongod. One primary takes writes. Secondaries copy the oplog. If the primary dies, the remaining voting members elect a new one. Your driver talks to the set (mongodb+srv://… or replicaSet=), not to a single hostname you hope never reboots.
- 01App + driver
- 02Primary (writes)
- 03Secondary
- 04Secondary
- 05Election if primary gone
- Three voting members is the usual minimum — a majority can still elect if one node is down.
- Arbiters vote but hold no data. They exist to make an odd count cheap; they are a last resort, not a design.
- Hidden / delayed secondaries are for analytics or delayed copies, not for your API's read-after-write.
- Oplog is a capped history of writes. Too small and a secondary (or a restore) cannot catch up.
Failover is automatic and not instant — seconds, not milliseconds. In-flight writes without majority ack can vanish (next lesson). Multi-document transactions require a replica set. Atlas is a replica set (or a sharded cluster of them) you did not SSH into. You still choose concerns, indexes, and the connection string.
Interview question
What is a MongoDB replica set, and what happens when the primary fails?
A replica set is a primary plus secondaries that replicate via the oplog. Writes go to the primary. If it fails, remaining voting members elect a new primary. The driver follows the set, not a single host. Three voting members is the usual minimum so a majority still exists after one failure.