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: 1 return 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 to rollback/<collectionUUID>/removed.*.bson on recovery.
  • Answer: Deploy 3-node or 5-node data-bearing PSS topologies across distinct AZs and enforce { w: "majority", wtimeout: 5000 } plus readConcern: "majority" globally via setDefaultRWConcern.
  • Watch out: In MongoDB 5.0+, 3-node PSA (Primary-Secondary-Arbiter) sets still default implicitly to w: 1, and omitting wtimeout hangs client threads indefinitely during network partitions.

Enforce w:majority with wtimeout on PSS sets to stop rollbacks

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:

  1. Local Single-Node Acknowledgment (w: 1): Prior to MongoDB 5.0, the default write concern was w: 1 (and in 5.0+, 3-node PSA sets still fall back to w: 1 implicitly). Under w: 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.
  2. Asynchronous Replication Window: Secondaries tail local.oplog.rs across 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.
  3. Primary Crash and Minority-Primary Partition Window: If the primary terminates abruptly while holding un-replicated w: 1 operations, surviving secondaries wait electionTimeoutMillis (default 10,000 ms, after missing five 2,000 ms heartbeats) and elect a new primary with a higher term from the surviving majority. Worse, during an asymmetric network partition that isolates the old primary from the two secondaries, the old primary continues accepting w: 1 writes until its own heartbeat timeout expires and forces it to step down to SECONDARY. Throughout that up-to-10-second overlap window, clients routed to the isolated AZ receive w: 1 acknowledgments that are guaranteed to diverge from the new majority primary’s timeline.
  4. 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. Under w: "majority", by contrast, the minority primary cannot gather quorum acknowledgments during a partition, so writes fail cleanly after wtimeout rather than silently diverging.

w:1 writes acknowledge locally and vanish during RTS recovery

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

ConfigurationRollback Risk1-Node Outage BehaviorPartition BehaviorDecision
w: 1 (Legacy / PSA Implicit)High; un-replicated writes lost on crashWrites continue on primaryMinority primary accepts divergent writesRejected: Silent data loss on failover
3-Node PSA + Explicit w: "majority"Zero when both data nodes upAll writes block if 1 secondary dropsMinority/arbiter pair cannot satisfy data majorityRejected: Sacrifices HA on single node loss
PSS + w: "majority" (No wtimeout)ZeroWrites succeed via 2 of 3 data nodesClient threads hang indefinitely on partitionRejected: Exhausts app connection pools
PSS + w: "majority" + wtimeout: 5000Mathematically zeroWrites succeed via remaining majorityFails fast at 5s with WriteConcernErrorChosen: 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.

Only PSS with w:majority and wtimeout avoids loss and hangs

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.

Multi-AZ PSS consensus advances stable_timestamp on majority

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,000 ms). Missing heartbeats for electionTimeoutMillis (10,000 ms, or five missed heartbeats) triggers an election. Lowering electionTimeoutMillis speeds 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-replicated w: 1 writes 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 optime is behind their own, and each member can vote for at most one candidate per term. Setting priority: 0 on 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, whereas hidden: true (which requires priority: 0) also removes it from driver topology discovery.
  • Journal Durability (writeConcernMajorityJournalDefault): By default, writeConcernMajorityJournalDefault is true, meaning w: "majority" requires a majority of voting data-bearing nodes to flush the oplog entry to their on-disk WiredTiger journal (j: true semantics) before acknowledging. Setting it to false acknowledges 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:

  1. The replica set continuously advances stable_timestamp to the highest optime committed by a majority of voting nodes (majority commit point).
  2. When a recovering node detects diverged history, WiredTiger reverts its in-memory and on-disk B-trees directly to the checkpoint at stable_timestamp and truncates post-checkpoint journal records—typically completing in seconds regardless of collection size.
  3. MongoDB extracts the rolled-back documents and writes them to <dbPath>/rollback/<collectionUUID>/removed.<timestamp>.bson (controlled by createRollbackDataFiles, enabled by default). Operators can inspect these files with bsondump and replay idempotent upserts via mongorestore or a custom recovery script, though replaying after newer writes have occurred requires careful conflict resolution. Note that RTS is bounded by rollbackTimeLimitSecs (default 86,400 seconds, or 24 hours); if an isolated primary diverges for longer than 24 hours, automatic rollback aborts with UnrecoverableRollbackError and requires a full initial sync from a healthy member.

