All academies
Roadmap
LEVEL 7 · REPLICATION

Replica Sets

12 min read

A replica set is a group of mongod servers holding the same data: one primary accepts all writes, and secondaries replicate them by tailing the primary's oplog (operations log). Watch it live in the replication simulator.

Automatic failover

If the primary becomes unreachable, the remaining members hold an election and vote a secondary into the primary role — typically within seconds. Your driver reconnects automatically. This is why production replica sets have an odd number of voting members (usually 3): a majority is needed to elect.

Write & read concerns

writeConcern controls how many members must acknowledge a write: { w: 1 } primary only, { w: "majority" } survives failover. readPreference controls where reads go: primary (default), secondary, nearest. Reading secondaries can return slightly stale data (replication lag).

mongosh
db.orders.insertOne(
  { item: "book" },
  { writeConcern: { w: "majority" } }
)

Check your understanding

Q1.

How many primaries can a replica set have at once?

Q2.

Why are replica sets usually deployed with 3 (or another odd number of) members?

Q3.

With readPreference: 'secondary', you might read slightly stale data.