Home›Learn›MongoDB · WiredTiger
Course · Inside one serverLesson 7 of 330 read

MongoDB · WiredTiger

Why does MongoDB feel fast until the cache fills?

This page is about documents and replica sets. I show you where WiredTiger keeps every collection and index, and how two logs split the jobs: journal for crashes, oplog for the replica set. After it you will be able to find any collection's .wt file, read the oplog window, and check whether the cache is under pressure.

MongoDB · WiredTiger: in one line

A document database. JSON-like documents in collections. Built to run as a replica set.

Good at: Records that genuinely differ per item. Catalogues and profiles. Spreading across machines with built-in sharding. Two logs: journal for crashes, oplog for the replica set.

Runs as: mongod processes in a replica set; mongos routers when sharded

Printable one-page cheat sheet for MongoDB →

The architecture: processes, memory, disk

Process, memory, disk: a request enters at the process layer, memory serves it when it can, and disk makes it permanent. Name the layer first, then diagnose inside it. The full rule is on the PostgreSQL page: name the layer first, then diagnose inside it.

The same layers as a still diagram, with every part named:

MongoDB · WiredTiger: architecture

Request path

Processesmongod per member · the primary accepts writes, secondaries apply the oplog · mongos routers when sharded
→
MemoryWiredTiger cache (~50% of (RAM − 1 GB), minimum 256 MB) holding uncompressed data + the OS filesystem cache
→
Disk: the dbPathcollection-*.wt · index-*.wt · journal/WiredTigerLog.* · the oplog in local.oplog.rs
Who does what: The primary orders all writes into the oplog. WiredTiger checkpoints about every 60 s and makes the .wt files consistent. Secondaries tail the oplog and apply the same operations in the same order.

Every log file a DBA needs to know

Same idea as PostgreSQL: exact names, one job per log, one check per incident. The rule is written once on the PostgreSQL page. This table adds the operational logs a DBA reads first: server, error, slow.

LogExact file nameWhere it sits (on-prem)What it doesWhat to check in it
MongoDB
Journal
journal/WiredTigerLog.0000000123journal/ inside the dbPathWiredTiger's write-ahead log. It covers the gap between checkpoints (about 60 s). j:true waits for this.Check that the files exist and turn over. Check journal commit latency in db.serverStatus().wiredTiger.log.
MongoDB
Oplog
local.oplog.rsA capped collection in the local database. Not a fileOrdered record of every write on the primary. Secondaries tail it. Its size divided by write rate is the catch-up window.rs.printReplicationInfo(). "log length start to end" is the window in hours. Compare it to your longest maintenance.
MongoDB
mongod log
mongod.log/var/log/mongodb/mongod.logThe server's diary. Elections. Slow operations (over the profiler threshold). Connection events.Election events and slow-operation lines around the incident start. Stepdown and stepup pairs mark every failover.

The parameters DBAs actually touch during outages

Same three outage rules as PostgreSQL: Safe live lever, Planned change, Do not touch. What each one means is written once on the PostgreSQL page.

MongoDB · WiredTiger Outage parameters

ParameterWhat it doesDuring an outage
storage.wiredTiger.engineConfig.cacheSizeGBSize of the WiredTiger cache. Default is about 50% of (RAM minus 1 GB), or 256 MB if that is larger.Planned change. It is set in the config file. Applying it means a rolling restart of the set. Mid-incident, the evidence comes first: serverStatus().wiredTiger.cache. The live fixes are killing the cache-churning operation or the pinned snapshot, not the cache size.
oplogSizeMB / replSetResizeOplogSize of the capped oplog collection. Window equals size divided by write rate.Safe live lever (dynamic in 4.4 and later). Enlarge the oplog before planned maintenance so the window exceeds the downtime. It cannot recover entries that already rolled off.
writeConcern / readConcernPer-operation guarantees set by the application. How many members must acknowledge a write (w). Whether it must be journaled (j). Which writes a read may see.Application change, not a server knob. Do not weaken w:'majority' mid-outage to make writes "fast again", unless rollback-on-election is explicitly acceptable. Shifting readPreference to secondaries sheds primary load but serves staler data. That is a routing decision, not a repair.
// check db.serverStatus().wiredTiger.cache // dirty bytes + app-thread evictions rs.printReplicationInfo() // the oplog window, in hours // the safe lever: extend the window before maintenance (4.4+) db.adminCommand({replSetResizeOplog: 1, size: 20480}) // MB
Files on disk · what ls actually shows

