Home›Learn›MongoDB 3: what happens on every write
MongoDB · Chapter 3

What happens on every write

Where does a document go first, and why is the order of an index so important?

Three ideas explain most of what WiredTiger does: the cache holds the working set, the journal and checkpoints make writes durable, and indexes in the right order decide what a query costs.

Explained clearly

One insert, from the driver to the disk

Step through it:

Explained clearly

The WiredTiger cache: MongoDB's working memory

Listen, 3 min 6 s
1

The problem

Your collections and indexes live on disk, compressed. Reading from disk is about a thousand times slower than memory, and every compressed page also has to be decompressed. Doing that on every query would be slow.

2

What it is

The WiredTiger cache is an area of RAM that holds uncompressed pages of collections and indexes. By default it is 50 percent of (RAM minus 1 GB) or 256 MB, whichever is larger. The OS page cache keeps the compressed files too, so RAM is used twice, in two forms.

3

Follow one request

  1. find({_id: 42}) walks the _id index in the cache, then the collection.
  2. A missing page is read from the .wt file (often from the OS cache), decompressed, and kept.
  3. An update creates a new version of the document in the cache and adds a journal record.
  4. Every 60 seconds a checkpoint writes the changed pages to disk.
  5. When the cache fills, eviction threads push out clean pages and write dirty ones.

For your app: if eviction cannot keep up (the cache reaches 95 percent full, or 20 percent dirty), MongoDB makes your app's own threads help evict. That shows up as sudden latency spikes on ordinary queries.

4

What to watch in production

  • Fill and dirty ratios. Under 80 percent full and under 5 percent dirty is calm. Close to 95 and 20 means app threads are evicting.
  • Pages read into cache. If it climbs fast in normal traffic, the working set no longer fits.
  • Containers. Set storage.wiredTiger.engineConfig.cacheSizeGB well below the container memory limit, leaving room for connections and the OS.
const c = db.serverStatus().wiredTiger.cache;
print(c["bytes currently in the cache"] / c["maximum bytes configured"]);
print(c["tracked dirty bytes in the cache"] / c["maximum bytes configured"]);
print(c["pages read into cache"]);

The same idea elsewhere: MySQL calls it the buffer pool. PostgreSQL calls it shared buffers.

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.

Next · chapter 4High availabilityReplica sets, elections and write concern← Chapter 2: How it stores your data
Part 1 of 4 · Learn · 56 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.

Start 1: the basicsStart 2: ten conceptsStart 3: how a query travelsStart 4: napkin mathThe courseShort videosPostgreSQL 1: why PostgreSQLPostgreSQL 2: how it stores your dataPostgreSQL 3: what happens on every writePostgreSQL 4: high availability with PatroniPostgreSQL 5: running it as a DBREPostgreSQL 6: when it breaksPostgreSQL on Kubernetes: CloudNativePGMySQL 1: why MySQLMySQL 2: how it stores your dataMySQL 3: what happens on every writeMySQL 4: high availability with InnoDB ClusterMySQL 5: running it as a DBREMySQL 6: when it breaksMySQL failover with OrchestratorMySQL on Kubernetes: the Percona operatorsMongoDB 1: why MongoDBMongoDB 2: how it stores your dataMongoDB 3: what happens on every writeMongoDB 4: high availability with replica setsMongoDB 5: running it as a DBREMongoDB 6: when it breaksMongoDB on Kubernetes: the Percona operatorB-tree and LSM treeRedis 1: why RedisRedis 2: how it stores your dataRedis 3: high availabilityRedis 4: running it as a DBRERedis 5: when it breaksCassandra 1: why CassandraCassandra 2: how it stores your dataCassandra 3: high availabilityCassandra 4: running it as a DBRECassandra 5: when it breaksVector databases 1: why vector searchVector databases 2: how it stores your dataVector databases 3: high availabilityVector databases 4: running it as a DBREVector databases 5: when it breaksDatabase familiesEngines side by sideQueries that look fine and are notLost updates and write skewMany servers 1: keep a copy runningMany servers 2: who is the leaderMany servers 3: CAP as settingsMany servers 4: unique IDsMany servers 5: split the dataMany servers 6: across servicesMany servers 7: a thousand databasesStaff path, zero to architect