Course contentsShow
← System Design
Lesson 394 of 1,91911. NoSQL: Document StoresFree lesson

Replica Sets for High Availability

How MongoDB uses replica sets with primary-secondary architecture to ensure data redundancy and automatic failover.

Replica Sets for High Availability

What you'll learn: How MongoDB uses replica sets to keep your data safe and accessible even when servers fail.


The Core Idea

A replica set in MongoDB is a group of MongoDB servers that all hold copies of the same data. This group follows a primary-secondary architecture: one server acts as the primary (handling all writes), while the others are secondaries (maintaining synchronized copies).

Think of it like a classroom with one teacher and several teaching assistants. The teacher (primary) writes notes on the board, and all assistants (secondaries) copy those notes to their own boards in real time. If the teacher suddenly leaves, one assistant immediately steps up to become the new teacher.

How It Works

When you write data to MongoDB, it goes to the primary node. The primary then replicates changes to all secondary nodes through an operation log (oplog). Secondaries continuously sync this log to stay up-to-date.

The magic happens during failure: if the primary crashes, the remaining nodes automatically hold an election and promote one secondary to become the new primary. This automatic failover typically completes in seconds, minimizing downtime.

Why This Matters

Replica sets provide data redundancy—your data exists on multiple servers, so losing one doesn't mean losing data. They also enable high availability—if one server fails, another takes over automatically without manual intervention.

You can configure a replica set with 3, 5, or more nodes. An odd number is preferred for election purposes. Reading from secondaries is optional and trades consistency for performance.

Key Takeaway: MongoDB replica sets use primary-secondary architecture to maintain multiple synchronized data copies, enabling automatic failover and ensuring your database stays available even when individual servers fail.