WiredTiger Under Pressure: Cache, Eviction, Checkpoints, Journaling, and the History Store
In a write-heavy database, memory is a write shock absorber—when dirty-page generation outpaces physical EBS bandwidth, WiredTiger invokes flow control, conscripts application threads into synchronous disk I/O, and drains all concurrent write tickets.
TL;DR
- Problem: Periodic 60-second write latency cliffs occur when checkpoint flushing plus dirty-page accumulation saturates
gp3baseline bandwidth (3,000 IOPS / 125 MiB/s), pushing dirty cache past the20%eviction_dirty_triggerand stalling all write tickets.- Answer: Scale
gp3IOPS and throughput online withaws ec2 modify-volume(ensuring the EC2 instance’s own EBS bandwidth exceeds the volume target), keepsyncdelayat its60-second default, and isolate long-running reads off the primary soWiredTigerHS.wtcan prune.- Watch out: Expanding
cacheSizeGBmakes 60-second checkpoint stalls worse by allowing a larger dirty backlog to accumulate, and smaller EC2 instances liker6g.largebaseline at78.75 MB/s(630 Mbps) regardless of EBS provisioning.
Situation
WiredTiger is MongoDB’s multi-threaded storage engine. Under steady OLTP traffic, mutations update B-tree pages in WiredTiger’s internal cache and append sequentially to the write-ahead journal. To bound crash-recovery time and persist state durably, WiredTiger flushes dirty pages to data files continuously via background eviction threads and writes a crash-consistent checkpoint every 60 seconds (or whenever 2 GB of journal data is written—meaning bulk-insert storms can fire back-to-back checkpoints in under 60 seconds, compounding random B-tree write amplification).
When self-managed MongoDB clusters run on AWS EC2 backed by baseline gp3 EBS volumes (3,000 IOPS and 125 MiB/s throughput), high-throughput write workloads—such as event ingestion or frequent in-place updates—frequently generate dirty memory pages faster than the disk can flush them. Instead of slowing down smoothly, the cluster serves low-latency traffic for 50 to 55 seconds and then locks up on the 60-second checkpoint boundary.
The Problem
Three documented WiredTiger thresholds and storage constraints explain why write tickets collapse during checkpoints:
- Eviction Watermark Hierarchy (
5%Target /20%Trigger): WiredTiger’s internal cache (defaulting tomax(0.5 * (RAM - 1 GB), 256 MB)) runs background eviction when total cache occupancy hits80%(eviction_target) or dirty pages hit5%(eviction_dirty_target). If disk bandwidth cannot keep up and dirty pages reach20%(eviction_dirty_trigger)—or total occupancy reaches95%(eviction_trigger)—WiredTiger engages emergency flow control and forces application worker threads to evict and write dirty pages synchronously before executing their own queries. Notice the counter-intuitive cache-sizing math:20%of a 30 GB cache is 6 GB of dirty pages (48 seconds to drain at 125 MB/s), whereas20%of a 60 GB cache is 12 GB of dirty pages (96 seconds to drain at 125 MB/s). ExpandingcacheSizeGBwithout scaling disk throughput simply builds a larger dirty backlog before the wall hits. - Ticket Conscription Deadlock: In MongoDB 4.4 and 5.0,
mongodcaps concurrent storage operations at128read tickets and128write tickets (concurrentTransactions). When a conscripted application thread blocks in disk wait (w_await) on a saturated EBS volume, it holds its write ticket until thewrite()completes. Within milliseconds, all 128 write tickets are pinned by blocked threads, queuing every incoming write behindglobalLock. Meanwhile, sequential journal writes (flushed every100ms by default, or immediately onj: true/w: "majority"operations) compete for the exact same EBS queue depth as random checkpoint page writes when journal and data share one volume. - Checkpoint Overlap Arithmetic: Suppose a write-heavy workload accumulates 10 GB of dirty pages over a 60-second interval on a baseline
gp3volume capped at 125 MB/s: $$\text{Flush Time} = \frac{10\text{ GB}}{125\text{ MB/s}} = 80\text{ seconds}$$ Because 80 seconds exceeds the 60-second checkpoint interval, the next checkpoint fires before the previous flush finishes, saturating the disk controller continuously. - History Store Retention (
WiredTigerHS.wt): Introduced in MongoDB 4.4 to support MVCC and point-in-time reads, the History Store holds older versions of updated documents during page reconciliation. Long-running transactions or analytical queries on the primary pin old read timestamps, preventing WiredTiger from pruningWiredTigerHS.wtand adding heavy random I/O to every checkpoint.
Diagnose ticket exhaustion and dirty cache state directly from db.serverStatus() and iostat:
mongosh --eval '
var c = db.serverStatus().wiredTiger.cache;
var t = db.serverStatus().wiredTiger.concurrentTransactions;
print("Dirty %: " + ((c["tracked dirty bytes in the cache"] / c["maximum bytes configured"]) * 100).toFixed(1));
print("App-thread evictions: " + c["pages evicted by application threads"]);
print("Write tickets avail: " + t.write.available);
'
iostat -xz 1 10
Why does expanding cacheSizeGB worsen 60-second WiredTiger stalls, and how can platform teams eliminate application-thread eviction without destabilizing checkpoints?
Options Considered
When confronting 60-second checkpoint stalls, engineers often reach for memory or checkpoint-timer knobs before fixing storage throughput.
| Option | Mechanism | Immediate Effect | Where It Breaks | Decision |
|---|---|---|---|---|
Expand cacheSizeGB | Allocate 80–90% of RAM to WiredTiger cache | Delays the first 20% dirty trigger | Accumulates a larger dirty backlog, making checkpoints longer, and starves OS page cache | Rejected |
Lower syncdelay (< 60s) | Force more frequent checkpoints via storage.syncPeriodSecs | Flushes smaller deltas per cycle | MongoDB docs explicitly advise against changing syncdelay in production; increases metadata flush overhead | Rejected |
Scale gp3 Online + Eviction Workers | Raise EBS IOPS/throughput via modify-volume + tune eviction_dirty_target | Background eviction outpaces dirty-page generation | Requires EC2 instance type with sufficient EBS bandwidth ceiling | Chosen |
Expanding cacheSizeGB treats the symptom rather than the I/O deficit: 20% of a 100 GB cache is 20 GB of dirty pages instead of 12 GB on a 60 GB cache, which takes even longer to flush once triggered. Lowering syncdelay below 60 seconds contradicts MongoDB’s official parameter guidance, which warns that syncdelay should remain at 60 in production systems. Scaling EBS bandwidth online directly resolves the Dirty Generation > Disk Write Throughput inequality.
Teams with extreme sustained write ingest also evaluate splitting journal/ onto a separate EBS volume so sequential WAL appends do not share an I/O queue with random checkpoint flushes. While separating journal and data volumes isolates write queues, it complicates backup consistency: crash-consistent EBS snapshots across two independent volumes require coordinated multi-volume snapshots or db.fsyncLock() pauses, whereas a single gp3 volume with sufficient provisioned IOPS and throughput keeps backup orchestration simple.
WiredTiger Eviction and Storage Architecture
Understanding where flow control triggers requires tracing a write through WiredTiger’s ticket gate, cache watermarks, and History Store reconciliation:
- Admission Ticket Gate: Every operation acquires a read or write ticket before entering the storage engine. In MongoDB 4.4 and 5.0, this defaults to
128static tickets each; in MongoDB 7.0+, dynamic ticket allocation scales tickets adaptively up to128based on workload contention. - In-Memory Mutation and Journal Append: The thread modifies the B-tree page in WiredTiger’s cache (marking it dirty) and appends the operation to the sequential write-ahead journal.
- Background vs. Conscripted Eviction: Below
5%dirty cache, eviction workers are idle. Between5%and20%, background eviction workers compress and flush dirty pages asynchronously. Above20%, application threads are conscripted into synchronous eviction while holding their tickets. Note the diagnostic distinction indb.serverStatus().wiredTiger.cache: risingunmodified pages evictedindicates a working-set read miss problem (too little RAM for hot data), whereas risingmodified pages evictedpaired withpages evicted by application threadsproves a dirty-page write throughput bottleneck. - History Store Reconciliation: When a dirty page is evicted or checkpointed, WiredTiger executes reconciliation: it walks the in-memory page’s update chains, writes only the newest committed values into a fresh Snappy-compressed disk block for the collection
.wtfile, and moves any older versions still required by active MVCC read timestamps intoWiredTigerHS.wt. KeepingtransactionLifetimeLimitSecondsat its60-second default and routing analytical reads to secondaries preventsWiredTigerHS.wtfrom growing unbounded. Adding background eviction workers (eviction=(threads_min=4,threads_max=8)) ensures reconciliation and compression parallelize across multiple CPU cores when dirty pages are spread across dozens of collections and indexes.
Production Configuration Baseline
Scale gp3 volumes online without downtime or instance restarts:
aws ec2 modify-volume \
--volume-id "${VOLUME_ID}" \
--volume-type gp3 \
--iops 10000 \
--throughput 500
For sustained heavy-write clusters, optionally nudge WiredTiger’s background eviction to start earlier (3% dirty target, 15% trigger) and add worker threads in /etc/mongod.conf while keeping syncPeriodSecs at 60:
storage:
syncPeriodSecs: 60
wiredTiger:
engineConfig:
configString: "eviction=(threads_min=4,threads_max=8),eviction_dirty_target=3,eviction_dirty_trigger=15"
How It Rolls Out
Execute storage and eviction remediation in four gated steps so every change is reversible without cluster downtime.
- Diagnose and Isolate the Bottleneck: Capture
tracked dirty bytes in the cache,pages evicted by application threads,concurrentTransactions.write.available, andiostat -xz(w_await,%util) during a spike window. Confirm whetherpages evicted by application threadsincrements alongsidew_awaitsaturation, and check whetherVolumeQueueLengthin CloudWatch rises in lockstep with the 60-second checkpoint timer. - Verify EC2 Instance EBS Bandwidth Before Scaling Volume: Check the EC2 instance type’s EBS baseline and burst limits before running
aws ec2 modify-volume. For example, anr6g.largebaselines at only78.75 MB/s(630 Mbps) and bursts to593.75 MB/s(4,750 Mbps); attaching a500 MB/sgp3volume to an under-sized instance hits the EC2 host ceiling once burst credits (EBSByteBalance%in CloudWatch) expire. Scale thegp3volume online (secondaries first, then primary) and monitoraws ec2 describe-volumes-modificationsuntiloptimizingorcompleted. Note that AWS enforces a 6-hour cooldown between consecutivemodify-volumecalls on the same EBS volume, so size the target IOPS and throughput with headroom on the first pass. Rollback:modify-volumecan step IOPS/throughput back down after the 6-hour AWS modification cooldown. - Bound History Store Retention: Verify
transactionLifetimeLimitSecondsis60(db.adminCommand({ getParameter: 1, transactionLifetimeLimitSeconds: 1 })) and move long-running reporting queries toreadPreference=secondaryso primaryWiredTigerHS.wtreconciliation stays fast. Also checkdb.serverStatus().wiredTiger.cache["history store score"]orWiredTigerHS.wtfile size on disk between checkpoints to confirm old MVCC versions are being reclaimed rather than accumulating. - Validate Zero User-Thread Evictions: Under peak write load, sample
pages evicted by application threadsover a 10-second interval (after - beforemust equal0), confirm dirty cache stays below10%, and verify checkpoint duration (transaction checkpoint most recent time (msecs)) remains well below the 60-second interval. If a singlegp3volume’s provisioned IOPS or throughput (scalable up to80,000 IOPSand2,000 MiB/son modern AWS limits, orio2for sub-millisecond tail latency) still saturates during burst ingest, horizontal sharding is the remaining structural lever to split dirty-page generation across multiple storage volumes.
In Practice
The failure modes and remediation steps above are grounded in documented WiredTiger, MongoDB, and AWS EC2 behavior:
- WiredTiger Eviction Thresholds: WiredTiger and MongoDB documentation explicitly define the four default cache watermarks:
eviction_target(80%),eviction_trigger(95%),eviction_dirty_target(5%), andeviction_dirty_trigger(20%). Crossing20%dirty or95%total triggers application-thread eviction, which is directly observable viadb.serverStatus().wiredTiger.cache["pages evicted by application threads"]. - MongoDB
syncdelayandtransactionLifetimeLimitSeconds: MongoDB’s parameter reference specifiessyncdelay(60seconds) as the checkpoint interval and explicitly advises not modifying it in production;transactionLifetimeLimitSecondsdefaults to60seconds to bound runaway multi-document transactions and prevent cache/History Store pressure. - MongoDB 7.0+ Dynamic Concurrency Control: Starting in MongoDB 7.0, MongoDB replaced the static 128-ticket cap with dynamic ticket allocation (adaptive concurrency control) that adjusts concurrent read and write storage execution tickets in real time (up to
128) based on workload contention—meaning lower ticket counts under light load in 7.0+ are expected rather than a sign of throttling. - Isolating History Store vs. Data Eviction: When
transaction checkpoint most recent time (msecs)spikes, operators can dynamically raise log verbosity forcomponent.STORAGE.WTHS(History Store) andcomponent.STORAGE.WTEVICT(eviction) to verify whether reconciliation time is spent pruning old MVCC versions or flushing dirty collection pages.
I have not operated a 40,000-ops/s IoT ingest cluster on r6g.4xlarge personally; the mechanisms, watermarks, and AWS EBS bandwidth limits above are derived directly from MongoDB, WiredTiger, and AWS EC2 documentation.
Where It Breaks
| Condition | Breaks How | Detect | Mitigate |
|---|---|---|---|
EC2 instance EBS cap < gp3 target | Instance like r6g.large baselines at 78.75 MB/s (630 Mbps), throttling high-throughput gp3 volumes. | iostat throughput plateaus below provisioned gp3 MB/s; w_await climbs. | Upgrade EC2 instance class to match sustained EBS throughput before scaling gp3. |
Legacy gp2 volume under heavy writes | Burst credits drain; IOPS drops to 3 IOPS/GiB baseline and triggers permanent eviction stalls. | CloudWatch VolumeBurstBalance reaches 0 alongside ticket exhaustion. | Migrate gp2 to gp3 (or io2) online with aws ec2 modify-volume. |
| Long-running transactions on primary | Old read timestamps pin MVCC versions in WiredTigerHS.wt, bloating checkpoints. | Growing WiredTigerHS.wt file size and rising checkpoint scan times. | Keep transactionLifetimeLimitSeconds at 60 and route analytics to secondaries. |
| 2 GB journal checkpoint loop | Extreme write ingest fills 2 GB of journal data faster than 60s, firing back-to-back checkpoints. | transaction checkpoints increments faster than 1/minute. | Shard write-heavy collections horizontally across multiple replica set shards. |
Oversized cacheSizeGB (> 50% RAM) | Starves Linux OS page cache and allows larger dirty backlogs to accumulate between checkpoints. | Rising physical read IOPS and multi-second checkpoint stalls. | Keep cacheSizeGB at max(0.5 * (RAM - 1 GB), 256 MB) or lower. |
Key Takeaways
- 60-second latency cliffs are storage bandwidth deficits, not CPU bugs: When
Dirty Generation Rate > Disk Write Throughput, dirty cache crosses20%, conscripting app threads while they hold write tickets. - Never fix checkpoint stalls by expanding
cacheSizeGB: A larger cache holds a larger dirty backlog, lengthening checkpoint flushes and starving the compressed Linux OS page cache. - Keep
syncdelayat60seconds: MongoDB documentation advises against loweringsyncdelayin production; scalegp3IOPS and throughput online withaws ec2 modify-volumeinstead. - Check EC2 instance EBS ceilings before scaling
gp3: Anr6g.largebaselines at78.75 MB/s(630 Mbps), which will bottleneck a500 MB/sgp3volume once burst credits expire. - Protect
WiredTigerHS.wtfrom long-running reads: EnforcetransactionLifetimeLimitSeconds = 60and route analytical queries to secondaries so MVCC reconciliation stays bounded.
What to Do Next
- Problem: Write-heavy MongoDB clusters on baseline
gp3orgp2EBS volumes hit periodic 60-second stalls when dirty cache crosses20%, conscripting application threads and exhausting write tickets. - Solution: Scale
gp3IOPS and throughput online viaaws ec2 modify-volumeon an EC2 instance class with matching EBS bandwidth, tune background eviction (eviction_dirty_target=3), and keep long-running reads off the primary. - Proof: Sample
pages evicted by application threadsover 10 seconds under peak write load and verify it increments by0, whiletracked dirty bytesstays below10%ofmaximum bytes configured. - Action: Run the
db.serverStatus().wiredTigerdiagnostic snippet on your busiest primary today, compare its EBS write throughput againstiostat -xz 1, and provisiongp3headroom before the next traffic peak.