Modernizing a Legacy MongoDB 3.x Estate: MMAPv1, WiredTiger, and the Upgrade Path Forward
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 (
mongodaborts at startup on MMAPv1 files), while MMAPv1’s collection-level write locks and uncompressed storage saturate EBSgp2burst credits and serialize concurrent writers.- Answer: Keep Feature Compatibility Version (FCV) at
4.0, convert secondaries one by one to WiredTiger via emptydbPathinitial sync ongp3EBS volumes, then executers.stepDown(60, 10)withretryWrites=trueand 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 convertgp2volumes togp3(3,000 IOPS baseline) before syncing.
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:
- Collection-Level Write Lock Serialization: In MMAPv1, concurrent writes to the same collection contend for an exclusive collection lock. Querying
db.serverStatus().globalLock.currentQueue.writersshows writer threads piling up behind the lock, saturating application connection pools and driving tail write latency upward. Scaling EC2 instances vertically (for example, fromm5.2xlargetom5.8xlarge) adds vCPUs that sit idle waiting on the same collection lock. - EBS
gp2Burst 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 EBSgp2volumes, 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. - 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.
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 Path | Mechanism | Downtime / Risk | Where It Breaks | Decision |
|---|---|---|---|---|
mongodump + mongorestore | Logical export and import into a new WiredTiger cluster | Hours of write freeze or complex dual-write cutover | Violates uptime SLAs on multi-terabyte datasets | Rejected |
| In-Place Binary Upgrade | Replace 4.0 binaries with 4.2 binaries on MMAPv1 files | Immediate startup failure | mongod 4.2 removed MMAPv1 support and halts on startup | Rejected |
| Rolling Secondary Replacement | Mixed-engine 4.0 replica set + empty dbPath initial sync | Zero planned write downtime; 2–6s election on rs.stepDown() | Requires expanded oplog window and gp3 baseline IOPS | Chosen |
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.
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.
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 tomax(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
.wttables.
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.
Phase 1: Pre-Flight Safety Verification
- Confirm Quorum and Health: Verify all members report state
1(PRIMARY) or2(SECONDARY) and that the set has an odd number of voting members. - 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. - 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 - Upgrade Storage & Snapshot: Modify target
gp2EBS volumes togp3(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:
- Audit Driver Retryability: Confirm all application connection strings include
retryWrites=trueso drivers automatically buffer and replay transient write errors during the 2-to-6-second election window. - Step Down the Primary: Run
rs.stepDown(60, 10)onNode Ato force a clean election to a WiredTiger secondary. The first argument (60) preventsNode Afrom standing for re-election for 60 seconds; the second (10) instructsNode Ato wait up to 10 seconds for an eligible secondary to catch up to the latest optime before relinquishing primary status, preventing unnecessary rollbacks. - Convert Retired
Node A: Shut downNode A, move its MMAPv1 directory to.mmapv1.bak, switchmongod.confto WiredTiger, and let it initial-sync from the new WiredTiger primary. - Verify Fleet State: Run
db.serverStatus().storageEngine.nameon every member to confirmwiredTiger, verifyglobalLock.currentQueue.writersdrops under load, and retain.mmapv1.bakdirectories 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.rscollection overwrites the starting entry before cloning finishes, the secondary aborts withOplogStartMissing(Error 120) and must restart from scratch. - AWS EBS
gp2vs.gp3Throughput Behavior: AWS EBS documentation definesgp2baseline performance at 3 IOPS per GiB (100 IOPS floor), relying on finite burst credits to reach 3,000 IOPS on volumes under 1 TiB.gp3decouples 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_targetat 80%,eviction_triggerat 95%,eviction_dirty_targetat 5%,eviction_dirty_triggerat 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
| Condition | Breaks How | Detect | Mitigate |
|---|---|---|---|
| Oplog rollover during initial sync | Primary 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 bump | Mixed-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 SIGKILL | WiredTiger 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 exhaustion | Parallel 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 stepdown | Application 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. |
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.0mixed-engine replication before any 4.2+ binary upgrade. - Initial sync is an I/O and oplog race, not a CPU problem: Provision
gp3(orio2) EBS volumes and expandoplog.rswithreplSetResizeOplogbefore converting the first secondary, orOplogStartMissing(Error 120) will reset multi-terabyte syncs. - Preserve
.mmapv1.bakdirectories for 48 hours: MovingdbPathinstead of deleting it gives operators an instant local rollback path if a converted node fails validation. - Bound
cacheSizeGBexplicitly on shared hosts: WiredTiger’s defaultmax(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=truebeforers.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
gp2burst credits, and MongoDB 4.2+ binaries refuse to start on MMAPv1 data files. - Solution: Convert replica sets online on FCV
4.0by migrating secondaries one by one via emptydbPathinitial sync ontogp3EBS volumes, followed byrs.stepDown(60, 10)and primary conversion. - Proof: Confirm
db.serverStatus().storageEngine.namereturns"wiredTiger"on all members,globalLock.currentQueue.writersdrops under load, and disk usage shrinks via Snappy compression. - Action: Run
db.serverStatus().storageEngineandrs.printReplicationInfo()across your legacy MongoDB 4.0 clusters today, convert anygp2data volumes togp3, and test the.mmapv1.baksecondary-swap runbook in staging this week.
Interactive tools for this topic