Replica Sets, High Availability, and Failover Mechanisms

MongoDB Replication

Replication keeps multiple copies of your data in sync across servers, providing high availability and protecting against data loss. In MongoDB, this is implemented through replica sets.

1. What Is a Replica Set?

A replica set is a group of MongoDB instances maintaining the same data set. It consists of one Primary node (handles all writes) and multiple Secondary nodes (replicate data from the primary and can serve reads).

Node TypeRole
PrimaryReceives all write operations; replicates changes via the oplog
SecondaryReplicates data from primary; can serve read queries
ArbiterParticipates in elections but holds no data (tie-breaker)

2. Setting Up a Replica Set

// Start three mongod instances with --replSet
mongod --replSet "rs0" --port 27017 --dbpath /data/db1
mongod --replSet "rs0" --port 27018 --dbpath /data/db2
mongod --replSet "rs0" --port 27019 --dbpath /data/db3

// Initiate the replica set from mongosh
rs.initiate({
  _id: "rs0",
  members: [
    { _id: 0, host: "localhost:27017" },
    { _id: 1, host: "localhost:27018" },
    { _id: 2, host: "localhost:27019" }
  ]
})

3. Automatic Failover

If the primary becomes unreachable, the remaining secondaries hold an election to promote a new primary — typically within seconds, minimizing downtime.

rs.status()      // View current replica set state
rs.isMaster()    // Check which node is currently primary
Best Practice: Always deploy an odd number of voting members (3, 5, 7) to avoid split-vote scenarios during elections.

4. Read Preferences

Read PreferenceBehavior
primary (default)All reads go to the primary — strongest consistency
primaryPreferredPrimary if available, else a secondary
secondaryAll reads from secondaries — reduces primary load
nearestLowest network latency node, primary or secondary

5. Write Concern

db.orders.insertOne(
  { item: "Book", qty: 3 },
  { writeConcern: { w: "majority", wtimeout: 5000 } }
)

w: "majority" ensures the write is acknowledged by a majority of replica set members before returning success — a strong durability guarantee.

6. Replication Checklist

  • ✅ Understand primary/secondary/arbiter roles
  • ✅ Initiate and verify a replica set
  • ✅ Know how automatic failover elections work
  • ✅ Configure read preferences appropriately
  • ✅ Use write concern for durability guarantees
Key Takeaway: Replica sets are the foundation of MongoDB's high availability story — every production deployment should run as a replica set, never a single standalone node.

Ready to master MongoDB?

Build real-world MongoDB-powered applications with hands-on projects, mentor-led sessions, and placement support.

Explore Course