When a database storage engine reaches end-of-life, the hardest engineering problem is not learning the new B-tree layout—it is migrating a live, multi-terabyte transactional replica set without dropping writes or outrunning the oplog.

TL;DR

  • Problem: MongoDB 4.2 removed MMAPv1 completely (mongod aborts at startup on MMAPv1 files), while MMAPv1’s collection-level write locks and uncompressed storage saturate EBS gp2 burst credits and serialize concurrent writers.
  • Answer: Keep Feature Compatibility Version (FCV) at 4.0, convert secondaries one by one to WiredTiger via empty dbPath initial sync on gp3 EBS volumes, then execute rs.stepDown(60, 10) with retryWrites=true and convert the retired primary.
  • Watch out: If initial sync outlasts the primary’s oplog window, the secondary aborts with OplogStartMissing (Error 120); always resize the oplog first and convert gp2 volumes to gp3 (3,000 IOPS baseline) before syncing.

Comparison of MMAPv1 collection-level write locks against WiredTiger document-level concurrency bridged via oplog.rs replication

Situation

For MongoDB’s first decade, the default storage engine was MMAPv1, which mapped data files directly into process address space via mmap() and delegated page caching and eviction to the Linux virtual memory manager. While simple, MMAPv1 wrote uncompressed BSON records into preallocated files, relocated documents when in-place updates exceeded padding, and serialized concurrent mutations behind collection-level write locks (introduced in MongoDB 3.0 to replace the older global lock).

MongoDB introduced WiredTiger in 3.0, made it the default in 3.2, and deprecated MMAPv1 in 4.0. Many production estates on AWS EC2 remained on MMAPv1 into the 4.0 lifecycle because teams deferred multi-terabyte physical rebuilds.

The hard deadline arrived in MongoDB 4.2, which removed MMAPv1 from the binary. A mongod 4.2 process refuses to start if its dbPath contains MMAPv1 data files. Because an in-place binary upgrade across 4.0 to 4.2 is impossible on MMAPv1 files, every node must be converted to WiredTiger on MongoDB 4.0 (with featureCompatibilityVersion set to "4.0") before upgrading binaries to 4.2 or later.

The Problem

Legacy MMAPv1 clusters fail under concurrent write load and block version upgrades along three measurable constraints:

  1. Collection-Level Write Lock Serialization: In MMAPv1, concurrent writes to the same collection contend for an exclusive collection lock. Querying db.serverStatus().globalLock.currentQueue.writers shows writer threads piling up behind the lock, saturating application connection pools and driving tail write latency upward. Scaling EC2 instances vertically (for example, from m5.2xlarge to m5.8xlarge) adds vCPUs that sit idle waiting on the same collection lock.
  2. EBS gp2 Burst Exhaustion (3 IOPS/GiB Baseline): Because MMAPv1 stores data and indexes uncompressed, working sets consume significantly more disk blocks than WiredTiger’s Snappy-compressed collections and prefix-compressed indexes. On AWS EBS gp2 volumes, baseline performance scales at 3 IOPS per GiB (minimum 100 IOPS), and volumes under 1 TiB rely on burst credits to reach 3,000 IOPS. Sustained dirty-page flushing or a multi-terabyte initial sync drains the burst bucket and throttles the disk to baseline.
  3. Oplog Window Ceiling During Initial Sync: A multi-terabyte initial sync clones all collections, builds all indexes, and replays concurrent oplog entries. If the sync takes longer than the primary’s oplog retention window, the oldest required oplog entry rolls over and the syncing secondary fails with OplogStartMissing (Error 120).

Consider the sizing arithmetic before starting a conversion. Suppose a replica set stores 2 TB of uncompressed MMAPv1 data and sustains an oplog generation rate of 4 GB per hour during normal business hours, rising to 10 GB per hour during batch ETL jobs. At 125 MiB/s (gp3 baseline throughput), copying and indexing 2 TB of logical BSON data requires at least 4.5 to 6 hours under ideal conditions, and 12 to 18 hours once random index-build I/O and network serialization are accounted for. A default 50 GB oplog holds only 5 hours of peak batch writes—guaranteeing OplogStartMissing if a batch job overlaps the initial sync. Sizing the oplog to 200 GB provides 20 hours of peak-rate buffer and 50 hours at steady state.

Three operational constraints: MongoDB 4.2 binary removal of MMAPv1, collection-level write lock serialization, and gp2 3 IOPS/GiB baseline throttling

