A replica set is primary + secondaries for redundancy and read scaling. Oplog replays operations to secondaries.
Roles
- Primary — accepts writes
- Secondary — replicates, can serve reads with readPreference
- Arbiter — voting only, no data (legacy layouts)
Read preference
// Driver concept:
// readPreference: 'secondaryPreferred' for analytics readsPractice: Concepts apply to Atlas and self-hosted; try read-only commands in mongosh where safe.
Failover
Election picks new primary on failure—apps must handle brief write errors and retry.
Change streams (on replica sets)
const cs = db.orders.watch()
// Apps consume insert/update/delete events; store resume tokens after restartsChange streams tail the oplog—use for cache invalidation, search sync, or integrations instead of polling updatedAt.
Practice: Concepts apply to Atlas and self-hosted; try read-only commands in mongosh where safe.
Important interview questions and answers
- Q: Oplog?
A: Capped collection of operations secondaries tail for replication. - Q: Change streams vs polling?
A: Lower latency event delivery with resume tokens vs repeated find queries.
Self-check
- Which node accepts writes?
- Why store a resume token?
Tip: readPreference secondary for analytics; primary for read-your-writes. Persist change-stream resume tokens.
Interview prep
- Primary role?
- Accepts writes; secondaries replicate oplog.
- readPreference?
- Chooses which member serves reads.