MongoDB WiredTiger Cache Internals: Eviction Pressure, OS Page Cache Interaction, and Working Set Sizing
WiredTiger does not use the Linux OS page cache. This is not a configuration option — it is a deliberate architectural decision. WiredTiger opens its data files with O_DIRECT, bypassing the kernel buffer cache entirely, and manages its own memory pool: the WiredTiger internal cache. When engineers size MongoDB instances by disk footprint alone, they are measuring the compressed on-disk representation of data that WiredTiger will decompress to 2–4× its disk size when loaded into its internal cache. The mismatch between compressed disk size and uncompressed cache size is the root cause of the most common MongoDB memory misconfiguration: a server with 64 GB of RAM, a 20 GB dataset on disk, and WiredTiger eviction pressure severe enough to stall application threads — because the 20 GB dataset occupies 55 GB of uncompressed cache space.
Situation
WiredTiger has been MongoDB’s default storage engine since version 3.2, replacing MMAPv1. The architectural shift from MMAPv1 to WiredTiger changed the memory model fundamentally: MMAPv1 used memory-mapped files and relied entirely on the OS page cache for buffering. WiredTiger inverts this — it uses O_DIRECT I/O (bypassing OS page cache) and maintains its own internal cache, independent of and separate from the OS buffer pool.
| Storage Engine | Cache Layer | Compression | I/O Mode | Working Set Sizing Model |
|---|---|---|---|---|
| MMAPv1 (MongoDB ≤3.0) | OS page cache (kernel manages) | None — data stored uncompressed on disk | mmap — kernel handles read/write buffering | Size RAM to ≥ total uncompressed dataset |
| WiredTiger (MongoDB ≥3.2) | WT internal cache (WT manages directly) | Snappy/zlib/zstd on disk — uncompressed in cache | O_DIRECT — bypasses OS page cache for data files | Size WT cache to ≥ uncompressed working set |
| WiredTiger + OS page cache (both layers) | Both: WT cache for working set + OS cache for journal/oplog | WT: on-disk compression. OS: sees compressed blocks | WT data files: O_DIRECT. Journal: buffered I/O | WT cache for primary working set; OS cache for journal replay |
The default WiredTiger cache size is computed as: max(256 MB, (totalRAM − 1 GB) × 0.5). On a 64 GB server, that is 31.5 GB. MongoDB documentation explicitly states that this leaves approximately half of system RAM for the OS page cache — but because WiredTiger uses O_DIRECT for its data files, the OS page cache primarily serves the journal (WiredTiger’s write-ahead log), oplog, and any memory-mapped files used by other processes. The OS page cache does not buffer WiredTiger data reads.
The Problem
WiredTiger’s eviction system attempts to keep the internal cache below a configurable high-water mark. When read and write pressure drives cache occupancy above that mark faster than background eviction threads can drain it, application threads are forced into foreground eviction: before completing their read or write operation, the application thread must evict one or more pages from the cache to make room. This foreground eviction is serialized with the application operation — the thread stalls until eviction completes.
The diagnostic signature is characteristic and often misattributed: IOPS climbs, CPU remains flat, operation latency increases to 50–200ms on operations that normally complete in under 1ms, and adding indexes provides no relief because the index B-Tree pages themselves are not fitting in cache and are being evicted between accesses.
The uncompressed-vs-compressed ratio makes the failure mode non-obvious until it is too late. Snappy compression, WiredTiger’s default, achieves approximately 2–4× compression on document data. A collection that occupies 15 GB on disk after Snappy compression holds 30–60 GB of uncompressed data in the WiredTiger cache when fully loaded. On a server with 31.5 GB of WiredTiger cache, a 15 GB dataset can still cause severe eviction pressure.
How do you determine the uncompressed working set size, identify whether WiredTiger eviction is active, distinguish foreground from background eviction, and size the cache correctly before the failure mode appears in production latency?
WiredTiger Cache Architecture: B-Tree Pages, Eviction Threads, and MVCC Update Chains
WiredTiger stores all data in B-Tree structures. Each collection and each index is stored as a separate B-Tree file. Understanding the in-memory representation of a B-Tree page explains both why the cache is larger than the disk representation and why eviction is expensive.
B-Tree page layout in memory. A WiredTiger B-Tree page has three states: clean (read from disk, not modified), dirty (modified, must be reconciled before eviction), and empty (evicted from cache). When a page is read from disk, WiredTiger decompresses it (Snappy/zlib) and stores the uncompressed WT_PAGE structure in the cache. The WT_PAGE structure includes the page header, the array of WT_ROW entries (for row-store collections), and a pointer to the in-memory update list.
MVCC update chains. WiredTiger implements MVCC (Multi-Version Concurrency Control) at the storage engine level. When a document is updated, WiredTiger does not modify the existing page record in-place. Instead, it prepends a WT_UPDATE structure to the update list for that row. The update list forms a singly-linked chain: each WT_UPDATE contains the new value, the transaction ID that wrote it, and a pointer to the previous version. Reads traverse this chain to find the appropriate version for their read timestamp.
This MVCC structure has a direct impact on cache size: a document updated 50 times between checkpoints may have a chain of 50 WT_UPDATE structures held in cache simultaneously — all versions must be retained until they are no longer needed by any active read. High-update-rate workloads on frequently written documents accumulate longer update chains, increasing the effective memory footprint per document beyond the document size itself.
Eviction architecture: server thread, worker threads, and application threads. WiredTiger eviction is managed by a hierarchy of threads:
Eviction Server Thread (1)
└── Scans B-Trees for eviction candidates
└── Places candidates on eviction queue
└── Monitors cache thresholds
Eviction Worker Threads (configurable, default 4)
└── Pull pages from eviction queue
└── Reconcile dirty pages (write dirty data to disk via checkpoint)
└── Evict clean pages directly (no I/O required)
Application Threads (foreground eviction)
└── Triggered when cache > eviction_trigger (default 95%)
└── Each application thread evicts pages before completing its operation
└── Direct cause of latency spikes during severe cache pressure
The eviction thresholds that govern this hierarchy:
| Threshold | Default | Meaning |
|---|---|---|
eviction_target | 80% of cache | Background eviction keeps cache below this level during normal operation |
eviction_trigger | 95% of cache | Application thread eviction begins above this level |
eviction_dirty_target | 5% of cache | Background eviction keeps dirty pages below this fraction |
eviction_dirty_trigger | 20% of cache | Aggressive dirty page eviction begins above this fraction |
eviction_updates_target | 0% | Target for update list memory (0 = unbounded) |
When eviction_trigger is breached, every application thread that needs to allocate cache space first participates in evicting one or more pages. At this point, operation latency is directly proportional to eviction cost (page size × reconciliation cost for dirty pages).
Reconciliation — the dirty page write path. Reconciling a dirty page is significantly more expensive than evicting a clean page. Reconciliation involves: consolidating all WT_UPDATE entries on the page into the on-disk format, compressing the reconciled page (Snappy by default), and writing the compressed page to the data file via direct I/O. Only after reconciliation can the dirty page be evicted from cache. A workload with many dirty pages (high write rate, long checkpoint intervals) will see eviction worker threads spending the majority of their time on reconciliation — creating a backlog on the eviction queue and increasing the probability of foreground eviction.
In Practice
Identifying cache pressure and eviction state. The primary diagnostic is db.serverStatus().wiredTiger.cache:
// Paste this directly into mongosh — returns the cache state you need
const c = db.serverStatus().wiredTiger.cache;
const fill = (c["bytes currently in the cache"] / c["maximum bytes configured"] * 100).toFixed(1);
const dirty = (c["tracked dirty bytes in the cache"] / c["maximum bytes configured"] * 100).toFixed(1);
print(`Cache fill: ${fill}%`);
print(`Dirty pages: ${dirty}% of max cache`);
print(`Foreground evictions: ${c["pages evicted by application threads"]}`);
print(`Background evictions: ${c["pages evicted by the internal page eviction worker"]}`);
print(`Read into cache: ${c["pages read into cache"]}`);
print(`Written from cache: ${c["pages written from cache"]}`);
print(`Unmodified removed: ${c["unmodified pages evicted"]}`);
print(`Modified removed: ${c["modified pages evicted"]}`);
The field pages evicted by application threads is the single most actionable signal. A nonzero and growing value means foreground eviction is active. Any value above zero means application threads are being stalled for eviction. Cross-reference it against the bytes currently in the cache fill ratio: if fill exceeds 90% and foreground eviction is occurring, the cache is undersized for the active working set.
Distinguishing WiredTiger cache misses from OS page cache misses. Because WiredTiger uses O_DIRECT, a WiredTiger cache miss results in a direct I/O read to the block device — bypassing the OS page cache entirely. This means iostat shows real physical reads:
# Run on the MongoDB server to correlate WT cache pressure with disk I/O
# -x = extended stats, -d = disk only, 1 = 1-second interval
iostat -xd 1 | grep -E "^Device|$(lsblk -o NAME,MOUNTPOINT | awk '/\/var\/lib\/mongodb/{print $1}')"
Key iostat fields during WiredTiger cache miss pressure:
r/s(reads per second) climbs from near-zero (working set fits in cache) to hundreds or thousands (cache misses driving disk reads)rMB/sreveals the read bandwidth; compare against the device’s maximum sequential read bandwidthr_await(average read latency in milliseconds) above 5ms for SSDs indicates queueing or device saturation
For NVMe SSDs, WiredTiger’s O_DIRECT reads achieve 200–800 µs per 4K page at low queue depth. At full eviction pressure with hundreds of concurrent application threads triggering foreground eviction, the I/O queue depth can saturate the NVMe device’s internal queue (typically 1024 commands), and r_await climbs to 5–20ms per read — accounting for the observed 50–200ms operation latency when each operation triggers multiple page reads.
eBPF tracing for WiredTiger I/O patterns (Linux 5.8+). For deeper I/O analysis without application instrumentation:
# Trace WiredTiger pread64 calls — shows actual page read sizes and latency
# Requires bpftrace on Linux 5.8+ with kernel headers installed
bpftrace -e '
tracepoint:syscalls:sys_enter_pread64 /comm == "mongod"/ {
@start[tid] = nsecs;
@size[tid] = args->count;
}
tracepoint:syscalls:sys_exit_pread64 /comm == "mongod" && @start[tid]/ {
$lat_us = (nsecs - @start[tid]) / 1000;
@read_latency_us = hist($lat_us);
@read_size_bytes = hist(@size[tid]);
delete(@start[tid]); delete(@size[tid]);
}
interval:s:10 { print(@read_latency_us); print(@read_size_bytes); clear(@read_latency_us); clear(@read_size_bytes); }'
This traces every pread64 syscall from the mongod process, capturing read latency (microseconds) and read size (bytes). WiredTiger reads pages in its configured page size (default 32KB for leaf pages, configurable via leaf_page_max). A histogram dominated by 32KB reads with latency above 500µs indicates cache miss pressure reaching the disk layer.
Estimating uncompressed working set size. Before sizing the WiredTiger cache, determine the uncompressed working set:
// Get compression ratio for each collection in the working database
db.getCollectionNames().forEach(name => {
const stats = db.getCollection(name).stats({scale: 1024 * 1024});
if (!stats.storageSize) return;
const ratio = stats.size / stats.storageSize; // uncompressed / compressed
print(`${name}: ${stats.storageSize.toFixed(0)} MB compressed → ` +
`${stats.size.toFixed(0)} MB uncompressed ` +
`(${ratio.toFixed(1)}× expansion)`);
});
The size field is the uncompressed data size (as if stored without compression); storageSize is the on-disk compressed footprint. The ratio reveals the actual expansion factor for each collection. Sum the size fields for all collections that are in the hot working set (accessed in the past 24–48 hours) — that sum is the minimum WiredTiger cache requirement.
WiredTiger cache configuration. Set the cache size to accommodate the uncompressed working set with 20% headroom:
# /etc/mongod.conf — WiredTiger cache configuration
storage:
dbPath: /var/lib/mongodb
wiredTiger:
engineConfig:
cacheSizeGB: 48 # Set to 60-70% of system RAM on dedicated MongoDB hosts
journalCompressor: snappy
directoryForIndexes: false # Keep indexes in same WT files as collections
collectionConfig:
blockCompressor: snappy # Default; zstd gives better compression at moderate CPU cost
indexConfig:
prefixCompression: true # Reduces index disk footprint by 40-60% for many index types
For dedicated MongoDB hosts, MongoDB’s official documentation recommends setting cacheSizeGB to 60% of system RAM, leaving 40% for: the OS page cache (used by WiredTiger’s journal, oplog, and MongoDB’s diagnostic log), connection buffers (roughly 1 MB per connection × max connection count), sort operation memory, and system processes.
WiredTiger checkpoint and eviction interaction. WiredTiger runs a checkpoint every 60 seconds by default (configurable via checkpointDelaySecs). During checkpoint, WiredTiger writes all dirty pages to disk and advances the durable timestamp. Checkpoint is NOT the same as eviction — it writes dirty pages but does not remove them from cache. Eviction removes pages from cache (after reconciling if dirty). Understanding this distinction prevents a common misconfiguration: reducing checkpoint frequency to reduce I/O actually increases eviction cost, because it allows dirty pages to accumulate larger WT_UPDATE chains before reconciliation, making each reconciliation more expensive.
Monitoring with Atlas metrics or Prometheus. For Atlas deployments, the relevant metrics in the Atlas monitoring dashboard:
# Atlas metric names for WiredTiger cache monitoring
CACHE_USED_BYTES # Current cache bytes in use
CACHE_DIRTY_BYTES # Dirty bytes in cache
TICKETS_AVAILABLE_READS # Available read tickets (128 default) — saturation = queuing
TICKETS_AVAILABLE_WRITES # Available write tickets (128 default)
# For self-managed with mongodb_exporter (Prometheus):
mongodb_ss_wiredTiger_cache_bytes_currently_in_cache
mongodb_ss_wiredTiger_cache_maximum_bytes_configured
mongodb_ss_wiredTiger_cache_pages_evicted_by_application_threads_total
mongodb_ss_wiredTiger_cache_tracked_dirty_bytes_in_cache
PromQL alert for foreground eviction:
# Alert if foreground eviction rate exceeds 10 pages/second over 5 minutes
rate(mongodb_ss_wiredTiger_cache_pages_evicted_by_application_threads_total[5m]) > 10
Where It Breaks
| Failure Mode | Root Cause | Production Blast Radius | Mitigation |
|---|---|---|---|
| Foreground eviction stalls application threads | Cache fill exceeds eviction_trigger (95% default); background eviction cannot drain cache fast enough; application threads participate in eviction before completing read/write | All operations experience added latency proportional to page eviction cost (10–100ms per eviction cycle at disk speeds); at high concurrency, the effect compounds — 100 threads each stalling 50ms = 5,000 ms-thread-seconds of latency added per second | Increase cacheSizeGB to 60–70% of RAM; if cache is correctly sized, check eviction_dirty_trigger — a workload with many small dirty pages may need eviction_dirty_target reduced to 2% to trigger more aggressive background dirty page flush |
| MVCC update chain accumulation — cache bloat from high-update documents | Frequently updated documents accumulate long WT_UPDATE chains between checkpoints; each chain version is retained in cache until checkpoint advances the stable timestamp past the oldest reader | Cache appears undersized even though document count is small; tracked dirty bytes in the cache grows faster than data volume | Ensure checkpoints complete within the 60-second interval; monitor db.serverStatus().wiredTiger["transaction"]["transaction checkpoint max time (msecs)"] — if checkpoint takes >30 seconds, investigate dirty page accumulation; consider workloads that update many versions of the same document (time-series style) as candidates for WiredTiger’s native time-series collection type |
| Analytics scan flooding cache — OLTP working set evicted | Full collection scan (aggregation, $match without index) scans all pages of a large collection sequentially; these pages fill the cache and evict the OLTP hot pages that were previously resident | OLTP operation latency spikes during or after an analytics query; subsequent OLTP reads require cache re-warming from disk | Use allowDiskUse: true for analytics aggregations and ensure the aggregation uses an index; consider routing analytics queries to a secondary with a dedicated read preference; configure maxTimeMS to prevent unbounded analytics scans from running indefinitely |
| Compression ratio underestimate — cache too small for working set | Team sizes cache based on compressed disk footprint (e.g., 20 GB on disk → assume 20 GB cache needed); actual uncompressed working set is 50 GB; cache is undersized by 2.5× | Constant eviction pressure from startup; no amount of tuning resolves it because the root cause is insufficient RAM | Run the collection-level uncompressed size query above before hardware provisioning; multiply db.collection.stats().size (uncompressed) sum across the working set by 1.2 for safety headroom |
| Index pages not fitting in cache | B-Tree index pages for large indexes are evicted from cache between accesses; adding more indexes increases the total index working set beyond cache capacity | Index scans trigger disk reads for index pages before reaching document pages; IXSCAN operations paradoxically become slower than expected because the index itself is not cache-resident | Run db.collection.stats().indexSizes to get the uncompressed size of each index; sum active index sizes plus document working set to compute total cache requirement; drop unused indexes ($indexStats reveals unused indexes older than 30 days) |
| WiredTiger checkpoint I/O spike — eviction latency increases during checkpoint | During 60-second checkpoints, WiredTiger reconciles dirty pages to disk; if dirty page volume is large, checkpoint I/O saturates the storage device; eviction competes with checkpoint for I/O bandwidth | Periodic latency spikes at 60-second intervals; r_await and w_await in iostat spike simultaneously | Provision storage with sufficient write bandwidth for both normal write operations and checkpoint I/O; on AWS, use io2 Block Express volumes (not gp3) for deployments with >50% dirty page ratios; separate WiredTiger journal to a different volume (EBS volume) to reduce write I/O contention during checkpoint |
| Read ticket exhaustion — queuing before cache interaction | WiredTiger limits concurrent reads to 128 tickets by default; at high concurrency, tickets exhaust before cache pressure is reached; subsequent reads queue waiting for a ticket | Operation latency climbs linearly with read ticket queue depth; db.serverStatus().wiredTiger.concurrentTransactions.read.out shows tickets in use; available drops to zero when queuing occurs | Increase read tickets to 256 for read-heavy workloads: db.adminCommand({setParameter: 1, wiredTigerConcurrentReadTransactions: 256}); this increases parallelism but also increases cache pressure — only raise tickets if cache headroom exists |
| Two-layer memory confusion — OS page cache not helping WT data reads | Engineers expect the OS page cache to absorb WiredTiger cache misses for data files; WiredTiger opens data files with O_DIRECT, so the OS page cache never buffers data file reads | Teams allocate less RAM to WiredTiger cache assuming the OS layer will help; it does not for data; cache misses hit disk directly | Confirm WiredTiger data file I/O bypasses OS cache: `lsof -p $(pgrep mongod) |
2025 WiredTiger and MongoDB 7.x/8.x Update
WiredTiger (available in MongoDB 7.x, GA in 8.0 released October 2024) introduced a revised eviction configuration model that adds eviction_updates_target and eviction_updates_trigger thresholds specifically for controlling WT_UPDATE chain memory. In high-update workloads where update chains accumulate faster than checkpoint can advance the stable timestamp, these thresholds allow the eviction system to target update-heavy pages specifically, reducing the incidence of cache bloat from MVCC chains without requiring a reduction in checkpoint frequency.
WiredTiger’s block manager in MongoDB 8.x (GA 2024-10-02) also added improved read-ahead logic: when an eviction-forced read requests a page, WiredTiger now pre-fetches adjacent pages in the B-Tree leaf level, reducing the number of sequential cache misses during range scans. This improvement specifically benefits workloads that experienced cache thrashing during range queries where adjacent pages were consistently evicted between query iterations.
For deployments on Linux kernel 6.x, WiredTiger added support for io_uring as an alternative to pread64/pwrite64 for direct I/O — reducing per-I/O system call overhead by batching I/O submissions. The io_uring backend is enabled by setting wiredTigerEngineConfig: "io_type=io_uring" in the mongod configuration (experimental as of late 2024, pending stabilization). On NVMe SSDs, io_uring reduces per-read latency from approximately 50–100µs (pread64 system call overhead) to 10–30µs at low queue depths.
What to Do Next
- Problem: WiredTiger uses
O_DIRECTand manages its own memory pool separate from the OS page cache; teams that size MongoDB RAM based on compressed disk footprint routinely undersize the WiredTiger cache by 2–4×, causing foreground eviction that stalls application threads mid-operation and is misdiagnosed as a storage I/O problem. - Solution: Run
db.serverStatus().wiredTiger.cacheto check cache fill ratio andpages evicted by application threads; run the collection-level uncompressed working set query to determine the true cache requirement; setcacheSizeGBto cover the uncompressed working set plus 20% headroom, targeting 60–70% of total system RAM on dedicated MongoDB hosts. - Proof: WiredTiger’s use of
O_DIRECTfor data files is documented in the WiredTiger architecture documentation and confirmed by MongoDB’s Server Manual section on WiredTiger storage engine internals; thepages evicted by application threadsmetric is explicitly documented in MongoDB’sdb.serverStatus()output reference as the indicator of foreground eviction pressure. - Action: Run the mongosh cache fill check above against any MongoDB instance currently showing elevated read latency or IOPS; if
pages evicted by application threadsis nonzero andbytes currently in the cacheexceeds 85% ofmaximum bytes configured, you have foreground eviction — verify yourcacheSizeGBagainst the uncompressed working set size before concluding the storage layer is the bottleneck.
Sources to Verify
- WiredTiger Architecture Documentation — Cache, Eviction, and Reconciliation Internals: https://source.wiredtiger.com/develop/arch-cache.html
- MongoDB Server Manual — WiredTiger Storage Engine, Cache and Compression: https://www.mongodb.com/docs/manual/core/wiredtiger/
- MongoDB Server Manual — db.serverStatus() Output Reference — wiredTiger.cache Fields: https://www.mongodb.com/docs/manual/reference/command/serverStatus/#mongodb-serverstatus-serverstatus.wiredTiger.cache
- WiredTiger Source — eviction_trigger and eviction_target Configuration Parameters: https://source.wiredtiger.com/develop/tune_cache.html
- Linux
io_uringand Direct I/O Interaction — Jens Axboe, USENIX ATC 2019: https://www.usenix.org/conference/atc19/presentation/axboe - MongoDB Engineering Blog — WiredTiger Eviction Deep Dive (2022): https://www.mongodb.com/blog/post/performance-best-practices-mongodb-data-modeling-and-memory-sizing
- Brendan Gregg — Systems Performance (2nd ed.) Chapter 8: Memory — OS Page Cache vs Direct I/O Interaction: https://www.brendangregg.com/systems-performance.html