Building a Safe MongoDB Index Recommendation Engine: The ESR Rule, Prefix Deduplication, and Write Penalties
Automating database index recommendations is not merely an optimization to accelerate slow queries—it is a defensive mechanism to protect WiredTiger from the synchronous write amplification and cache bloat of redundant B-tree indexes.
TL;DR
- Problem: Ungoverned per-endpoint index PRs create overlapping left-prefix indexes and misordered
E-R-Scompound keys, multiplying WiredTiger B-tree writes (1 + N_indexes) per insert and forcing blocking sorts.- Answer: Build a CI/CD index synthesizer that classifies query shapes via the Equality-Sort-Range (ESR) rule, rejects candidates that are left-prefixes of existing indexes, and safely subsumes narrower non-unique indexes.
- Watch out: Never drop a subsumed index if it enforces
unique: trueor a distinctpartialFilterExpression, and never trust$indexStatsaccesses.ops == 0after a recentmongodrestart.
Production Scope: MongoDB 5.0 / 6.0 / 7.0 / 8.0 on AWS EC2 + EBS
gp3
Situation
In microservice architectures backed by self-managed MongoDB replica sets on AWS EC2 (r6g.2xlarge with 64 GB RAM and ~31.5 GB WiredTiger cache, paired with EBS gp3 volumes), application teams optimize for single-endpoint read latency while platform engineers must protect the shared WiredTiger cache and storage IOPS budget. As collections grow past tens of millions of documents into multi-terabyte datasets, unindexed query predicates trigger COLLSCAN operations that pull cold data pages into cache, evict the active working set, and exhaust concurrent read tickets.
When developers see request timeouts, the common response is to open a pull request adding a single-field index for each new filter predicate. Without algorithmic governance, collections accumulate overlapping B-tree indexes that share identical leading keys, inflating checkpoint flush volume, doubling backup snapshot sizes, and degrading write latency across the entire replica set.
The Problem
Three Failure Modes of Unregulated Indexing
- Pathological Collection Scans (
COLLSCAN): Queries filtering on unindexed predicates inspect every document in the collection. When the collection exceeds the WiredTiger cache size (~31.5 GB on anr6g.2xlarge), a singleCOLLSCANpulls cold data pages from EBS into cache, evicting hot working-set B-tree pages and causing latency spikes across unrelated indexed endpoints. - Redundant Prefix Bloat: Adding
{ status: 1 }when{ status: 1, created_at: -1 }already exists wastes memory and disk. Because MongoDB B-trees satisfy any left-to-right prefix of a compound index,{ status: 1 }serves zero queries that the compound index cannot already serve, yet consumes WiredTiger cache and backup snapshot capacity. - Synchronous Write Amplification ($W_{\text{mult}} = 1 + N_{\text{indexes}}$): WiredTiger updates every index synchronously inside the document write path. A collection with 10 indexes executes 11 distinct B-tree mutations per insert (1 base collection row-store + 10 index row-stores). At 5,000 inserts per second, 10 indexes generate 55,000 B-tree page mutations per second. On an
r6g.2xlargewith a ~31.5 GB WiredTiger cache, the 20%eviction_dirty_triggersits at ~6.3 GB and the 5%eviction_dirty_targetat ~1.58 GB; if each uncoalesced mutation dirties a 4 KB leaf page, peak dirty-page generation approaches ~220 MB/s, pushing application threads into synchronous eviction stalls once dirty bytes cross 20%. - Blocking Sort Ceiling (100 MB): Compound indexes ordered with Range before Sort (
E-R-S) cannot return keys in sort order, forcing a blockingSORTstage that aborts at 100 MB (internalQueryMaxBlockingSortMemoryUsageBytes=104,857,600bytes in MongoDB 4.4+; 32 MB in 4.2 and earlier).
The core architectural question is: How can platform teams automate index recommendations that synthesize ESR-optimal compound keys, reject redundant left-prefixes, and prevent write amplification before indexes reach production?
Options Considered
| Approach | Read Latency & Sort | Write Amplification | Prefix Governance | Decision |
|---|---|---|---|---|
| Ad-Hoc Developer PRs | Inconsistent; frequent E-R-S mistakes | Unbounded index growth | Manual review only; misses prefixes | Rejected: Accumulates redundant B-trees under feature velocity |
| Single-Field Per Predicate | Forces index intersection or blocking SORT | High; 1 B-tree per field | None; creates overlapping singletons | Rejected: Cannot satisfy compound equality + sort natively |
| ESR + Prefix Pruning Engine | Eliminates SORT via native B-tree order | Bounded by subsuming narrow indexes | Rejects left-prefixes automatically | Chosen: Optimizes both read plans and WiredTiger write budget |
Ad-hoc PRs and single-field-per-predicate indexing were rejected because neither enforces Equality -> Sort -> Range ordering nor prevents left-prefix duplication. While MongoDB can occasionally combine two single-field indexes via index intersection (AND_HASH or AND_SORTED), intersection cannot eliminate a blocking SORT stage when sort fields are unindexed and requires scanning and intersecting two separate B-trees. Wildcard indexes ({ "$**": 1 }) were also rejected for OLTP collections because they cannot support compound ESR sort-and-filter plans and index every dynamic subfield indiscriminately. An automated ESR synthesizer paired with catalog prefix checking enforces both read-plan optimality and write-budget bounds deterministically in CI/CD.
The Recommendation Architecture: The ESR Theorem and Prefix Pruning
An automated recommendation engine parses slow query shapes from mongod.log, classifies predicates into Equality, Sort, and Range buckets, and validates the synthesized candidate against listIndexes() before approving any build.
flowchart TD
LogSource["Structured Slow Logs — mongod.log"] --> Parser["Query Shape Parser — AST Tokenizer"]
Parser --> Classifier["Predicate Classifier — Equality / Sort / Range"]
Classifier --> EStage["1. Equality Fields — Exact Matches"]
EStage --> SStage["2. Sort Fields — Ordering Direction"]
SStage --> RStage["3. Range Fields — Inequalities"]
RStage --> Candidate["Synthesized Candidate Compound Index"]
Candidate --> FetchExisting["Fetch Existing Indexes via getIndexes"]
FetchExisting --> PrefixCheck{"Candidate a Prefix of Existing Index?"}
PrefixCheck -->|Yes| RejectRedundant["REJECT — Existing Index Satisfies Query"]
PrefixCheck -->|No| SubsumeCheck{"Candidate Subsumes Existing Index?"}
SubsumeCheck -->|Yes| FlagReplacement["RECOMMEND DROP — Replace Narrow Index"]
SubsumeCheck -->|No| CardinalityCheck["Check Cardinality & Multikey Bounds"]
CardinalityCheck --> Approved["Approved Spec — Stage Rolling Build"]
1. The Equality, Sort, Range (ESR) Rule
Compound index keys must follow strict ESR ordering:
$$\text{Index Key Order} = [\text{Equality Fields}] \longrightarrow [\text{Sort Fields}] \longrightarrow [\text{Range Fields}]$$
- Equality (
E) First: Exact-match predicates ({ tenant_id: "T-102", status: "ACTIVE" }) narrow the B-tree search to a single contiguous branch. Order higher-cardinality equality fields first when sharing prefixes across multiple query shapes. Note that$inbehaves like equality when combined with no sort, or as multiple equality branches when sorted; however, large$inarrays paired with a sort force a blockingSORTunless the index covers the sort key cleanly. - Sort (
S) Second: Sort fields (.sort({ created_at: -1 })) immediately follow equality keys so WiredTiger reads leaf entries in exact output order, eliminating any blockingSORTstage and avoiding the 100 MBinternalQueryMaxBlockingSortMemoryUsageBytesabort threshold. Remember that B-tree index traversal can walk a single-field or compound sort key in reverse (-1) only if all sort fields match the index direction or its exact inverse ({ a: 1, b: -1 }satisfies{ a: 1, b: -1 }and{ a: -1, b: 1 }, but not{ a: 1, b: 1 }). - Range (
R) Last: Inequality predicates ($gt,$gte,$lt,$lte,$ne,$regex) scan across multiple B-tree leaf ranges and must come last. Placing a range key before a sort key (E-R-S) breaks sort order guarantees and forces an in-memorySORT. - Covered Queries (
PROJECTION_COVERED): When every field in the filter, sort, and projection exists in the index—and_idis explicitly excluded ({ _id: 0 }) unless_idis part of the index—explain()reportsPROJECTION_COVEREDwithtotalDocsExamined: 0, avoiding collection document fetches entirely.
2. Algorithmic Prefix Deduplication and Subsumption
Given { tenant_id: 1, status: 1, created_at: -1 }, MongoDB natively satisfies queries on { tenant_id: 1 }, { tenant_id: 1, status: 1 }, and { tenant_id: 1, status: 1 } sorted by created_at: -1. When a proposed index is a left-prefix of an existing index, the engine rejects it immediately. Conversely, when a new ESR candidate extends an existing narrower index (and the narrower index is not unique, sparse, expireAfterSeconds, or partialFilterExpression-scoped), the engine schedules a subsumption replacement.
Three index types require explicit subsumption exemptions. First, a partial index (partialFilterExpression) omits non-matching documents to stay small; replacing it with an unfiltered compound index inflates B-tree footprint, while replacing a non-partial index with a partial one causes any query omitting the partial predicate to fall back to COLLSCAN. Second, TTL indexes (expireAfterSeconds) must remain single-field indexes because MongoDB’s background TTL monitor does not evaluate compound keys. Third, unique: true constraints enforce uniqueness strictly across the declared key tuple; widening a unique key ({ email: 1 } to { email: 1, tenant_id: 1 }) weakens the constraint and permits duplicate values.
Before approving any candidate, the validation gate also checks multikey array bounds: if a document field is an array, MongoDB creates an index entry for every element in that array. Indexing two array fields in the same compound index is forbidden by MongoDB (cannot index parallel arrays) because the Cartesian product of two arrays would explode index cardinality. Even a single array field with hundreds of elements multiplies W_mult proportionally on every document update.
Deep Internals: WiredTiger Row-Store B-Trees and Prefix Compression
Every MongoDB collection and secondary index is stored as an independent WiredTiger row-store B-tree file (index-*.wt). Index internal pages default to 4 KB (internal_page_max) to fit CPU L1/L2 caches, while leaf pages store BSON-encoded index keys mapped to RecordId pointers.
Unlike collection data blocks—which are compressed on disk (Snappy or Zstandard) and uncompressed in WiredTiger RAM—secondary index pages remain prefix-compressed inside the WiredTiger cache (prefixCompression: true by default). Consecutive sorted keys share common leading bytes once per page, reducing index RAM footprint at the cost of minor CPU cycles to reconstruct keys during traversal. However, every insert, update, or delete must still traverse each index B-tree from root to leaf, acquire hazard pointers to pin pages during concurrent reads, dirty 4 KB leaf pages, and flush them during the 60-second (or 2 GB journal) checkpoint cycle via fsync.
Diagnostic Telemetry: Auditing $indexStats and Cache Footprint
Audit unused indexes with $indexStats (remembering that counters reset on mongod restart or replica set failover, and that secondary nodes only record reads routed via non-primary read preferences):
db.orders.aggregate([
{ $indexStats: {} },
{ $project: { name: 1, key: 1, ops: "$accesses.ops", since: "$accesses.since" } },
{ $sort: { ops: 1 } }
]);
Inspect physical index sizes and WiredTiger row-store B-tree depth using stats({ indexDetails: true }). Compare totalIndexSize directly against your WiredTiger internal cache budget (by default 50% of (RAM - 1 GB)). When totalIndexSize approaches or exceeds the cache budget, index B-trees evict each other and hot collection documents continuously, turning even indexed point lookups into synchronous EBS gp3 reads. Checking maximum tree depth also flags fragmented B-trees after heavy delete workloads:
const stats = db.orders.stats({ indexDetails: true });
Object.keys(stats.indexSizes).forEach((name) => {
const btree = stats.indexDetails[name]?.btree;
print(name, (stats.indexSizes[name] / 1048576).toFixed(2) + " MB",
"depth=" + btree?.["maximum tree depth"],
"internalPages=" + btree?.["row-store internal pages"]);
});
Automated ESR Synthesizer CLI (mongo_index_synthesizer.py)
#!/usr/bin/env python3
import argparse, json, sys
from pymongo import MongoClient
from pymongo.errors import PyMongoError
RANGE_OPS = {"$gt", "$gte", "$lt", "$lte", "$ne", "$regex"}
def classify_predicates(filter_dict, sort_dict):
eq_fields, range_fields = [], []
for field, cond in filter_dict.items():
if isinstance(cond, dict) and any(op in RANGE_OPS for op in cond):
range_fields.append(field)
else:
eq_fields.append(field)
return eq_fields, list(sort_dict.keys()), range_fields
def synthesize_esr(eq_fields, sort_fields, range_fields, sort_dict):
keys, seen = [], set()
for f, d in [(x, 1) for x in eq_fields] + [(x, sort_dict.get(x, 1)) for x in sort_fields] + [(x, 1) for x in range_fields]:
if f not in seen:
keys.append((f, d))
seen.add(f)
return keys
def check_redundancy(existing, candidate):
cand_names = [k[0] for k in candidate]
subsumed = []
for idx in existing:
ex_names = [k[0] for k in idx.get("key", {}).items()]
if len(ex_names) >= len(cand_names) and ex_names[:len(cand_names)] == cand_names:
return True, f"Left-prefix of {idx.get('name')}", []
if len(cand_names) > len(ex_names) and cand_names[:len(ex_names)] == ex_names:
if idx.get("name") != "_id_" and not idx.get("unique") and "partialFilterExpression" not in idx:
subsumed.append(idx.get("name"))
return False, "", subsumed
How It Rolls Out
Replacing or adding indexes in production follows four gated steps:
- Phase 1 — Synthesize and Deduplicate in CI: Run the ESR synthesizer against slow-query shapes from
mongod.log. Reject any proposal that matches an existing left-prefix or introduces a second array field in a compound index. - Phase 2 — Build the Wider ESR Index: Create the approved compound index using a rolling build protocol during low-traffic windows so secondaries do not breach oplog retention.
- Phase 3 — Verify Plan Adoption: Run
explain("executionStats")on a hidden secondary to confirmIXSCANreplacesCOLLSCANorSORT, and monitor$indexStatsto verifyaccesses.opsshifts onto the new index. - Phase 4 — Drop Subsumed Narrow Indexes: Only after confirming the narrower index is not
unique,sparse, orpartialFilterExpression-scoped—and after 30+ days of uptime—executedb.collection.dropIndex()to reclaim WiredTiger cache and write IOPS. Rollback: recreate the dropped index if a legacy query shape regresses.
In Practice
Documented MongoDB query planner and WiredTiger behaviors explain why ESR ordering and prefix pruning govern cluster stability:
- Prefix Compression and Write Amplification: Per MongoDB’s WiredTiger documentation, every secondary index maintains its own B-tree (
index-*.wt) that must be updated synchronously on writes. KeepingprefixCompression: true(the default) reduces index cache footprint, but does not eliminate the per-index B-tree traversal and dirty-page checkpoint cost (W_mult = 1 + N_indexes). Consolidating redundant left-prefix indexes directly reduces dirty-page generation per insert. - ESR vs.
E-R-SExecution Plans: Per MongoDB’s ESR indexing documentation, placing a range predicate (price: { $gte: 50 }) before a sort field (created_at: -1) forcesmongodto scan all index keys matching the equality prefix and price range, then execute a blockingSORTstage subject to the 100 MBinternalQueryMaxBlockingSortMemoryUsageByteslimit. Ordering the index{ category_id: 1, created_at: -1, price: 1 }allowsIXSCANto return documents increated_atorder directly, eliminating theSORTstage. - Safe Index Retirement with
hideIndex(): Before runningdropIndex()on a subsumed or zero-access index, MongoDB 4.4+ supportsdb.collection.hideIndex("index_name"). Hiding an index removes it from query planner candidate selection while continuing to maintain its B-tree on writes. If an unexpected batch job or reporting query regresses after hiding,unhideIndex()restores the plan instantaneously without a multi-hour index rebuild; if no regressions appear over a full business cycle,dropIndex()reclaims the storage and write amplification. - MongoDB 8.0 Query Controls (
setQuerySettings): When an unindexed or misplanned query shape hits production before an index build completes, MongoDB 8.0 provides persistent, cluster-widesetQuerySettingswithindexHints(replacing deprecatedplanCacheSetFilter) to constrain candidate indexes:
db.adminCommand({
setQuerySettings: {
find: "orders",
filter: { "tenant_id": "T-100", "status": "ACTIVE" },
sort: { "created_at": -1 },
$db: "production_commerce"
},
settings: {
indexHints: {
ns: { db: "production_commerce", coll: "orders" },
allowedIndexes: ["tenant_id_1_status_1_created_at_-1"]
}
}
});
Where It Breaks
| Operational Action | Physical Failure Mechanism | Architectural Consequence | Safe Mitigation Protocol |
|---|---|---|---|
| Low-Cardinality Leading Keys | Leading boolean or status field ({ is_active: 1, user_id: 1 }). | Fails to partition B-tree; forces wide scans and wastes cache. | Put high-cardinality equality keys first or use partialFilterExpression. |
| Parallel Array Multikey Index | Two array fields in one compound index ({ tags: 1, categories: 1 }). | MongoDB rejects writes (cannot index parallel arrays). | Enforce schema lint rules allowing at most one array field per index. |
| Dropping After Recent Restart | Reading $indexStats ops == 0 shortly after mongod restart. | Counters reset on restart; drops indexes needed by monthly batches. | Require 30+ days continuous uptime before approving index drops. |
| Concurrent Primary Index Builds | Building large indexes on primary during peak write traffic. | Saturates EBS IOPS and causes secondary replication lag. | Use rolling builds or schedule during low-write maintenance windows. |
| Oversized String Index Keys | Indexing raw multi-KB URLs or payloads (4.2+ removed 1,024-byte cap). | Bloats WiredTiger index cache and reduces B-tree fanout. | Use hashed indexes or store a fixed-length SHA-256 hash field. |
| Partial Index Filter Mismatch | Query omits the predicate defined in partialFilterExpression. | Planner cannot prove coverage and falls back to COLLSCAN. | Verify query filters strictly imply the partial filter predicate. |
| Subsuming a Unique Index | Dropping { email: 1 } (unique: true) for { email: 1, tenant_id: 1 }. | Removes uniqueness enforcement on email, allowing duplicates. | Block automated drops on any index with unique or sparse flags. |
| Over-Indexing Write-Heavy Tables | Maintaining >10–15 indexes on high-insert collections. | Synchronous write amplification exhausts dirty-cache eviction. | Prune left-prefixes via ESR and cap total index count per collection. |
Key Takeaways
- Every index adds synchronous write overhead: WiredTiger updates
1 + N_indexesrow-store B-trees per insert, directly consuming dirty-cache budget and EBSgp3IOPS. - Strict ESR ordering eliminates blocking sorts: Ordering keys as
Equality -> Sort -> Rangesatisfies sorting natively from the B-tree and avoids the 100 MBinternalQueryMaxBlockingSortMemoryUsageByteslimit. - Left-prefix pruning prevents catalog bloat: Reject any proposed index that is a left-prefix of an existing compound index, and subsume narrower non-unique indexes only after verifying plan adoption.
- Guardrails beat blind automation: Never drop indexes with
unique: trueorpartialFilterExpressionvia prefix subsumption, and never trust$indexStatsuntilmongoduptime spans at least 30 days.
What to Do Next
- Problem: Production collections accumulate overlapping left-prefix indexes and misordered compound keys that degrade write throughput and trigger blocking sorts.
- Solution: Enforce an automated ESR synthesizer and prefix-deduplication gate in CI/CD before any
createIndex()reaches production. - Proof: Run
$indexStatsandstats({ indexDetails: true })to identify zero-access indexes and measure total index RAM footprint against collection data size. - Action: Audit your highest-write collection this week for left-prefix duplicates, verify
uniqueandpartialFilterExpressionconstraints, and scheduledropIndex()for confirmed redundant prefixes.