How MongoDB replica sets work and why you need them
replica set architecture, primary and secondary nodes, automatic failover, read preferences, write concern, oplog, replication lag, arbiters
Replica set architecture
A replica set is a group of MongoDB instances maintaining identical copies of the same data. One node is the primary — it accepts all write operations. The rest are secondaries that continuously replicate the primary's operation log (oplog). If the primary becomes unavailable, the remaining nodes elect a new primary automatically, typically within 10–30 seconds, with no manual intervention required.
// Connection string listing all replica set members
const client = new MongoClient(
'mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=rs0'
)
// The driver detects failover and reroutes operations automatically
// Write concern — wait for majority of nodes to acknowledge the write
await db.collection('payments').insertOne(
{ amount: 500, userId: 'u1', status: 'processed' },
{ writeConcern: { w: 'majority', wtimeout: 5000 } }
)
// Read from secondaries — acceptable for analytics with slight lag
const logs = await db.collection('events')
.find({}, { readPreference: 'secondaryPreferred' })
.toArray()Write concern levels
w: 1 (default) acknowledges after the primary writes only. w: 'majority' waits for more than half the voting nodes to confirm — essential for financial data since it ensures the write survives a primary failure before replication completes. Always use w: 'majority' for data that must never be lost under any failure scenario.
For self-hosted replica set setup, initialize the set from the primary with rs.initiate() in mongosh, then add members with rs.add('host2:27017'). Check the current replica set status at any time with rs.status(), which shows each member's role, health, replication lag in seconds, and the optime of its last applied operation.
