MongoDBReplication

Replication

A replica set is a group of MongoDB servers maintaining the same dataset. It provides redundancy, high availability, and automatic failover — making it the foundation of every production MongoDB deployment. Never run MongoDB in production as a standalone single node.

Replica Set Architecture

Role

Holds Data

Accepts Writes

Votes for Primary

Primary

Yes

Yes (all writes go here)

Yes

Secondary

Yes

Read-only (with read preference)

Yes

Arbiter

No

No

Yes

How Replication Works
  1. A client write lands on the primary

  2. The primary records the operation in the oplog (a capped, ordered operations log)

  3. Each secondary tails the primary oplog and replays operations in order

  4. Secondaries reach eventual consistency — typical replication lag is milliseconds

Automatic Failover

If the primary becomes unavailable, the remaining secondaries detect the absence through heartbeat timeouts and hold an election. The secondary with the most up-to-date oplog and the highest configured priority wins and becomes the new primary. Failover typically completes in 10–30 seconds.

Note
During an election the cluster briefly accepts no writes. Design applications to catch NotPrimaryError and retry the operation once the new primary is elected.
Setting Up a Replica Set

Bash
# Start 3 mongod instances with the same replica set name
mongod --replSet rs0 --port 27017 --dbpath /data/rs0-0 --bind_ip localhost
mongod --replSet rs0 --port 27018 --dbpath /data/rs0-1 --bind_ip localhost
mongod --replSet rs0 --port 27019 --dbpath /data/rs0-2 --bind_ip localhost

JS
// Connect to the first instance and initialize the set
// mongosh --port 27017

rs.initiate({
  _id: "rs0",
  members: [
    { _id: 0, host: "localhost:27017", priority: 2 },  // preferred primary
    { _id: 1, host: "localhost:27018", priority: 1 },
    { _id: 2, host: "localhost:27019", priority: 1 }
  ]
})
Replica Set Status

JS
// Full replica set status — shows each member's state, health, and optime
rs.status()

// Quick check — is this node the primary?
rs.isMaster()

// Oplog size and time range on the primary
rs.printReplicationInfo()

// Replication lag on each secondary
rs.printSecondaryReplicationInfo()
Read Preferences

Read Preference

Description

Use Case

primary

All reads from the primary

Strong consistency required

primaryPreferred

Primary if available, else secondary

Mostly consistent, some tolerance

secondary

Always read from a secondary

Analytics / reporting workloads

secondaryPreferred

Secondary if available, else primary

Distribute read load

nearest

Node with lowest network latency

Geo-distributed applications

Write Concerns

JS
// w:1 — primary acknowledges the write (default, fastest)
db.orders.insertOne(doc, { writeConcern: { w: 1 } })

// w:'majority' — quorum of members acknowledges (recommended for production)
db.orders.insertOne(doc, { writeConcern: { w: 'majority', wtimeout: 5000 } })

// j:true — write must be committed to the journal before acknowledgment
db.criticalData.insertOne(doc, { writeConcern: { w: 'majority', j: true } })

majority is the recommended production write concern. It guarantees the write survives the loss of any single node (including the primary) because a majority of the set has it.

Atlas Replication

MongoDB Atlas manages replica sets automatically. M10+ dedicated clusters are deployed as 3-node replica sets. Atlas performs rolling maintenance — upgrading one node at a time — so the cluster stays available during version upgrades and security patches. You never need to run rs.initiate() or manage oplog sizing yourself.

Tip
Always deploy with at least 3 nodes. A 2-node replica set cannot elect a new primary if one node fails because neither node alone holds a majority of votes. Three nodes can always form a quorum even when one is down.
Note
The oplog is a capped collection. Its size determines how long a secondary can be offline before it falls too far behind to catch up (requiring a full resync). Size it large enough to cover your longest expected maintenance window — the default is 5% of free disk space, with a minimum of 990 MB.