Before touching any node, establish an empirical baseline across storage engine state, lock queue depth, oplog window, and filesystem free space:

mongo --eval "db.serverStatus().storageEngine"
mongo --eval "var q = db.serverStatus().globalLock.currentQueue; print('Total: ' + q.total + ' | Writers: ' + q.writers);"
mongo --eval "rs.printSecondaryReplicationInfo()"
df -h /var/lib/mongodb

How can a platform team convert a multi-terabyte MMAPv1 replica set to WiredTiger while serving live transactional traffic, without a write freeze or an OplogStartMissing abort?

Options Considered

Teams migrating off MMAPv1 evaluate three paths. Only one preserves continuous write availability without requiring dual-write application logic.

Migration PathMechanismDowntime / RiskWhere It BreaksDecision
mongodump + mongorestoreLogical export and import into a new WiredTiger clusterHours of write freeze or complex dual-write cutoverViolates uptime SLAs on multi-terabyte datasetsRejected
In-Place Binary UpgradeReplace 4.0 binaries with 4.2 binaries on MMAPv1 filesImmediate startup failuremongod 4.2 removed MMAPv1 support and halts on startupRejected
Rolling Secondary ReplacementMixed-engine 4.0 replica set + empty dbPath initial syncZero planned write downtime; 2–6s election on rs.stepDown()Requires expanded oplog window and gp3 baseline IOPSChosen

Logical export with mongodump and mongorestore produces clean WiredTiger data files, but keeping the source and target synchronized during a multi-hour dump requires either an application write freeze or custom change-stream dual-writing. In-place binary replacement is physically unsupported in MongoDB 4.2+. Rolling secondary replacement leverages MongoDB’s logical replication layer so nodes on different storage engines coexist safely inside one FCV 4.0 replica set.

Comparison of mongodump/restore, in-place binary upgrade, and rolling secondary replacement

Rolling Storage Engine Modernization Architecture

The migration relies on a core property of MongoDB replica sets: replication operates at the logical oplog.rs layer, independent of each member’s local storage engine.

In MongoDB 4.0 with featureCompatibilityVersion locked at "4.0", a replica set can run MMAPv1 on the primary and WiredTiger on one or more secondaries simultaneously. The primary records BSON mutations in local.oplog.rs; secondaries pull those operations over the network and apply them through their local storage engine API.

Mixed-engine MongoDB 4.0 replica set topology with MMAPv1 primary streaming oplog.rs to a WiredTiger secondary

WiredTiger resolves MMAPv1’s concurrency and I/O bottlenecks through three architectural changes:

  • Document-Level Concurrency Control: WiredTiger uses optimistic concurrency control and hazard pointers so multiple writer threads mutate distinct documents in the same collection concurrently without blocking on a collection-level lock. If two threads attempt to modify the exact same document simultaneously, WiredTiger detects a write conflict on one transaction and retries it internally—keeping unrelated document writes completely lock-free.
  • Dedicated Internal Cache: Instead of delegating eviction to the OS mmap() page cache, WiredTiger manages a dedicated cache defaulting to max(0.5 * (RAM - 1 GB), 256 MB), using background eviction threads to separate database working-set management from OS filesystem caching. In this dual-cache model, WiredTiger holds uncompressed, deserialized B-tree pages in its internal cache for fast query execution, while the Linux page cache holds compressed disk blocks read from EBS.
  • Block and Prefix Compression: WiredTiger compresses collection blocks (Snappy by default, or zstd/zlib) and applies prefix compression to B-tree indexes, substantially reducing on-disk footprint and EBS write amplification compared to uncompressed MMAPv1 files. Because MMAPv1 preallocates data files in power-of-two increments up to 2 GB per file and leaves fragmented free lists after deletes, converting via initial sync also compacts dead space into fresh, contiguous WiredTiger .wt tables.

Target mongod.conf configuration for converted nodes:

storage:
  dbPath: /var/lib/mongodb
  engine: wiredTiger
  wiredTiger:
    engineConfig:
      cacheSizeGB: 14  # Explicitly bounded at ~50% of (RAM - 1 GB)
    collectionConfig:
      blockCompressor: snappy
    indexConfig:
      prefixCompression: true

How It Rolls Out

Execute the conversion in four gated phases so voting quorum is preserved and rollback remains instant until the final cleanup.

Four-phase rolling conversion runbook with pre-flight, secondary retirement, initial sync polling, and primary stepdown

