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.
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.
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.
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.
The quiet win. With a spare node, patches, upgrades and hardware swaps become rolling switchovers during the day, not maintenance windows at night.
A backup. A bad DELETE reaches every replica in milliseconds. You still need backups and point-in-time recovery.
| Availability target | Downtime allowed per year | Per month | What it takes |
|---|---|---|---|
| 99.9% ("three nines") | 8.8 hours | 43.8 minutes | One server and good backups can almost do it, if nothing big breaks. |
| 99.99% ("four nines") | 52.6 minutes | 4.4 minutes | Automatic failover. One manual 3 a.m. failover uses most of the year. |
| 99.999% ("five nines") | 5.3 minutes | 26 seconds | Automatic 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.
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:
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.
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.
Consul, etcd or a proxy layer tells every app where the primary is right now. Failover updates one record, not a thousand config files.
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.
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.
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.
Now let us look at how one replica set does it, and how MongoDB got from manual promotion to elections built into the database.
| When | What changed | What it fixed |
|---|---|---|
| Early versions | Master-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.
One server is one failure away from an outage. Copies help only if something decides, quickly and without two winners, which copy takes writes.
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.
For your app: MongoDB says the median time to a new primary should not exceed 12 seconds with default settings.
w: "majority" for writes you cannot lose. A w: 1 write can be rolled back after a failover.Step through it:
Running on Kubernetes? See MongoDB on Kubernetes with the Percona operator. At fleet scale, see running 1,000 databases.
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.
400.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
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" }] })
mongodb://app@db1:27017,db2:27017,db3:27017/orders?replicaSet=rs0&w=majority&retryWrites=true
electionTimeoutMillis passes. db2 calls an election for a new term.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.
| Failure | What happens | What you do |
|---|---|---|
| The primary dies | Election in about 10 to 12 s. | Nothing. Check rs.status() afterwards. |
| The primary is cut off from the others | It 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 down | No 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 oplog | It goes to RECOVERING and cannot catch up. | Resync it from scratch, then size the oplog larger. |
| Elections keep happening | Usually network flaps or an overloaded primary missing heartbeats. | Check the network and the primary's load before raising timeouts. |
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.
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.