Home›Learn›MongoDB 4: high availability with replica sets
MongoDB · Chapter 4 · High availability

High availability with MongoDB replica sets

Why does a MongoDB primary step down on its own, and what happens to the writes it had?

MongoDB builds failover into the database. A replica set elects its own primary, and drivers follow it automatically. The choices that matter are how many members vote, and how many must have a write before you call it saved.

Why this chapter matters

Why we need high availability at all

Every server fails eventually: a disk, a kernel panic, a zone outage, or just the patch you have to install on Tuesday. With one database, each of those is an outage for every customer at once. High availability turns them into a few seconds that most users never notice.

What we are protecting

Revenue and trust. Checkout, login, payments: when the database is down, the whole product is down, and nothing in the app can work around it.

What we achieve

Two numbers. RTO: how fast writes work again, seconds instead of the 15 to 30 minutes a manual failover takes. RPO: how much confirmed data a failure can lose, ideally zero.

Maintenance without downtime

The quiet win. With a spare node, patches, upgrades and hardware swaps become rolling switchovers during the day, not maintenance windows at night.

What it is not

A backup. A bad DELETE reaches every replica in milliseconds. You still need backups and point-in-time recovery.

What the targets mean in minutes

Availability targetDowntime allowed per yearPer monthWhat it takes
99.9% ("three nines")8.8 hours43.8 minutesOne server and good backups can almost do it, if nothing big breaks.
99.99% ("four nines")52.6 minutes4.4 minutesAutomatic failover. One manual 3 a.m. failover uses most of the year.
99.999% ("five nines")5.3 minutes26 secondsAutomatic failover in seconds, and maintenance with no downtime at all.

The arithmetic is why teams automate: a single manual failover at 3 a.m. can spend a whole year of a 99.99% budget.

How companies usually set it up

  1. Three nodes across three availability zones in one region, with automatic failover. This is the standard production setup; losing a zone loses one node.
  2. A replica in a second region for disaster recovery, usually asynchronous, promoted by a person or a runbook when a whole region is gone.
  3. A proxy or pooler in front, so the app has one address and never needs to know which server is primary.
  4. Backups and continuous WAL archiving to object storage, with restores tested on a schedule.
  5. Or a managed service (RDS, Aurora, Cloud SQL) that does the same three jobs for you, with less control.

Running it on thousands of servers

Nobody configures a thousand clusters by hand. At that scale, high availability is a product the database team runs, with the same few parts everywhere:

Desired state in code

Each cluster is a file in Git: size, version, replicas, settings. Terraform, Ansible or a Kubernetes operator turns the file into servers, and a pull request is how anything changes.

One failover tool, everywhere

The same Patroni (or orchestrator, or Group Replication) setup on every cluster, so a failover at 3 a.m. behaves exactly like the one you tested.

Service discovery, not hard-coded hosts

Consul, etcd or a proxy layer tells every app where the primary is right now. Failover updates one record, not a thousand config files.

Fleet automation with guardrails

Rolling patches and upgrades one node, then one cluster, at a time. Rate limits so a bad network day cannot trigger a hundred failovers at once.

Proof, not hope

Scheduled switchovers and game days that kill a primary on purpose, restore tests from backup, and dashboards that show every cluster's role, lag and last failover.

Runbooks a machine can follow

The common incidents are scripted and safe to run; the rare ones page a person with the evidence already gathered. That is the idea behind the DBA agent on this site.

Step through it: how a team patches a cluster with no downtime.

What it looks like at real companies

Now let us look at how one replica set does it, and how MongoDB got from manual promotion to elections built into the database.

The idea behind it

How MongoDB got here

WhenWhat changedWhat it fixed
Early versionsMaster-slave replication.Copies, but no automatic failover. You promoted a slave by hand. Removed in 4.0.
1.6 (2010)Replica sets.Members vote, and a new primary is elected without a person.
3.2 (2015)Replication protocol version 1, based on Raft, became the default.Faster elections and terms that stop an old primary from confusing the set.
4.0 (2018)Multi-document transactions on replica sets.All or nothing across documents, replicated as one unit.
5.0 (2021)Default write concern became majority (with some arbiter exceptions).A write acknowledged by default is on a majority, so a failover does not roll it back.

