Lesson 6 of 9 · 24m
Indexing Pitfalls That Only Appear in Production
Selectivity, write amplification, regex scans, skip pagination, TTL, partial indexes, and the operational cost of every extra key.
Indexes are not free performance. Every index is another structure updated on writes, cached in memory, replicated to secondaries, and carried through backups and restores. The skill is not adding indexes; it is knowing which ones deserve to exist.
Low-selectivity indexes often lose
An index on status where 97% of documents are "active" rarely pays for itself. The database reads a huge fraction of the index and then fetches most documents anyway. Compound indexes rescue this when paired with a selective equality field such as tenantId:
db.tasks.createIndex({ tenantId: 1, status: 1, updatedAt: -1 })Partial indexes are sharper when only a minority of documents matter:
db.users.createIndex({ email: 1 }, { unique: true, partialFilterExpression: { deletedAt: { $exists: false } } })That preserves unique email among live users without locking out old soft-deleted records forever.
Beware the write amplification bill
Each insert updates every matching index. Updates may touch indexes even when the query predicate did not. Ten indexes do not mean "ten times faster reads"; they often mean every write performs extra B-tree maintenance. On write-heavy collections, removing an unused index can improve p99 latency more than adding another ever will.
Query shapes that defeat indexes
- Leading-wildcard regex (
/foo/,/^.*foo/) and$whereJavaScript expressions are collection-scan machines. - Expressions that transform the indexed field in the predicate (for example
$toLower); use a collation or store a normalized field instead. - Deeply nonselective
$inlists that expand into dozens or hundreds of branches.
Anchored regex such as /^maya/ can use an index because MongoDB can seek the prefix range; substring scans cannot.
Skip pagination degrades linearly
.skip(100000).limit(50) scans and discards 100,000 results. Use keyset pagination instead:
db.orders.find({ tenantId: t, $or: [
{ createdAt: { $lt: lastSeenCreatedAt } },
{ createdAt: lastSeenCreatedAt, _id: { $lt: lastSeenId } }
]}).sort({ createdAt: -1, _id: -1 }).limit(50)Add _id as a tie-breaker because timestamps repeat. Verify explain for the $or boundary because planner versions optimize it differently; when it is indexed well, page 1,000 is approximately as cheap as page 2.
TTL indexes are deletion systems, not archiving systems
db.sessions.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 })The TTL monitor deletes expired documents roughly once a minute, not exactly at expiry. Do not use TTL as a compliance boundary or precise eviction mechanism. It is excellent janitorial automation, not a legally binding shredder.
Field notes
- Check
db.orders.aggregate([{ $indexStats: {} }])before deleting indexes; check again after. - Unique partial indexes are powerful but easy to misunderstand. Test insertion paths for documents that do not match the filter.
- Sparse indexes omit missing fields; partial indexes include documents matching a predicate. They overlap sometimes, but they are not synonyms.
- Every index design decision is a read/write trade. State the trade out loud in review.
Was this lesson helpful?