Phase 1: Pre-Flight Safety Verification

  1. Confirm Quorum and Health: Verify all members report state 1 (PRIMARY) or 2 (SECONDARY) and that the set has an odd number of voting members.
  2. Lock Feature Compatibility Version: Confirm FCV is "4.0" (db.adminCommand({ getParameter: 1, featureCompatibilityVersion: 1 })). Never bump FCV to "4.2" while any MMAPv1 member remains.
  3. Expand Oplog Window: Inspect rs.printReplicationInfo(). If the oplog window is smaller than 3x the expected initial sync duration, resize it online (value in MB):
    db.adminCommand({ replSetResizeOplog: 1, size: Double(51200) }); // 50 GB
    
  4. Upgrade Storage & Snapshot: Modify target gp2 EBS volumes to gp3 (delivering a consistent 3,000 IOPS and 125 MiB/s baseline independent of volume size, with higher provisioned IOPS if needed) and take EBS snapshots across the set.

Validation gate: Confirm snapshot completion and verify rs.printReplicationInfo() shows sufficient oplog hours. Rollback: None required; no node configuration has changed.

Phase 2: Non-Destructive Secondary Retirement

Target one secondary (Node C) while the remaining secondary (Node B) preserves voting quorum with the primary (Node A):

mongo --eval "db.adminCommand({ shutdown: 1 })"
sudo systemctl stop mongod
DB_PATH=$(grep dbPath /etc/mongod.conf | awk '{print $2}')
sudo mv ${DB_PATH} ${DB_PATH}.mmapv1.bak
sudo mkdir -p ${DB_PATH}
sudo chown -R mongodb:mongodb ${DB_PATH}

Moving dbPath to .mmapv1.bak rather than running rm -rf preserves an instant local rollback path if the host fails to sync or hits configuration errors. Update /etc/mongod.conf to engine: wiredTiger and start mongod.

Phase 3: Initial Sync Polling

Because dbPath is empty, mongod enters STARTUP2 and initiates a full initial sync from the primary. Monitor structured progress via db.adminCommand({ replSetGetStatus: 1 }).initialSyncStatus (appliedOps, bytesCopied, totalInitialSyncTime). Wait until the node transitions through RECOVERING to SECONDARY and rs.printSecondaryReplicationInfo() reports zero lag, then repeat Phase 2 and Phase 3 for Node B.

For fleets with dozens of clusters, automate Phase 2 and Phase 3 in Ansible using community.mongodb.mongodb_status (poll sets max queries, interval sets seconds between polls):

# Illustrative: adapt the `until` condition to the fields your community.mongodb collection version returns
- name: Wait for secondary to complete initial sync
  community.mongodb.mongodb_status:
    login_host: "localhost"
    poll: 360
    interval: 10
  register: node_status
  until: node_status.state_str == "SECONDARY"

Rollback: If a secondary fails mid-sync, stop mongod, restore ${DB_PATH}.mmapv1.bak to ${DB_PATH}, revert mongod.conf, and restart.

Phase 4: Controlled Primary Stepdown and Final Conversion

Once all secondaries run WiredTiger with zero replication lag:

  1. Audit Driver Retryability: Confirm all application connection strings include retryWrites=true so drivers automatically buffer and replay transient write errors during the 2-to-6-second election window.
  2. Step Down the Primary: Run rs.stepDown(60, 10) on Node A to force a clean election to a WiredTiger secondary. The first argument (60) prevents Node A from standing for re-election for 60 seconds; the second (10) instructs Node A to wait up to 10 seconds for an eligible secondary to catch up to the latest optime before relinquishing primary status, preventing unnecessary rollbacks.
  3. Convert Retired Node A: Shut down Node A, move its MMAPv1 directory to .mmapv1.bak, switch mongod.conf to WiredTiger, and let it initial-sync from the new WiredTiger primary.
  4. Verify Fleet State: Run db.serverStatus().storageEngine.name on every member to confirm wiredTiger, verify globalLock.currentQueue.writers drops under load, and retain .mmapv1.bak directories for 48 hours before reclaiming disk.

In Practice

