Replica set · databases

Also known as: MongoDB replica set

On this page 7

A replica set in databases is a group of database servers that maintain identical copies of the same data, with one member accepting writes and the others replicating its changes. The term is most closely associated with the MongoDB replica set, where it is the basic unit of high availability: if the primary fails, the remaining members elect a new primary automatically, usually within seconds.

In the wider field of replication, a replica set combines a primary-replica topology, a consensus-based election protocol and configurable durability guarantees. It protects against server and data center failures, can serve reads from secondary members and forms the building block of each shard in a sharded cluster.

How a replica set replicates and elects

A replica set works by having the primary record every write in an operation log, called the oplog in MongoDB, which secondary members copy and apply in order. Each secondary tails the oplog of the primary or of another secondary, so replication is asynchronous by default and secondaries may lag slightly behind.

Members exchange heartbeats every two seconds. When a secondary does not reach the primary within the election timeout, 10 seconds by default, it calls an election. The election protocol is derived from Raft: candidates increment a term number, request votes and need a strict majority of voting members to win, and the member with the most recent oplog entries is favored.

The table below summarizes the member roles a replica set can contain.

Member typeHolds dataVotesTypical purpose
PrimaryYesYesAccepts all writes and default reads
SecondaryYesYesReplicates data and can become primary
ArbiterNoYesBreaks ties in elections without storing data
Hidden memberYesOptionalBackups or analytics invisible to clients
Delayed memberYesOptionalKeeps an older copy to recover from mistakes
Replica set member types

Only one primary can accept majority-acknowledged writes at any time. A former primary that loses contact with the majority steps down to secondary, which prevents a split-brain situation in which two members both accept durable writes.

Sizing and configuration parameters

The most important design decision is the number of voting members, because elections require a majority. An odd number of voters is recommended, since adding a fourth voter to three raises the majority from two to three without improving fault tolerance.

Voting membersMajority neededFailures tolerated
321
431
532
743
Voting members and fault tolerance

MongoDB allows up to 50 members in a replica set, of which at most 7 vote. Beyond member count, durability and consistency are tuned per operation with write concern and read concern, while read preference decides which members serve queries.

SettingCommon valuesEffect
Write concernw: 1, w: majorityHow many members must acknowledge a write
Read concernlocal, majority, linearizableWhich data a read is allowed to return
Read preferenceprimary, secondaryPreferred, nearestWhich member serves a read
Member priority0 to 1000Likelihood of becoming primary; 0 means never
Election timeout10 seconds by defaultTrade-off between fast failover and false alarms
Key replica set settings

A replica set differs from a basic primary-replica pair mainly through built-in automatic failover. Classic setups with read replicas in relational systems often need an external tool, such as Patroni for PostgreSQL, to detect failure and promote a new primary.

ConceptWrite modelFailoverTypical system
Replica setSingle primaryBuilt in, majority electionMongoDB
Streaming replicationSingle primaryExternal manager requiredPostgreSQL
Multi-primary replicationSeveral writersNo election neededGalera Cluster, MySQL Group Replication
Always On availability groupsSingle primaryCluster-managedSQL Server
Sharded clusterOne primary per shardPer shard replica setMongoDB at scale
Replica set and neighboring concepts

Replication is not partitioning. A replica set copies all data to every data-bearing member, so it increases availability and read capacity but does not increase write capacity. Write scaling requires sharding, in which each shard is itself a replica set.

Deploying a replica set in production

A production replica set should place members so that no single failure removes the majority. The common baseline is three data-bearing members in three availability zones, which survives the loss of one zone while keeping a writable primary.

  • Use w: majority for important writes so acknowledged data survives a failover.
  • Size the oplog window to cover at least the longest expected maintenance outage, often 24 to 72 hours of writes.
  • Monitor replication lag and alert when secondaries fall behind by more than a few seconds.
  • Prefer a third data-bearing member over an arbiter, because an arbiter cannot help satisfy majority write concern.
  • Configure clients with the full member list or a seed list so drivers can discover the new primary after an election.

Limitations and failure modes

Replica sets protect against hardware and network failures but not against logical errors. An accidental collection drop replicates to every member within moments, so backups or a delayed member remain necessary.

With w: 1, a primary can acknowledge writes that never reached a secondary. If it then fails, the new primary lacks those writes, and when the old primary rejoins, the unreplicated operations are rolled back and saved to rollback files instead of the live data. Reads from secondaries can also return stale data, which surprises applications that expect read-your-writes behavior without causal consistency sessions.

The simple explanation

A replica set is like a team of three clerks who each keep the same ledger. Only one clerk, the leader, writes new entries, and the other two copy every entry into their own books.

If the leader suddenly goes home sick, the remaining clerks quickly vote and pick a new leader from among themselves, so customers can keep making changes. The key takeaway is that a replica set keeps data available when a server fails, but every clerk copies mistakes too, so it does not replace backups.

How it is used in practice

A food delivery platform stores orders in a three-member MongoDB replica set, with one member in each of three availability zones of a cloud region. The application writes orders with write concern majority and reads order status from the primary, while an analytics job reads from a hidden member so heavy reports never slow down checkout.

During a Friday evening peak, the zone hosting the primary loses power. The two surviving members detect missing heartbeats, hold an election and promote a secondary to primary after about 12 seconds. Drivers in the application servers retry the few interrupted writes, and because each acknowledged order had already reached a majority, no confirmed order is lost. When the zone recovers, the old primary rejoins as a secondary and catches up from the oplog.