MongoDB Replica Set HA: Elections, Read Preference, Write Concern, and Rollbacks
When a primary node crashes, a high-availability failover can silently erase newly written data if application write durability and cluster election quorums disagree on consensus.
TL;DR
- Problem: Writes acknowledged with
w: 1return from the primary’s local WiredTiger cache and journal before secondaries replicate the oplog; if the primary crashes before replication, WiredTiger Rollback to Stable Timestamp (RTS) reverts those writes torollback/<collectionUUID>/removed.*.bsonon recovery.- Answer: Deploy 3-node or 5-node data-bearing PSS topologies across distinct AZs and enforce
{ w: "majority", wtimeout: 5000 }plusreadConcern: "majority"globally viasetDefaultRWConcern.- Watch out: In MongoDB 5.0+, 3-node PSA (Primary-Secondary-Arbiter) sets still default implicitly to
w: 1, and omittingwtimeouthangs client threads indefinitely during network partitions.
Production Scope: MongoDB 4.4 – 8.0 on AWS EC2 Multi-AZ
Situation
Self-managed MongoDB replica sets on AWS EC2 achieve high availability by distributing voting members across three distinct Availability Zones (such as us-east-1a, us-east-1b, and us-east-1c). When the primary fails due to hypervisor termination, kernel panic, or AZ isolation, surviving secondaries detect missed heartbeats and elect a new leader automatically within seconds.
In transactional workloads—payment ledgers, billing state machines, and order fulfillment pipelines—a subtle durability gap appears between write acknowledgment and failover consensus. If an application driver considers a write committed before a majority of voting data nodes have recorded it in their oplog, an abrupt primary crash creates a divergent timeline. Even a brief cross-AZ replication delay of a few milliseconds is enough for hundreds of w: 1 writes to exist only on the failed primary’s local disk. When the failed primary reboots and rejoins the replica set, WiredTiger physically rolls back the un-replicated transactions, leaving upstream services unaware that acknowledged writes were discarded.
At the same time, fixing durability naively—by enabling w: "majority" without a timeout, or by deploying a Primary-Secondary-Arbiter (PSA) topology to save EC2 instance costs—introduces availability outages of its own during single-node restarts or network partitions.
The Problem
Mechanics of Phantom Data Loss and Rollbacks
Legacy w: 1 acknowledgments and misconfigured topologies expose four compounding failure constraints:
- Local Single-Node Acknowledgment (
w: 1): Prior to MongoDB 5.0, the default write concern wasw: 1(and in 5.0+, 3-node PSA sets still fall back tow: 1implicitly). Underw: 1, the primary acknowledges writes as soon as they mutate its local WiredTiger cache and journal buffer, returning before any secondary pulls the oplog entry. - Asynchronous Replication Window: Secondaries tail
local.oplog.rsacross cross-AZ VPC links. Network transit time, OS socket buffering, and secondary oplog applier queuing create a replication lag window of several milliseconds (or seconds under heavy write bursts) between primary commit and secondary application. - Primary Crash and Minority-Primary Partition Window: If the primary terminates abruptly while holding un-replicated
w: 1operations, surviving secondaries waitelectionTimeoutMillis(default10,000ms, after missing five 2,000 ms heartbeats) and elect a new primary with a highertermfrom the surviving majority. Worse, during an asymmetric network partition that isolates the old primary from the two secondaries, the old primary continues acceptingw: 1writes until its own heartbeat timeout expires and forces it to step down toSECONDARY. Throughout that up-to-10-second overlap window, clients routed to the isolated AZ receivew: 1acknowledgments that are guaranteed to diverge from the new majority primary’s timeline. - Rollback to Stable Timestamp (RTS): When the crashed or partitioned former primary reconnects, its replication handshake detects divergent oplog entries absent from the new primary’s timeline. WiredTiger executes Rollback to Stable Timestamp (RTS), reverting memory and disk state to the last majority-committed checkpoint (
stable_timestamp), truncating the journal, and dumping the discarded documents under<dbPath>/rollback/<collectionUUID>/removed.<timestamp>.bson. Underw: "majority", by contrast, the minority primary cannot gather quorum acknowledgments during a partition, so writes fail cleanly afterwtimeoutrather than silently diverging.
The core architectural question is: How can platform engineers guarantee zero post-acknowledgment rollbacks across multi-AZ failovers without hanging application thread pools during network partitions or relying on per-service driver configs?
Options Considered
| Configuration | Rollback Risk | 1-Node Outage Behavior | Partition Behavior | Decision |
|---|---|---|---|---|
w: 1 (Legacy / PSA Implicit) | High; un-replicated writes lost on crash | Writes continue on primary | Minority primary accepts divergent writes | Rejected: Silent data loss on failover |
3-Node PSA + Explicit w: "majority" | Zero when both data nodes up | All writes block if 1 secondary drops | Minority/arbiter pair cannot satisfy data majority | Rejected: Sacrifices HA on single node loss |
PSS + w: "majority" (No wtimeout) | Zero | Writes succeed via 2 of 3 data nodes | Client threads hang indefinitely on partition | Rejected: Exhausts app connection pools |
PSS + w: "majority" + wtimeout: 5000 | Mathematically zero | Writes succeed via remaining majority | Fails fast at 5s with WriteConcernError | Chosen: Safe consensus with bounded tail |
Using w: 1 trades away durability for sub-millisecond local acks, while a 3-node PSA topology forces a bad choice between silent w: 1 rollbacks or a total write outage whenever the lone secondary restarts. In a 3-node PSA set, an arbiter holds a vote for elections (1 vote, 0 data) but stores no oplog or collection data; therefore, w: "majority" requires both the primary and the single data secondary to acknowledge every write. If that secondary undergoes OS patching or EBS maintenance, all w: "majority" writes block. Running a 3-node or 5-node data-bearing PSS set with w: "majority" and an explicit wtimeout eliminates rollbacks while tolerating single-node failures and bounding partition stalls.
For read scaling, readPreference and readConcern must be chosen together: routing reads to secondaries with readConcern: "local" can return un-committed oplog entries that later roll back on primary failover, whereas readConcern: "majority" ensures every returned document is durable across a quorum. When a workflow requires strict linearizability—guaranteeing it never reads stale data even from a partitioned primary during the 10-second electionTimeoutMillis window—use readConcern: "linearizable" on primary reads, accepting the extra majority heartbeat round-trip.
The Durability Architecture: Consensus, Elections, and Rollbacks
MongoDB replica sets coordinate durability and leadership via Protocol Version 1 (pv1)—a Raft-derived consensus protocol—paired with WiredTiger’s stable_timestamp checkpointing.
flowchart TD
Client["Application Client — Financial Service"] -->|Write Request| Primary["Node A Primary — us-east-1a"]
Primary -->|Oplog Sync| SecB["Node B Secondary — us-east-1b"]
Primary -->|Oplog Sync| SecC["Node C Secondary — us-east-1c"]
SecB -->|Oplog ACK| Primary
SecC -->|Oplog ACK| Primary
Primary -->|w majority Satisfied| ClientAck["Client Acknowledged — Durable"]
Primary -.->|Sudden Crash| DeadNode["Node A Down"]
SecB & SecC -->|pv1 Election| NewPrimary["Node B Promoted to Primary"]
DeadNode -->|Reboots| Rejoin["Node A Reconnects"]
Rejoin -->|Oplog Diverged| RTS["WiredTiger Rollback to Stable Timestamp"]
RTS --> DumpBSON["Dump removed.timestamp.bson"]
1. Protocol Version 1 (pv1) Election Mechanics
- Heartbeats and Timeout: Nodes exchange heartbeats every
heartbeatIntervalMillis(2,000ms). Missing heartbeats forelectionTimeoutMillis(10,000ms, or five missed heartbeats) triggers an election. LoweringelectionTimeoutMillisspeeds up failover detection, but setting it too aggressively (under 5,000 ms) across AWS AZs risks spurious elections during transient VPC jitter or Garbage Collection / checkpoint I/O pauses. - Pre-Election Catch-Up: A newly elected primary attempts to catch up any remaining oplog entries from other visible members up to
catchUpTimeoutMillis(default-1, meaning wait indefinitely until caught up or interrupted) before opening for writes. This preserves un-replicatedw: 1writes when a secondary with a slightly older optime wins an election, at the cost of delaying write availability until sync completes. - Quorum Formula, Votes, and Priorities: An election requires strict majority $\lfloor N / 2 \rfloor + 1$ of voting members (2 of 3 nodes, or 3 of 5 nodes), with a hard ceiling of 7 voting members across up to 50 total replica set members. Voters reject candidates whose term or last
optimeis behind their own, and each member can vote for at most one candidate per term. Settingpriority: 0on a dedicated analytics or cross-region backup secondary prevents it from ever winning an election while still allowing it to hold a vote if needed, whereashidden: true(which requirespriority: 0) also removes it from driver topology discovery. - Journal Durability (
writeConcernMajorityJournalDefault): By default,writeConcernMajorityJournalDefaultistrue, meaningw: "majority"requires a majority of voting data-bearing nodes to flush the oplog entry to their on-disk WiredTiger journal (j: truesemantics) before acknowledging. Setting it tofalseacknowledges from secondaries’ in-memory WiredTiger cache, which survives single-node crashes but risks data loss if a simultaneous multi-AZ power or hypervisor event terminates a majority before their 100 ms journal sync.
2. WiredTiger Rollback to Stable Timestamp (RTS)
Before MongoDB 4.0, rollbacks were logical—requiring the recovering node to fetch documents across the network and replay inverse operations, often taking hours on multi-terabyte collections and hitting a 300 MB rollback data ceiling. Since MongoDB 4.0, WiredTiger delegates rollbacks to RTS:
- The replica set continuously advances
stable_timestampto the highest optime committed by a majority of voting nodes (majoritycommit point). - When a recovering node detects diverged history, WiredTiger reverts its in-memory and on-disk B-trees directly to the checkpoint at
stable_timestampand truncates post-checkpoint journal records—typically completing in seconds regardless of collection size. - MongoDB extracts the rolled-back documents and writes them to
<dbPath>/rollback/<collectionUUID>/removed.<timestamp>.bson(controlled bycreateRollbackDataFiles, enabled by default). Operators can inspect these files withbsondumpand replay idempotent upserts viamongorestoreor a custom recovery script, though replaying after newer writes have occurred requires careful conflict resolution. Note that RTS is bounded byrollbackTimeLimitSecs(default86,400seconds, or 24 hours); if an isolated primary diverges for longer than 24 hours, automatic rollback aborts withUnrecoverableRollbackErrorand requires a full initial sync from a healthy member.
3. Read Concern and Write Concern Alignment
| Concern Setting | Guarantee | Behavior During Failover / Partition |
|---|---|---|
w: 1 | Primary memory + journal only | High rollback risk if primary crashes before oplog sync |
w: "majority", j: true | Committed to quorum + journaled | Zero rollback after acknowledgment; survives power loss |
readConcern: "local" | Reads node’s latest applied state | Can return uncommitted data later rolled back |
readConcern: "majority" | Reads only quorum-committed data | Never returns data that can be rolled back |
readConcern: "linearizable" | Live quorum check on primary | Prevents stale reads from a partitioned minority primary |
Diagnostic Telemetry: Optime Audit and PromQL Alerts
Audit replication lag and active cluster default concerns in mongosh:
const status = rs.status();
const primary = status.members.find((m) => m.stateStr === "PRIMARY");
print("term=", status.term, "primary=", primary?.name);
status.members.filter((m) => m.stateStr === "SECONDARY").forEach((m) => {
print(m.name, "lagSecs=", ((primary.optimeDate - m.optimeDate) / 1000).toFixed(3));
});
printjson(db.adminCommand({ getDefaultRWConcern: 1 }));
Monitor replication lag, RTS rollback events, and election term churn in Prometheus:
groups:
- name: mongodb_ha_durability_alerts
rules:
- alert: MongoSecondaryReplicationLagCritical
expr: mongodb_mongod_replset_member_replication_lag{state="SECONDARY"} > 10
for: 1m
labels: { severity: critical }
# The two metric names below vary by exporter version; confirm them against your exporter's /metrics output
- alert: MongoRollbackEventDetected
expr: increase(mongodb_ss_metrics_repl_stateTransition_lastRollbackExecutionTime[5m]) > 0
labels: { severity: critical }
- alert: MongoElectionTermChurn
expr: increase(mongodb_ss_repl_election_successful[10m]) > 2
labels: { severity: warning }
Safe Rollback Forensics & Recovery (mongo_rollback_auditor.py)
In MongoDB 4.4+, rollback files reside in UUID subdirectories (<dbPath>/rollback/<collectionUUID>/removed.<timestamp>.bson). Walk subdirectories recursively and resolve UUIDs against listCollections (or grep "rollback file" /var/log/mongodb/mongod.log) before replaying:
#!/usr/bin/env python3
import argparse, os, bson
from pymongo import MongoClient
def audit_rollback(rollback_dir, target_uri, dry_run):
client = MongoClient(target_uri, serverSelectionTimeoutMS=5000)
uuid_map = {}
for db_name in client.list_database_names():
if db_name in ("admin", "local", "config"):
continue
for c in client[db_name].list_collections():
u = c.get("info", {}).get("uuid")
if u:
uuid_map[str(u)] = (db_name, c["name"])
for root, _, files in os.walk(rollback_dir):
for fname in sorted(files):
if not fname.endswith(".bson"):
continue
fpath = os.path.join(root, fname)
coll_uuid = os.path.basename(root)
ns = uuid_map.get(coll_uuid)
with open(fpath, "rb") as f:
docs = bson.decode_all(f.read())
print(f"file={fpath} ns={ns} docs={len(docs)}")
if not dry_run and ns:
coll = client[ns[0]][ns[1]]
for d in docs:
coll.replace_one({"_id": d["_id"]}, d, upsert=True)
How It Rolls Out
- Phase 1 — Verify PSS Topology & Current Defaults: Run
rs.conf()to confirm zero arbiters in mission-critical sets, and inspectdb.adminCommand({ getDefaultRWConcern: 1 }). Verify all three data-bearing members reside in separate AWS Availability Zones so a single AZ outage cannot take down a voting majority. - Phase 2 — Enforce Cluster Defaults via
setDefaultRWConcern: Apply majority read/write defaults globally (available since MongoDB 4.4) with a boundedwtimeout:
Usingdb.adminCommand({ setDefaultRWConcern: 1, defaultWriteConcern: { w: "majority", wtimeout: 5000 }, defaultReadConcern: { level: "majority" } });wtimeout: 5000ensures that if two nodes become unreachable simultaneously, writes fail fast after 5 seconds with aWriteConcernErrorinstead of exhausting application worker threads. Rollback: revertdefaultWriteConcernor adjustwtimeoutviasetDefaultRWConcern. - Phase 3 — Lint Application URIs: Strip explicit
?w=1orreadConcernLevel=localoverrides from microservice connection strings in CI/CD, because client-explicit concerns override cluster defaults. Also ensure application handlers distinguishWriteConcernError(write succeeded on primary, failed to reach majority withinwtimeout) fromWriteError(write rejected outright) before retrying. - Phase 4 — Standardize Maintenance Stepdowns & Alerts: Require
rs.stepDown(60, 15)(60s stepdown block, 15ssecondaryCatchUpPeriodSecs) for planned failovers, and alert onlastRollbackExecutionTimeand/var/lib/mongodb/rollback/growth via Full Time Diagnostic Capture (FTDC) and Prometheus.
In Practice
Documented MongoDB consensus and storage engine behaviors explain the exact latency and availability tradeoffs of majority durability:
- Cross-AZ Latency Cost of
w: "majority": Per MongoDB’s replication mechanics,w: 1returns after local WiredTiger cache and journal buffering on the primary, whereasw: "majority"waits for at least one cross-AZ secondary (in a 3-node PSS set) to receive, journal/apply, and acknowledge the oplog batch. That adds at least one cross-AZ network round-trip time to write latency—an unavoidable physical cost for zero-rollback durability. - PSA Topology Implicit Fallback in MongoDB 5.0+: While MongoDB 5.0 changed the default write concern to
w: "majority"for PSS replica sets, it intentionally falls back tow: 1whenArbiters > 0andNon-Arbiters <= Majority of Voting Nodes(such as a 3-node PSA set). Otherwise, losing the lone secondary would leave only 1 data-bearing node and halt all writes. - Coordinated Maintenance Stepdowns (
rs.stepDown): PassingsecondaryCatchUpPeriodSecs(default10seconds, e.g.,rs.stepDown(60, 15)) instructs the primary to pause new writes and wait for an eligible secondary to synchronize its optime before stepping down. Combined withcatchUpTimeoutMillis: -1on the newly elected primary, planned failovers complete without generating rollback BSON files orWriteConcernErrorbursts. - Retryable Writes (
retryWrites=true) vs.WriteConcernError: Modern MongoDB drivers enableretryWrites=trueby default, attaching a monotonically increasingtxnNumberper session so single-document writes and multi-document transactions retry once automatically on transient network errors orNotWritablePrimary/InterruptedDueToReplStateChangeresponses during elections without creating duplicate inserts. However,WriteConcernErrormeans the primary already applied the write locally and only the replication acknowledgment timed out pastwtimeout—retrying blindly at the application layer without idempotency keys can still duplicate side effects if the write was not tagged as a driver-managed retryable write.
Where It Breaks
| Operational Action | Physical Failure Mechanism | Architectural Consequence | Safe Mitigation Protocol |
|---|---|---|---|
Omitting wtimeout with w: "majority" | Network partition prevents quorum from acknowledging writes. | Primary holds client connections open indefinitely; app pools exhaust. | Always set wtimeout: 5000 and handle WriteConcernError cleanly. |
Explicit w: "majority" on 3-Node PSA | Only 2 data nodes exist; 1 arbiter cannot store oplog data. | Losing the single data secondary halts all majority writes. | Replace arbiters with 3-node or 5-node data-bearing PSS topologies. |
Client URI Override (?w=1) | Microservice explicitly sets w=1 in its connection string. | Overrides setDefaultRWConcern and reintroduces rollback risk. | Lint connection strings in CI/CD to reject w=1 overrides. |
secondary Read + local Concern | Secondary returns local uncommitted oplog state. | Clients observe writes that later roll back on primary failover. | Enforce readConcern: "majority" or route critical reads to primary. |
linearizable Read During Partition | Primary cannot complete live majority heartbeat check. | Fails reads after maxTimeMS during inter-AZ packet loss. | Reserve linearizable for strict leader-verification checks only. |
Minority Primary Accepting w: 1 | Partitioned primary continues accepting w: 1 for up to 10s. | Writes diverge from new majority primary and roll back on rejoin. | Enforce w: "majority" so minority primaries cannot ack writes. |
| Rollback BSON Filling Disk | Repeated failovers dump GBs under dbPath/rollback/. | Exhausts EBS volume and crashes mongod. | Alert on RTS metrics and archive/purge inspected removed.*.bson files. |
Uncoordinated rs.stepDown() | Stepping down without allowing secondary oplog catch-up. | Forces election retries and transient WriteConcernError spikes. | Always pass secondaryCatchUpPeriodSecs (rs.stepDown(60, 15)). |
Key Takeaways
- Never rely on
w: 1for transactional data: WiredTiger Rollback to Stable Timestamp (RTS) silently discards un-replicatedw: 1writes intorollback/<collectionUUID>/removed.*.bsonafter a primary crash. - Always pair
w: "majority"withwtimeout: Settingwtimeout: 5000viasetDefaultRWConcernprevents application connection pools from hanging indefinitely during network partitions. - Avoid 3-node PSA topologies in production: Even in MongoDB 5.0+, 3-node PSA sets fall back implicitly to
w: 1because forcingw: "majority"halts writes whenever the single data secondary goes down. - Align
readConcernwithwriteConcern: Reading from secondaries withreadConcern: "local"exposes uncommitted data; enforcereadConcern: "majority"across the cluster.
What to Do Next
- Problem: Production replica sets using
w: 1or PSA topologies risk silent post-failover data loss via WiredTiger RTS. - Solution: Standardize on 3-node or 5-node PSS topologies and enforce
w: "majority",wtimeout: 5000, andreadConcern: "majority"viasetDefaultRWConcern. - Proof: Run
db.adminCommand({ getDefaultRWConcern: 1 })andrs.conf()to confirm PSS topology and active cluster-wide concerns. - Action: Audit
/var/lib/mongodb/rollback/across all nodes for historicalremoved.*.bsonfiles, strip any?w=1overrides from application URIs, and configure PromQL alerts onlastRollbackExecutionTimethis week.