The idea is the same as Patroni's etcd or Group Replication's majority: only a side that holds a majority of votes may have a primary, so a cut-off node cannot keep taking writes. MongoDB just builds the vote into each member.

Explained clearly

What a replica set does

Listen, 3 min 16 s
1

The problem

One server is one failure away from an outage. Copies help only if something decides, quickly and without two winners, which copy takes writes.

2

What it is

A replica set is a primary and its secondaries. The primary records every change in the oplog, a capped collection; secondaries copy and apply it. Members send heartbeats every 2 seconds. If secondaries lose the primary for electionTimeoutMillis (10 s), one of them calls an election and needs a majority of votes to win.

3

Follow one failover

  1. The primary's host dies.
  2. After 10 s without heartbeats, a secondary calls an election for a new term.
  3. Members vote for a candidate whose oplog is at least as recent as theirs. A majority wins.
  4. The new primary starts taking writes. Drivers discover it and retry a failed write once (retryable writes are on by default).
  5. The old primary comes back as a secondary. Any writes it had that never reached a majority are rolled back and saved to rollback files.

For your app: MongoDB says the median time to a new primary should not exceed 12 seconds with default settings.

4

What to watch

  • Use w: "majority" for writes you cannot lose. A w: 1 write can be rolled back after a failover.
  • Prefer three data-bearing members over two plus an arbiter. With an arbiter, losing one data member leaves you unable to reach a majority write.
  • Size the oplog so a secondary that is down for maintenance can catch up. If it falls off the oplog, it needs a full resync.

Step through it:

Running on Kubernetes? See MongoDB on Kubernetes with the Percona operator. At fleet scale, see running 1,000 databases.

The setup

Three data-bearing members, across three zones

Your appone addressDriverreplicaSet=rs0, w: majoritydb1 · primarytakes writes, writes the oplogdb2 · secondarycopies the oplogdb3 · secondarycopies the oplogchanges flowto every copy

No proxy is needed: the driver gets the member list from the connection string, asks who is primary, and follows elections itself. At most 7 members vote, out of up to 50. For more scale, a sharded cluster uses a replica set for every shard and for the config servers, so the same rules apply to each one.

Step by step

Set it up

  1. Install MongoDB 8.0 on three hosts, in three zones if you can. Allow port 27017 only from the app servers and the other members.
  2. Create a key file so members authenticate each other, and copy it to every host with permissions 400.
  3. Start each mongod with the same replica set name:
# /etc/mongod.conf on each host
replication:
  replSetName: rs0
  oplogSizeMB: 51200          # initial size; change it later with replSetResizeOplog
security:
  keyFile: /etc/mongodb/keyfile
net:
  bindIp: 0.0.0.0
  port: 27017
  1. Initiate the set with mongosh on db1 itself. The key file turns on authorization, and until the first user exists, MongoDB only accepts that local connection:
rs.initiate({
  _id: "rs0",
  members: [
    { _id: 0, host: "db1:27017" },
    { _id: 1, host: "db2:27017" },
    { _id: 2, host: "db3:27017" }
  ]
})
rs.status()
db.getSiblingDB("admin").createUser({ user: "admin", pwd: passwordPrompt(), roles: ["root"] })
// then, logged in as admin:
db.getSiblingDB("admin").createUser({ user: "app", pwd: passwordPrompt(), roles: [{ role: "readWrite", db: "orders" }] })
  1. Connect with every member listed, so the driver can find the primary even if one host is down:
mongodb://app@db1:27017,db2:27017,db3:27017/orders?replicaSet=rs0&w=majority&retryWrites=true
When it breaks

