A MongoDB replica set is the minimum production deployment — a single mongod is fine for development but loses all data on the host crash, and the recommended production topology is three voting members across three failure domains. This article walks the three-node bootstrap with keyfile authentication, the write-concern settings that make durability real, and the verification queries that confirm the primary election worked.
How to verify
On any member of a working replica set:
// Connect with mongosh
rs.status()
// Confirm the topology
rs.conf()
// Where am I in the topology
db.hello()
// Replication lag from the primary's perspective
rs.printSecondaryReplicationInfo()
rs.status() lists every member with its state (PRIMARY, SECONDARY, ARBITER if present), its uptime, and its optimeDate. Healthy replicas have optimeDate within seconds of the primary.
What’s happening
A replica set is a group of mongod processes that maintain the same data via an asynchronous replication protocol. One member is the primary (accepts writes), the others are secondaries (read-only, replicate from the primary). On primary failure, the surviving members hold an election; whichever gets a majority of votes becomes the new primary. With three voting members, the set can lose one and still elect.
Each write is replicated via the primary’s oplog (operations log, a capped collection in the local database). Secondaries tail the oplog over a long-polling cursor and apply each operation. The default write concern is {w: 1} — the primary acknowledges the write as soon as it has it locally, regardless of whether secondaries have replicated. For durability that survives primary loss, write with {w: "majority"}.
Keyfile authentication is the simplest way to mutually authenticate members of a replica set. Every member reads the same secret file at startup; an attacker without the keyfile cannot impersonate a member. In production, x.509 certificate authentication is preferred — see the MongoDB security docs — but keyfile is what most teams start with.
The procedure
-
Generate a keyfile. A random 1024-character base64 string is the standard pattern.
openssl rand -base64 756 | sudo tee /etc/mongodb-keyfile > /dev/null sudo chmod 400 /etc/mongodb-keyfile sudo chown mongodb:mongodb /etc/mongodb-keyfileCopy this same file to each of the three hosts. The contents must be byte-identical.
-
Configure each member’s
/etc/mongod.conf. Three hosts, each with its own hostname/IP, all listening on 27017.# /etc/mongod.conf on mongo01.internal security: authorization: enabled keyFile: /etc/mongodb-keyfile replication: replSetName: rs0 net: port: 27017 bindIp: 127.0.0.1,10.0.0.5 # localhost + this host's private IP storage: dbPath: /var/lib/mongodb wiredTiger: engineConfig: cacheSizeGB: 8Repeat on
mongo02.internal(bindIp 10.0.0.6) andmongo03.internal(bindIp 10.0.0.7). -
Restart all three nodes.
sudo systemctl restart mongod sudo systemctl status mongod --no-pager -
Initiate the replica set from one node (this node will be elected initial primary).
mongosh rs.initiate({ _id: "rs0", members: [ { _id: 0, host: "mongo01.internal:27017", priority: 2 }, { _id: 1, host: "mongo02.internal:27017", priority: 1 }, { _id: 2, host: "mongo03.internal:27017", priority: 1 } ] })Different priorities make the initial primary more likely to be re-elected after a failover-and-recovery cycle. Use equal priorities if all three nodes are functionally equivalent.
-
Create the admin user via the primary.
use admin db.createUser({ user: "admin", pwd: "strong-password", roles: [ { role: "userAdminAnyDatabase", db: "admin" }, { role: "clusterAdmin", db: "admin" } ] })Replica set admin users only need to be created on the primary; the change replicates.
-
Verify the election succeeded.
rs.status() // Look for one member in PRIMARY state, two in SECONDARY -
Test failover. Stop the current primary’s mongod and watch the others elect a new one.
# On the current primary sudo systemctl stop mongod # On another node, watch the election mongosh rs.status() # Within 10-12 seconds, a SECONDARY becomes PRIMARYRestart the stopped node — it joins as SECONDARY and starts catching up via the oplog.
-
Configure the application to use the replica set URI. Drivers need every member listed so they can route reads/writes and follow elections.
mongodb://orderapp:strong-password@mongo01.internal:27017,mongo02.internal:27017,mongo03.internal:27017/orders?replicaSet=rs0&authSource=orders&w=majority&readPreference=primaryPreferred -
Set write concern to majority for important data.
db.orders.insertOne( { customer: "abc", total: 100 }, { writeConcern: { w: "majority", wtimeout: 5000 } } )w: "majority"means the primary waits for confirmation from a majority of voting members before returning success — survives the loss of any single node without data loss. -
Right-size the oplog. Default oplog size is 5% of free disk or 50 GB, whichever is smaller. For high-write workloads it may need to be bigger — a too-small oplog rolls over before secondaries can catch up after downtime.
db.adminCommand({ replSetResizeOplog: 1, size: 16384 }) // 16 GB
Common pitfalls
- Keyfile permissions wrong (mode anything other than
400or600, or owned by a different user) — mongod refuses to start. - Hostname resolution differences between members — initiating with
localhostworks on the first node but breaks for the others. Always use stable DNS or/etc/hostsentries. - Primary election needs a majority of voting members; with 2 nodes (one of which is the primary), losing the secondary stalls writes. Always run odd numbers of voting members; if cost forces two, add an arbiter as a third vote.
- Write concern
{w: 1}(default) acknowledges as soon as the primary has the write — if the primary crashes before replication, that write is lost. For financial workloads, always usemajority. - A secondary whose oplog is older than the primary’s oldest entry cannot catch up — it requires a full resync (delete dataPath, restart). Right-size the oplog to give yourself a generous re-sync window.
In the engagements we run, MongoDB replica sets are three-node minimum, span three failure domains (separate racks, zones, or availability zones), and have a documented operator runbook for the failover and the rare two-node-failure scenario. We monitor with the MongoDB Prometheus exporter and alert on election count, oplog lag, and primary instability. Operated under Managed Operations — and the broader HA pattern is covered under Clustered Environments.