The operational mechanics of this migration are governed by documented MongoDB and AWS EBS behavior:

  • MongoDB Initial Sync & Oplog Mechanics: MongoDB’s initial sync documentation specifies that a syncing node clones all databases, builds indexes, and then applies oplog entries recorded since the clone began. If the primary’s capped oplog.rs collection overwrites the starting entry before cloning finishes, the secondary aborts with OplogStartMissing (Error 120) and must restart from scratch.
  • AWS EBS gp2 vs. gp3 Throughput Behavior: AWS EBS documentation defines gp2 baseline performance at 3 IOPS per GiB (100 IOPS floor), relying on finite burst credits to reach 3,000 IOPS on volumes under 1 TiB. gp3 decouples IOPS from capacity and provides 3,000 IOPS and 125 MiB/s continuously without burst credits, preventing mid-sync I/O throttling.
  • WiredTiger Eviction & History Store Evolution: In modern MongoDB releases (7.0 and 8.0), WiredTiger continues to rely on explicit cache eviction thresholds (eviction_target at 80%, eviction_trigger at 95%, eviction_dirty_target at 5%, eviction_dirty_trigger at 20%) and externalizes old MVCC document versions into the History Store (WiredTigerHS.wt, introduced in 4.4) so long-running transactions do not pin active working-set pages in memory.

I have not executed this conversion across a multi-cluster production fleet personally; the runbook sequence and gp3 pre-provisioning steps reflect the documented behavior of MongoDB 4.0 initial sync and AWS EBS volume classes.

Where It Breaks

ConditionBreaks HowDetectMitigate
Oplog rollover during initial syncPrimary overwrites starting oplog entry; secondary aborts with OplogStartMissing (Error 120).mongod log OplogStartMissing and STARTUP2 restart loop.Run replSetResizeOplog before Phase 2 to guarantee >3x sync duration headroom.
Premature FCV 4.2 bumpMixed-engine set rejects or breaks MMAPv1 nodes that cannot process 4.2 catalog metadata.setFeatureCompatibilityVersion error or node crash on binary swap.Keep FCV at "4.0" until serverStatus().storageEngine.name is wiredTiger on 100% of nodes.
Linux OOM killer SIGKILLWiredTiger cache + OS page cache + monitoring agents exceed host RAM.dmesg shows Out of memory: Killed process (mongod).Set cacheSizeGB to at most 0.5 * (RAM - 1 GB) and leave headroom for OS and agents.
EBS gp2 burst credit exhaustionParallel index builds drain burst bucket; disk throttles to 3 IOPS/GiB and lag grows.CloudWatch VolumeBurstBalance hits 0; node stalls in RECOVERING.Migrate volumes live from gp2 to gp3 (3,000+ IOPS) before starting Phase 2.
Missing retryWrites=true on stepdownApplication drivers fail writes during the 2–6s election window after rs.stepDown().Client NotWritablePrimary / NotMaster exceptions in app logs.Audit all connection strings for retryWrites=true before executing Phase 4.

Failure-path overlay showing OplogStartMissing Error 120, Linux OOM killer, gp2 throttling, and stepdown write errors

Key Takeaways

  • MMAPv1 must be retired on MongoDB 4.0: Because MongoDB 4.2 removed MMAPv1 from the binary, every node must convert to WiredTiger via FCV 4.0 mixed-engine replication before any 4.2+ binary upgrade.
  • Initial sync is an I/O and oplog race, not a CPU problem: Provision gp3 (or io2) EBS volumes and expand oplog.rs with replSetResizeOplog before converting the first secondary, or OplogStartMissing (Error 120) will reset multi-terabyte syncs.
  • Preserve .mmapv1.bak directories for 48 hours: Moving dbPath instead of deleting it gives operators an instant local rollback path if a converted node fails validation.
  • Bound cacheSizeGB explicitly on shared hosts: WiredTiger’s default max(0.5 * (RAM - 1 GB), 256 MB) assumes a dedicated host; account for OS page cache and monitoring agents to avoid OOM kills.
  • Verify retryWrites=true before rs.stepDown(): Driver-level retryable writes absorb the 2-to-6-second primary election window without surfacing write errors to callers.

What to Do Next

  • Problem: MMAPv1 collection-level write locks serialize concurrent writers, uncompressed files exhaust gp2 burst credits, and MongoDB 4.2+ binaries refuse to start on MMAPv1 data files.
  • Solution: Convert replica sets online on FCV 4.0 by migrating secondaries one by one via empty dbPath initial sync onto gp3 EBS volumes, followed by rs.stepDown(60, 10) and primary conversion.
  • Proof: Confirm db.serverStatus().storageEngine.name returns "wiredTiger" on all members, globalLock.currentQueue.writers drops under load, and disk usage shrinks via Snappy compression.
  • Action: Run db.serverStatus().storageEngine and rs.printReplicationInfo() across your legacy MongoDB 4.0 clusters today, convert any gp2 data volumes to gp3, and test the .mmapv1.bak secondary-swap runbook in staging this week.