Replication
Replica sets, elections, read preferences, and write concerns
Skills taught: mongodb.replication
What is a Replica Set?
A replica set is a group of MongoDB servers that maintain the same dataset. One member is the primary (receives all write operations), and one or more are secondaries (replicate from the primary asynchronously). If the primary becomes unavailable, the secondaries automatically elect a new primary.
Typical 3-node Replica Set:
┌─────────────────────────────────────────────┐
│ Replica Set │
│ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐│
│ │ Primary │───>│Secondary │ │Secondary ││
│ │ (writes) │ │ (reads) │ │ (reads) ││
│ └──────────┘ └──────────┘ └──────────┘│
│ │ │ │ │
│ └───── oplog replication ──────┘ │
└─────────────────────────────────────────────┘
If Primary fails:
→ Secondaries detect failure (after ~10s)
→ Election: remaining nodes vote for new primary
→ New primary elected automatically
→ App reconnects via connection string (no code change)
Connecting to a Replica Set
// Connection string lists all replica set members
// The driver automatically handles failover when primary changes
const uri = 'mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=myReplicaSet';
// MongoDB Atlas provides this automatically:
const atlasUri = 'mongodb+srv://user:pass@cluster0.mongodb.net/mydb?retryWrites=true&w=majority';
// 'mongodb+srv://' — SRV record resolves to all 3 replica set members
// retryWrites=true — automatically retry writes on network blips
// w=majority — wait for majority acknowledgement (data safety)
const client = new MongoClient(atlasUri);
await client.connect();
// The driver is now replica-set-aware — it knows all members
// and will automatically reconnect to the new primary if failover occurs
Write Concern — Data Durability
Write concern controls how many replica set members must acknowledge a write before the driver considers it successful. Higher write concern = more durability, slightly more latency.
// w: 1 (default) — acknowledged by primary only
// Fast but: if primary crashes before replicating, write may be lost
await db.collection('logs').insertOne(
{ event: 'page_view', url: '/home' },
{ writeConcern: { w: 1 } } // OK for non-critical data
);
// w: 'majority' — acknowledged by majority of voting members
// Slightly slower but: write survives primary failure
await db.collection('orders').insertOne(
{ userId: id, items: cart, total: 2499 },
{ writeConcern: { w: 'majority' } } // critical data — use majority!
);
// w: 0 — fire and forget (not acknowledged)
// Fastest but no guarantees — only for truly throwaway data
await analytics.insertOne(
{ event: 'ad_impression' },
{ writeConcern: { w: 0 } } // we don't care if a few are lost
);
// Set at collection level (applies to all operations)
const orders = db.collection('orders').withOptions({
writeConcern: { w: 'majority', j: true } // j: true = also wait for journal flush
});
Read Preference — Where Reads Go
Read preference controls which replica set member serves read operations. Reads from secondaries are eventually consistent — they may lag slightly behind the primary.
// primaryPreferred — read from primary, fallback to secondary if unavailable
const db = client.db('myapp', {
readPreference: 'primaryPreferred'
});
// secondary — always read from a secondary (never primary)
// Good for analytics/reporting that can tolerate slight staleness
const analyticsDb = client.db('myapp', {
readPreference: 'secondary'
});
// nearest — read from the replica set member with lowest network latency
// Good for globally distributed apps with read replicas in different regions
const nearestDb = client.db('myapp', {
readPreference: 'nearest'
});
// Per-operation read preference override:
const recentOrders = await db.collection('orders').find(
{ status: 'pending' },
{ readPreference: 'primary' } // must read from primary for strong consistency
).toArray();
// Read preferences:
// primary — always from primary (default)
// primaryPreferred — primary if available, secondary if not
// secondary — always from secondary (may be slightly stale)
// secondaryPreferred — secondary if available, primary if not
// nearest — lowest latency member
Change Streams — Real-Time Data
Change streams allow applications to subscribe to real-time changes in a collection, database, or entire deployment. Built on the oplog, they enable event-driven architectures without polling.
// Watch for changes to the orders collection
const changeStream = db.collection('orders').watch();
// Process each change event
for await (const change of changeStream) {
console.log('Change type:', change.operationType); // insert, update, delete
console.log('Document ID:', change.documentKey._id);
if (change.operationType === 'insert') {
const newOrder = change.fullDocument;
await sendConfirmationEmail(newOrder.userId, newOrder);
}
if (change.operationType === 'update') {
const { updatedFields } = change.updateDescription;
if (updatedFields.status === 'shipped') {
await sendShippingNotification(change.documentKey._id);
}
}
}
// Resume after restart using resumeToken
const token = loadResumeToken(); // load from storage
const resumedStream = db.collection('orders').watch([], {
resumeAfter: token // picks up exactly where it left off
});
Tip: Always use w: 'majority' for financial transactions, user account operations, and any critical writes. The slight latency increase (a few milliseconds) is worth the guarantee that the write survives primary failure.
Frequently Asked Questions
How many members should a replica set have?
Always use an odd number (3, 5, 7) to avoid split-brain during elections. A 3-node replica set is the standard — it tolerates 1 failure. For higher availability, use 5 nodes. Never use 2 nodes — if one goes down, the remaining node can't achieve a majority and won't elect a primary.
What is the oplog?
The oplog (operations log) is a special capped collection in the 'local' database that records all write operations as idempotent BSON documents. Secondaries replicate by tailing the primary's oplog. Change streams are also built on the oplog. The oplog has a configurable retention window.
Can I read from a secondary in MongoDB?
Yes, with read preference set to 'secondary' or 'secondaryPreferred'. However, secondary reads may be slightly stale (seconds behind the primary). Use secondary reads for reporting, analytics, or backup dumps — not for data that must be strongly consistent.