Replica Set

A replica set is MongoDB's name for a group of database nodes that maintain the same data and provide automatic failover. One node is the primary (accepts writes); the rest are secondaries that asynchronously apply the primary's operation log. If the primary becomes unreachable, the secondaries elect a new primary among themselves.

How it works

Writes go to the primary, which records them in its operation log (oplog). Secondaries tail the oplog and apply the same operations locally, eventually matching the primary's state. Reads can be served from secondaries with explicit read preferences, trading freshness for read scaling.

Membership and elections

  • Primary. Receives all writes; only one at a time.
  • Secondaries. Replicate from the primary; can serve reads with appropriate read concern.
  • Arbiter. Votes in elections but holds no data; used for odd member counts when adding another data-bearing node is unjustified.
  • Hidden, priority-0, delayed. Special-purpose secondaries that never become primary, used for backups, analytics, or disaster recovery.

Read and write concerns

  • Write concern. How many replicas must acknowledge a write before it returns. Higher values trade write latency for durability.
  • Read concern. How recent the data being read must be: local, majority, linearizable. Stronger reads cost more.

Subscribe to Sahil's Playbook

Clear thinking on product, engineering, and building at scale. No noise. One email when there's something worth sharing.
[email protected]
Subscribe
Mastodon