Replication & Replica Sets
Understand how MongoDB replica sets provide redundancy and automatic failover through primary and secondary nodes.
What Is a Replica Set?
A replica set is a group of MongoDB servers (nodes) that maintain identical copies of the same data, providing redundancy against hardware failure and enabling automatic recovery without manual intervention. MongoDB Atlas provisions a replica set (typically 3 nodes) by default, even on its free tier.
Primary and Secondary Nodes
One node in a replica set is elected the primary, accepting all writes. The other nodes are secondaries, continuously replicating the primary's changes (via an internal operation log called the oplog) so they stay in sync and ready to take over if needed.
Automatic Failover
If the primary node becomes unavailable, the remaining nodes automatically hold an election and promote one of the secondaries to become the new primary — typically completing within seconds, without requiring a human to intervene.
Because MongoDB Atlas provisions a replica set by default, even small hobby projects get automatic failover protection against a single server failure — a meaningful reliability guarantee with zero extra configuration.
Read Preferences
By default, all reads go to the primary, guaranteeing the most up-to-date data. A read preference can direct reads to secondaries instead — useful for distributing read load, at the cost of potentially slightly stale data due to replication lag.
db.orders.find({ status: "completed" }).readPref("secondaryPreferred");| Read Preference | Behavior |
|---|---|
| primary (default) | Always reads from the primary — the most consistent option |
| secondary | Always reads from a secondary — reduces load on the primary |
| secondaryPreferred | Prefers a secondary, falling back to the primary if none are available |
FAQs
A minimum of 3 is standard for production (enabling a majority vote during an election), though a replica set can technically function with fewer for development purposes.
Yes, to a small degree — replication lag means a secondary might be a few milliseconds (occasionally more) behind the primary; use readConcern "majority" if strict consistency matters more than distributing read load.
Summary
Replica sets provide redundancy and automatic failover through primary/secondary nodes, with read preferences letting you trade consistency for read scalability when appropriate. Next, you'll learn sharding, MongoDB's approach to scaling writes horizontally.