Replication Workflow
Replication is how MongoDB delivers high availability and durability.
Introduction
Replication is how MongoDB delivers high availability and durability. A replica set is a group of mongod processes that maintain the same data: one primary accepts writes, multiple secondaries stream them via the oplog, and an optional arbiter votes in elections without holding data.
If the primary dies, the secondaries hold an election and a new primary is chosen in seconds — clients reconnect automatically. Replication is mandatory in production; running a single mongod is a disaster waiting for the next reboot.
Understanding the topic
How the replication workflow runs:
- Oplog — capped collection on the primary recording every write as an idempotent operation.
- Tail & apply — secondaries tail the oplog asynchronously and replay operations.
- Heartbeat — members ping every 2s; missed heartbeats trigger an election.
- Election — Raft-based consensus picks the most up-to-date member with majority votes.
- Write concerns —
w: "majority"waits for replication before acknowledging the client. - Read preferences —
primary,secondary,nearestroute reads where they make sense.
Syntax reference
Topology of a typical 3-node replica set:
┌─────────────┐ writesclients ─┤ PRIMARY │◄──────────── app└─────┬───────┘│ oplog stream (async)┌──────┴──────┐▼ ▼┌─────────┐ ┌─────────┐│SECONDARY│ │SECONDARY│ ← analytics reads└─────────┘ └─────────┘• heartbeats every 2 s• election quorum = majority (2 of 3)• failover typically completes in 10–12 s
Informative example
Initiating a self-hosted replica set:
// On each node start mongod with --replSet rs0// Connect to one and initiate:rs.initiate({_id: "rs0",members: [{ _id: 0, host: "mongo-a:27017", priority: 2 },{ _id: 1, host: "mongo-b:27017", priority: 1 },{ _id: 2, host: "mongo-c:27017", priority: 1 }]});rs.status(); // verify PRIMARY + 2 SECONDARYrs.conf(); // election priorities, hidden members, tags
Real-world use
Atlas always provisions a 3-node replica set behind every cluster — even the free tier. Production teams typically run 3 data-bearing nodes in 3 availability zones plus a hidden analytics node tagged for BI tools.
Best practices
- Always use an odd number of voting members (3, 5, 7) to avoid split-brain.
- Spread members across different availability zones — same-AZ replica sets fail together.
- Default writes to
w: "majority"and reads toreadConcern: "majority"for durable consistency. - Avoid arbiters in 3-node sets — replace with a data-bearing node for stronger durability.
Common mistakes
- Long-running operations on the primary can block oplog application on secondaries — watch
rs.printSecondaryReplicationInfo(). - Letting an oplog window shrink below 24h — a slow secondary will need a full resync.
- Reading from a secondary with default read concern — you may see stale data.