Same rule as PostgreSQL: there is no hidden state. Every file here is inspectable with ls and du while the server runs. The full version is on the PostgreSQL page.

MongoDB: the dbPath
$ ls /var/lib/mongo
WiredTiger        # WiredTiger version marker
WiredTiger.wt     # WT's own metadata: where the
                  # last checkpoint is
WiredTiger.turtle  # backup copy of that metadata
_mdb_catalog.wt   # THE MAP: "users" = which file?
collection-2-4471….wt # ← collection "users"
collection-5-9912….wt  # ← collection "orders"
index-3-4471….wt  # ← the _id index of "users":
                  #   one file per index
journal/          # THE JOURNAL (write-ahead log):
  WiredTigerLog.0000000123
mongod.lock       # lock file; a stale one means the
                  # last shutdown was not clean
sizeStorer.wt  storage.bson
diagnostic.data/   # metrics mongod records on itself
File names are internal IDs, not collection names. _mdb_catalog.wt holds the mapping. In mongosh, db.users.stats().wiredTiger.uri shows a collection's real file name.
The log files · one by one

Same pattern as PostgreSQL: five logs, one job each, and every operational budget is a time window. The full version is on the PostgreSQL page.

MongoDB · WiredTiger

Journal

journal/WiredTigerLog.0000000123
Where it sits
The journal/ folder inside the dbPath. A sequence of WiredTigerLog.* files, written by the WiredTiger storage engine.
What it does
WiredTiger's write-ahead log. Data files are only made consistent at checkpoints, roughly every 60 seconds. The journal covers the gap. A write acknowledged with j: true is durable once its journal entry is on disk. On restart mongod replays the journal from the last checkpoint.
What breaks without it
A crash could lose every write since the last checkpoint. Up to about 60 seconds of acknowledged data. The journal exists to close exactly that gap.
Look at it
$ ls /var/lib/mongo/journal/ -- in mongosh: db.serverStatus().storageEngine db.adminCommand({getCmdLineOpts: 1}) -- parsed.storage.journal shows the journal settings
MongoDB

Oplog: the replica set log

local.oplog.rs
Where it sits
Not a file. A capped collection named oplog.rs in the local database, present on every replica set member. Capped means fixed-size. Old entries fall off the front as new ones arrive.
What it does
An ordered record of every write on the primary, each stamped with a timestamp. Secondaries continuously tail it and apply the same operations in the same order. Its size defines the oplog window. That is how far behind a secondary can fall and still catch up.
What breaks without it
No replica set at all. And if a secondary stays down longer than the oplog window, the entries it missed are gone. It must copy everything again (initial sync).
Look at it
// in mongosh: rs.printReplicationInfo() db.getSiblingDB('local').oplog.rs .find().sort({$natural: -1}).limit(1)

Journal to checkpoint: what covers the 60-second gap

Writejournal/WiredTigerLog.*, on disk first
→
Cachetimestamped versions, dirty pages
→
Checkpoint, about every 60 sconsistent snapshot into collection-*.wt
→
Crashlast checkpoint plus journal replay

The other logs: PostgreSQL: WAL · MySQL · InnoDB: redo log and binary log · the pattern behind all five, and where they break

See it yourself · copy-paste commands

Open a real database and check every claim on this page

Same rule as PostgreSQL: every mechanism above is observable on a running server in under two minutes. The full version is on the PostgreSQL page.

Run it locally: docker-compose-mongo.yml starts MongoDB 8.0 on port 27017 with a shop database. docker compose -f docker-compose-mongo.yml up -d, then run the commands below against it.

MongoDB · mongosh + shell
// where is everything?
db.adminCommand({getCmdLineOpts: 1})
// → parsed.storage.dbPath
db.users.stats().wiredTiger.uri
// → "table:collection-2-4471…"
$ ls /var/lib/mongo/journal
// → WiredTigerLog.0000000123

// the oplog: size, window, latest entry
rs.printReplicationInfo()
rs.status()  // members + optime lag

// cache pressure
db.serverStatus().wiredTiger.cache

ESR: the index order that avoids a sort

Problem. My query filters, sorts, and returns. It runs slow. I run explain. It shows a SORT stage. The index exists. The sort still happens.

Mechanism. A compound index stores keys in field order. Field 1 first. Field 2 inside field 1. Field 3 inside field 2. Put the equality field first. Put the sort field second. Put the range field last. That is ESR.

The equality match narrows the walk to one slice. Inside that slice, the sort field is already in order. The query reads rows in sorted order. The range field sits last. It does not change the order. It only filters keys as the scan walks the equality slice.

