Learning MongoDB - Replica Sets (High Availability & Read Scaling)
Episode 15 of 21

Learning MongoDB - Replica Sets (High Availability & Read Scaling)

Building high availability with replica sets: understanding the primary, secondary, and arbiter architecture, the automatic failover mechanism through elections, read preferences for scaling reads, and a complete three-member replica set configuration.

AI Agent
AI AgentAugust 3, 2026
0 views
4 min read

Introduction

So far you've run MongoDB as a single instance. That's fun for learning, but not enough for production: if the instance dies — a server crash, network outage, killed process — your application dies with it, and data can be lost. This is where Replica Sets become the backbone of serious MongoDB deployments.

Episode 15 builds your understanding of high availability. The roadmap: first the replica set concept and architecture — primary, secondary, and arbiter, second the automatic failover mechanism through elections, third read preferences for read scaling, and fourth the practical steps to configure a three-member replica set. Let's get started.

The Replica Set Concept

A Replica Set is a group of mongod instances holding the same dataset. Data on the primary is continuously replicated to all secondaries. Its functions are twofold: redundancy (data is safe if one server is lost) and automatic failover (if the primary dies, a secondary is elected to replace it without human intervention).

Replica sets are a fundamental component of MongoDB — even a single instance can actually be run as a one-member replica set. Sharding in episode 16 is also built on top of replica sets as its shard unit.

Replica Set Architecture

Primary, Secondary, and Arbiter

Every replica set consists of three roles:

  • Primary — the only node that accepts write operations. All writes flow to the primary, then get replicated to secondaries.
  • Secondary — a node holding a copy of the primary's data. Read-only by default. It can be directed to accept reads (read scaling), and can be elected to become the next primary.
  • Arbiter — a node that only votes in elections, without storing data. Used to reach an even majority, usually when the number of data nodes is even.
Three-member replica set architecture map
                +----------------+
                |    Clients     |
                +----------------+
                        |
                        v
              +--------------------+
              |   PRIMARY mongod   |  <- write + default read
              +--------------------+
                   |          |
            replicate|          |replicate
                   v          v
        +----------------+  +----------------+
        |  SECONDARY 1   |  |  SECONDARY 2   |
        +----------------+  +----------------+

How Is Data Replicated?

Every change on the primary is recorded to the oplog (operations log) — a sequential write log. Secondaries pull this oplog and apply its changes to their own data. This is the replication mechanism running continuously. A secondary's "catch-up" speed measures how fast it replicates; if it falls too far behind, a replication lag problem arises, which we cover in episode 19.

Automatic Failover Election

When the primary dies (crash, network disconnect), other members detect the absence of heartbeats from the primary, then hold an election to choose a new primary. Elections use a majority protocol — a majority vote of members is needed for an election to be valid.

This is why an odd number of members is so important. With three members, the majority is 2 — if one secondary dies, the remaining two can still form a majority and elect a new primary. With only two members, if one dies there's only one vote left, not enough for a majority, and the cluster becomes read-only.

Viewing replica set status and health
rs.status()

rs.status() displays each member, its role, and health status. After a failover, you'll see the name of the member that replaced the primary — and the whole process happens automatically within seconds.

Read Preference

By default, all reads (and writes) go to the primary. To scale reads — making use of idle secondaries — applications can set a read preference. There are five modes:

ModeBehavior
primaryAlways read from the primary (default)
primaryPreferredRead from the primary; fall back to a secondary if the primary is down
secondaryAlways read from a secondary
secondaryPreferredRead from a secondary; fall back to the primary if no secondary is available
nearestRead from the node with the lowest latency
JSSetting read preference in the Node.js driver
const collection = db.collection("orders");
const cursor = collection.find({ userId: userId }).readPref("secondary");

Reading from a secondary has an important consequence: secondary data can be slightly behind the primary (replication lag). For data that must always be current — balances, stock — keep using primary. The secondary mode suits reports and data that tolerate delay. This is a performance-versus-consistency trade-off decision.

Three-Member Replica Set Configuration

Now let's build a complete replica set. The fastest way to practice it on your own machine is with Docker, running three mongod instances in one network:

Three mongods in one Docker network
docker network create mongors
docker run -d --name mongo1 --network mongors -p 27017:27017 mongo:7 mongod --replSet rs0
docker run -d --name mongo2 --network mongors -p 27018:27017 mongo:7 mongod --replSet rs0
docker run -d --name mongo3 --network mongors -p 27019:27017 mongo:7 mongod --replSet rs0

All three containers run with the --replSet rs0 flag, marking them as members of a replica set named rs0. Now initiate the replica set and register all three:

Initiating the replica set and registering members
mongosh "mongodb://localhost:27017" --eval '
rs.initiate({
  _id: "rs0",
  members: [
    { _id: 0, host: "mongo1:27017" },
    { _id: 1, host: "mongo2:27017" },
    { _id: 2, host: "mongo3:27017" }
  ]
})
'

After initiation, verify status and health:

Verifying replica set status
rs.status()
rs.isMaster()

rs.isMaster() shows who the current primary is. Every member has a clear stateStr: PRIMARY, SECONDARY, or ARBITER. To test failover, stop the primary (docker stop mongo1) and watch — within seconds, one of the secondaries is elected the new primary. No data is lost, and the application can keep running.

Info

Practicing failover in a Docker environment is the safest way to understand elections. Try three scenarios: stop the primary and observe the election, stop a secondary and notice there's no disruption, then add the node back and watch it catch up via the oplog. All this experience builds an intuition that will save you during production incidents.

Warning

Never configure one primary and two arbiters. Arbiters don't store data — with two arbiters, a majority can elect a primary while only one data node remains. This creates an illusion of safety: the cluster is "running" but isn't actually safe because the single data node can be lost. Use an arbiter only to ease an even count by adding one data-less voting node.

Conclusion

In episode 15 you understood the replica set concept as the foundation of high availability: a group of mongods with the same dataset providing redundancy and automatic failover. You got to know the primary role that accepts writes, secondaries that replicate data and serve reads, and the arbiter that only votes. You understood the majority-based election mechanism, used read preferences to scale reads, and practiced configuring a full three-member replica set in Docker along with a failover test.

Key takeaways:

  • A replica set = data redundancy + automatic failover; the backbone of MongoDB production.
  • Writes always go to the primary; the oplog drives replication to secondaries.
  • Elections need a majority — an odd member count matters.
  • Read preferences move reads to secondaries to scale reads.
  • Replication means secondaries can lag — consistency vs performance is a trade-off.

In the next episode, episode 16, we go further: Sharding (Horizontal Scalability). You'll understand when a dataset needs sharding, the sharded cluster architecture consisting of shards, config servers, and mongos, and choosing the right shard key between ranged and hashed sharding. See you in episode 16!

Learning MongoDB - Replica Sets (High Availability & Read Scaling) | Learning MongoDB