Skip to content

Production MongoDB

Replica Sets

Primary, secondaries, elections and failover — the unit of high availability.

IntermediateAbout 6 minutes

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.

  1. 01App + driver
  2. 02Primary (writes)
  3. 03Secondary
  4. 04Secondary
  5. 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?

Think about it first.