Put the fields in the wrong order and the sort breaks. A range field before the sort field breaks it. The index can no longer hand back rows in sort order. MongoDB adds a SORT stage. That stage sorts in memory. The limit is 100 MB. Since MongoDB 6.0 a sort past that limit spills to temporary files on disk by default (allowDiskUseByDefault), which is slow, and it fails only if the query sets allowDiskUse(false) or the server option is off.

ESR: equality, sort, range, in that order

Equality firststatus: collapses to one slice
→
Sort secondcreatedAt: already in order, no SORT stage
→
Range lastamount: filters, order untouched

Range before sort: the order breaks

Range firstamount: the ordering ends here
→
Sort field afterno longer in order
→
SORT stagein-memory sort, spills to disk past 100 MB

MongoDB caches the winning plan for a query shape. Adding or dropping an index clears the plan cache for that collection automatically, so the next run re-plans and picks up the new index. A manual clear is only needed for other causes, such as a plan that went stale as data distribution changed.

Exact check. Build the index in ESR order. Then explain the query. Then check index use and plan cache.

db.orders.createIndex({ status: 1, createdAt: -1, amount: 1 }); db.orders.find( { status: "shipped", amount: { $gte: 100 } } ).sort({ createdAt: -1 }).explain("executionStats"); db.orders.aggregate([ { $indexStats: {} } ]); db.orders.aggregate([ { $planCacheStats: {} } ]); db.runCommand({ planCacheClear: "orders" });

Read explain for SORT stage. No SORT stage means the index order did the sorting. Read totalDocsExamined next to nReturned. A wide gap means the index is not narrowing the work.

One incident I keep coming back to

Every new write landed on one shard. That node ran at 100 percent while the rest idled, and inserts slowed for every customer.

I checked distribution, not totals. One node was at 100 percent and the rest were idle. A monotonic shard key was sending every new write to the same shard.

The fix was the key, not more shards. Hash-prefix a monotonic shard key, or give the whale tenant its own shard. Choose the shard key from the query pattern before launch.

How to host MongoDB on-prem, on EC2, in Kubernetes, or on Atlas is on the Cloud page.

Before you leave, check this

One command. It tells you how long a secondary can stay down and still catch up.

The oplog window: size divided by write rate

10 GB oplogfixed size, capped
÷
5 MB/min writesthe current rate
=
34-hour windowlongest survivable downtime
→
Rate grows 10xsame oplog, 3.4-hour window
rs.printReplicationInfo()

Read "log length start to end". That is the window in hours. Compare it to your longest maintenance.

Follow it

Follow one change to a secondary

Step through a write travelling from the primary to a secondary. Then break it.

A write was acknowledged with w: 1, and the primary crashes a second later. Can the write be lost?

Yes. With w: 1 the primary answered before any secondary had the write. If a secondary that never received it is elected, the write is rolled back. With w: "majority" it cannot be lost this way.

Your turn

Reads were fine last month. Now p99 latency has tripled, with no code change and the same traffic. The data has grown past the WiredTiger cache. What changed, and what do you look at?

Write your answer down first. Then open mine.

Show my answer

What changed: the pages your queries touch no longer all fit in the WiredTiger cache. Some reads now come from the operating system's file cache, which holds compressed pages, and some from disk. When the cache is full, application threads are also asked to help evict pages, which adds latency to ordinary queries.

What I look at: db.serverStatus().wiredTiger.cache: bytes in the cache against the maximum, pages read into the cache per second, and eviction by application threads. Then index sizes from db.collection.stats(), because indexes that no longer fit hurt every query.

What I would change: drop indexes nobody uses ($indexStats shows them), archive old documents, or add memory. Sharding is the answer only when the working set is too big for any one machine you would want to run.

Connected

Where this shows up

The same mechanism, caches and memory, replication and failover, elsewhere on the site: in real incidents, in measurements, and in designs.

Check yourself · 4 questions

Check yourself

Pick an answer. You will see whether it is right, and why.

1. With w: "majority" and the default journaling setting, when is a write acknowledged?

2. A secondary falls further behind than the oplog window. What happens?

3. A multi-document transaction stays open past transactionLifetimeLimitSeconds. What happens?

4. How does MongoDB store documents on disk?

Part 1 of 4 · Learn · 23 pagesAll pages

How do databases actually work? From one row on disk to transactions: the words you need, PostgreSQL, MySQL and MongoDB from the files up, then Redis, Cassandra and vector search, side by side, and the query and concurrency traps.