Part of series: MongoDB Roadmap
High Availability: Mastering Replica Sets
Welcome to Week 6! ๐ This is the final leg of our journey: Scaling.
Your apps will grow. Your servers will crash. How do you ensure 100% uptime? Replication.
1. How Replication Works
A Replica Set is usually 3 nodes:
- Primary: Accepts Writes and Reads.
- Secondary A: Copies data from Primary (OpLog).
- Secondary B: Copies data from Primary (OpLog).
Data flows asynchronously. The Primary doesnโt wait for Secondaries to acknowledge the write (unless you use w: "majority").
2. Automatic Failover ๐
If the Primary crashes (or the network cable is cut):
- The Secondaries notice โHey, the Primary is silent!โ.
- They hold an Election.
- The node with the most up-to-date data becomes the New Primary.
- Your app (using the MongoDB driver) automatically detects the new Primary and redirects traffic.
Downtime? usually 2-10 seconds.
3. Read Preference ๐
By default, all reads go to the Primary (Consistency > Latency). But you can scale reads by reading from Secondaries.
// Mongoose
const schema = new Schema({ ... }, { read: 'secondaryPreferred' });
Modes:
primary: (Default). Strong consistency.primaryPreferred: Read primary, unless itโs down.secondary: Read only from secondaries (Eventual Consistency).nearest: Read from the lowest latency node (Primary or Secondary).
4. Write Concern โ๏ธ
How โsafeโ do you want your writes to be?
w: 1(Default): Acknowledged by Primary.w: 0: Fire and forget (Fastest, risky).w: "majority": Acknowledged by >50% of the nodes. (Safest).
db.users.insertOne(
{ name: "Alice" },
{ writeConcern: { w: "majority", wtimeout: 5000 } }
)
Use w: "majority" for financial data to prevent data rollbacks during failover.
๐ง Daily Challenge
- If you have Docker, spin up 3 mongo containers.
- Configure them as a Replica Set (
rs.initiate()). - Kill the Primary container (
docker stop mongo1). - Watch
mongo2ormongo3become the Primary!
See you on Day 2 for the big one: Sharding! ๐