3. Read Concern and Write Concern Alignment

Concern SettingGuaranteeBehavior During Failover / Partition
w: 1Primary memory + journal onlyHigh rollback risk if primary crashes before oplog sync
w: "majority", j: trueCommitted to quorum + journaledZero rollback after acknowledgment; survives power loss
readConcern: "local"Reads node’s latest applied stateCan return uncommitted data later rolled back
readConcern: "majority"Reads only quorum-committed dataNever returns data that can be rolled back
readConcern: "linearizable"Live quorum check on primaryPrevents 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

Four-phase rollout enforces majority durability across drivers

  1. Phase 1 — Verify PSS Topology & Current Defaults: Run rs.conf() to confirm zero arbiters in mission-critical sets, and inspect db.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.
  2. Phase 2 — Enforce Cluster Defaults via setDefaultRWConcern: Apply majority read/write defaults globally (available since MongoDB 4.4) with a bounded wtimeout:
    db.adminCommand({
      setDefaultRWConcern: 1,
      defaultWriteConcern: { w: "majority", wtimeout: 5000 },
      defaultReadConcern: { level: "majority" }
    });
    
    Using wtimeout: 5000 ensures that if two nodes become unreachable simultaneously, writes fail fast after 5 seconds with a WriteConcernError instead of exhausting application worker threads. Rollback: revert defaultWriteConcern or adjust wtimeout via setDefaultRWConcern.
  3. Phase 3 — Lint Application URIs: Strip explicit ?w=1 or readConcernLevel=local overrides from microservice connection strings in CI/CD, because client-explicit concerns override cluster defaults. Also ensure application handlers distinguish WriteConcernError (write succeeded on primary, failed to reach majority within wtimeout) from WriteError (write rejected outright) before retrying.
  4. Phase 4 — Standardize Maintenance Stepdowns & Alerts: Require rs.stepDown(60, 15) (60s stepdown block, 15s secondaryCatchUpPeriodSecs) for planned failovers, and alert on lastRollbackExecutionTime and /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: 1 returns after local WiredTiger cache and journal buffering on the primary, whereas w: "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 to w: 1 when Arbiters > 0 and Non-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): Passing secondaryCatchUpPeriodSecs (default 10 seconds, 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 with catchUpTimeoutMillis: -1 on the newly elected primary, planned failovers complete without generating rollback BSON files or WriteConcernError bursts.
  • Retryable Writes (retryWrites=true) vs. WriteConcernError: Modern MongoDB drivers enable retryWrites=true by default, attaching a monotonically increasing txnNumber per session so single-document writes and multi-document transactions retry once automatically on transient network errors or NotWritablePrimary / InterruptedDueToReplStateChange responses during elections without creating duplicate inserts. However, WriteConcernError means the primary already applied the write locally and only the replication acknowledgment timed out past wtimeout—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

Four replica-set HA failure paths that silently break durability

Operational ActionPhysical Failure MechanismArchitectural ConsequenceSafe 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 PSAOnly 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 ConcernSecondary 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 PartitionPrimary 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: 1Partitioned 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 DiskRepeated 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: 1 for transactional data: WiredTiger Rollback to Stable Timestamp (RTS) silently discards un-replicated w: 1 writes into rollback/<collectionUUID>/removed.*.bson after a primary crash.
  • Always pair w: "majority" with wtimeout: Setting wtimeout: 5000 via setDefaultRWConcern prevents 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: 1 because forcing w: "majority" halts writes whenever the single data secondary goes down.
  • Align readConcern with writeConcern: Reading from secondaries with readConcern: "local" exposes uncommitted data; enforce readConcern: "majority" across the cluster.

What to Do Next

  • Problem: Production replica sets using w: 1 or 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, and readConcern: "majority" via setDefaultRWConcern.
  • Proof: Run db.adminCommand({ getDefaultRWConcern: 1 }) and rs.conf() to confirm PSS topology and active cluster-wide concerns.
  • Action: Audit /var/lib/mongodb/rollback/ across all nodes for historical removed.*.bson files, strip any ?w=1 overrides from application URIs, and configure PromQL alerts on lastRollbackExecutionTime this week.