A failover, second by second

  1. 0 sdb1, the primary, loses power. Its last majority-acknowledged write is already on db2.
  2. 2 sdb2 and db3 miss heartbeats from db1.
  3. 10 selectionTimeoutMillis passes. db2 calls an election for a new term.
  4. +1 sdb3 votes for db2. Two of three votes is a majority. db2 becomes primary.
  5. +1 to 2 sDrivers see the new primary and send writes there. A write that failed during the election is retried once.
  6. laterdb1 rejoins as a secondary. If it had w: 1 writes nobody else got, they are rolled back into rollback files for you to inspect.

A planned switchover: rs.stepDown(60) on the primary. It waits for a secondary to catch up, steps down, and will not stand again for 60 seconds.

What goes wrong

What breaks, and what the set does

FailureWhat happensWhat you do
The primary diesElection in about 10 to 12 s.Nothing. Check rs.status() afterwards.
The primary is cut off from the othersIt cannot see a majority and steps down to secondary. The majority side elects a new primary.Nothing. That is the fencing working.
Two of three members downNo majority, so no primary. Reads from secondaries still work if the app allows them.Bring a member back. Forcing a new config is a last resort.
A secondary falls off the oplogIt goes to RECOVERING and cannot catch up.Resync it from scratch, then size the oplog larger.
Elections keep happeningUsually network flaps or an overloaded primary missing heartbeats.Check the network and the primary's load before raising timeouts.
Monitoring

What to watch

rs.status()                         // state of every member, health, optime
rs.printSecondaryReplicationInfo()  // how far behind each secondary is
db.getReplicationInfo()             // oplog size and the time window it holds

Alert on: no primary, a member not PRIMARY or SECONDARY for more than a few minutes, replication lag over your limit, and an oplog window shorter than your longest planned maintenance. Page playbooks: no primary in the replica set, a secondary stuck or far behind.

Next · chapter 5Running it as a DBREWhat I watch, the logs, the settings, the commands← Chapter 3: What happens on every write
Part 1 of 4 · Learn · 56 pagesAll pages

How do databases actually work? From one row on disk to transactions: the words you need, PostgreSQL, MySQL and MongoDB from the files up, then Redis, Cassandra and vector search, side by side, and the query and concurrency traps.

Start 1: the basicsStart 2: ten conceptsStart 3: how a query travelsStart 4: napkin mathThe courseShort videosPostgreSQL 1: why PostgreSQLPostgreSQL 2: how it stores your dataPostgreSQL 3: what happens on every writePostgreSQL 4: high availability with PatroniPostgreSQL 5: running it as a DBREPostgreSQL 6: when it breaksPostgreSQL on Kubernetes: CloudNativePGMySQL 1: why MySQLMySQL 2: how it stores your dataMySQL 3: what happens on every writeMySQL 4: high availability with InnoDB ClusterMySQL 5: running it as a DBREMySQL 6: when it breaksMySQL failover with OrchestratorMySQL on Kubernetes: the Percona operatorsMongoDB 1: why MongoDBMongoDB 2: how it stores your dataMongoDB 3: what happens on every writeMongoDB 4: high availability with replica setsMongoDB 5: running it as a DBREMongoDB 6: when it breaksMongoDB on Kubernetes: the Percona operatorB-tree and LSM treeRedis 1: why RedisRedis 2: how it stores your dataRedis 3: high availabilityRedis 4: running it as a DBRERedis 5: when it breaksCassandra 1: why CassandraCassandra 2: how it stores your dataCassandra 3: high availabilityCassandra 4: running it as a DBRECassandra 5: when it breaksVector databases 1: why vector searchVector databases 2: how it stores your dataVector databases 3: high availabilityVector databases 4: running it as a DBREVector databases 5: when it breaksDatabase familiesEngines side by sideQueries that look fine and are notLost updates and write skewMany servers 1: keep a copy runningMany servers 2: who is the leaderMany servers 3: CAP as settingsMany servers 4: unique IDsMany servers 5: split the dataMany servers 6: across servicesMany servers 7: a thousand databasesStaff path, zero to architect