100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
MongoDB

Replica Sets Explained

How MongoDB replica sets provide high availability through automatic failover, elections, and data redundancy across primary and secondary nodes.

Scaling & PracticeIntermediate9 min readJul 10, 2026
Analogies

What Is a Replica Set?

A MongoDB replica set is a group of mongod processes that maintain the same data set, providing redundancy and high availability. One member is elected primary and accepts all write operations, while the remaining members are secondaries that replicate the primary's oplog to stay in sync. If the primary becomes unavailable, an eligible secondary is automatically elected to take over, so the application experiences only a brief interruption instead of a full outage.

🏏

Cricket analogy: Like a cricket team having a designated captain who makes on-field decisions while vice-captains shadow every call, ready to step in immediately if the captain is injured mid-over, a replica set keeps secondaries synced so one can take charge without the match stopping.

Elections and the Oplog

When a primary steps down or becomes unreachable, eligible secondaries call for an election using a Raft-inspired consensus protocol, and the member with the most up-to-date oplog and highest priority typically wins a majority vote. The oplog (operations log) is a special capped collection that records every write in an idempotent form; secondaries continuously tail this log and apply the same operations to stay current, which is also how initial sync and delayed members catch up after downtime.

🏏

Cricket analogy: Like a team selection committee voting on a new captain after an injury, weighing who has the most recent form and highest seniority, a replica set election picks the secondary with the freshest oplog and highest priority.

Write Concern and Read Preference

Write concern controls how many replica set members must acknowledge a write before it is considered successful; w: 'majority' waits for acknowledgment from a majority of voting members and, combined with journaling, guards against data loss during failover. Read preference determines which members can serve reads: primary (default, strongly consistent), secondaryPreferred (favors read scaling but may return stale data), and nearest (lowest latency regardless of role) are the most commonly used modes in production.

🏏

Cricket analogy: Like a run only being confirmed once both the on-field umpire and the third umpire agree on a review, w: majority only confirms a write once most of the replica set has acknowledged it.

javascript
// Initiate a 3-node replica set
rs.initiate({
  _id: "rs0",
  members: [
    { _id: 0, host: "mongo1:27017", priority: 2 },
    { _id: 1, host: "mongo2:27017" },
    { _id: 2, host: "mongo3:27017" }
  ]
});

// Application connection string using the replica set
mongodb://mongo1:27017,mongo2:27017,mongo3:27017/mydb?replicaSet=rs0

// Write with majority acknowledgment
db.accounts.updateOne(
  { _id: "acct-1" },
  { $inc: { balance: -100 } },
  { writeConcern: { w: "majority", wtimeout: 5000 } }
);

// Read from secondaries when eventual consistency is acceptable
db.orders.find({ status: "shipped" }).readPref("secondaryPreferred");

Replica sets need an odd number of voting members to avoid tied elections. If you have an even number of data-bearing nodes for cost reasons, add an arbiter (a vote-only member that holds no data) to break ties, but avoid running more than one arbiter since it can complicate majority write concern.

Failover and Recovery

Automatic failover typically completes within a few seconds once the remaining members detect the primary is down and hold a new election, but any writes that reached the old primary and were not yet replicated to a majority can be rolled back when that node rejoins as a secondary. This is why applications that cannot tolerate any data loss should use w: majority alongside appropriate read concerns, rather than relying on the default acknowledgment from a single primary.

🏏

Cricket analogy: Like a declared innings score being revised after a third-umpire review overturns a boundary that wasn't properly confirmed by the on-field umpires, an unreplicated write can be rolled back after failover.

Using the default write concern of w: 1 means a write is acknowledged as soon as the primary applies it, before secondaries replicate it. If the primary crashes moments later, that write can be silently lost on rollback. Use w: 'majority' for any data you cannot afford to lose.

  • A replica set is a group of mongod nodes holding the same data, with one primary and one or more secondaries.
  • Elections use a consensus protocol and favor the secondary with the most up-to-date oplog and highest priority.
  • The oplog is a capped collection of idempotent operations that secondaries continuously tail to stay in sync.
  • Write concern 'majority' waits for acknowledgment from most voting members, protecting against data loss on failover.
  • Read preference modes (primary, secondaryPreferred, nearest) trade off consistency against latency and read scaling.
  • Arbiters can break ties in an even-numbered cluster but hold no data themselves.
  • Unreplicated writes on a failed primary can be rolled back once it rejoins, so w: 1 carries data-loss risk.

Practice what you learned

Was this page helpful?

Topics covered

#MongoDB#MongoDBStudyNotes#Database#ReplicaSetsExplained#Replica#Sets#Explained#Set#StudyNotes#SkillVeris