Why this needs a checklist
Since 4.2, index builds no longer hold an exclusive lock for their whole duration. They take brief exclusive locks only at the start and end. Since 4.4 they run on the primary and secondaries at the same time and commit only when a commit quorum of members is ready. That is much safer than the old foreground/background split. It also brings failure modes that only appear on large collections: a build that never commits, secondaries that lag, disks that fill with external-sort files, and a node restart that resumes a half-finished build.
Work through this list before you run createIndexes against a collection of hundreds of millions of documents.
1. Decide whether you need it at all
- The index is justified by
explain("executionStats")on the real query, not by guesswork. ChecktotalKeysExaminedvsnReturned. - No existing index already covers it as a prefix (
{a:1}is redundant when{a:1,b:1}exists, unless it is unique or partial). - You know the write cost: every insert and every update to an indexed field now maintains one more index.
- Partial (
partialFilterExpression) or sparse indexes were considered for skewed data.
db.orders.aggregate([{ $indexStats: {} }]) // find unused indexes you can drop to make room
2. Capacity before you start
- Disk: free space on every data-bearing member covers the final index size plus temporary sort files in
<dbpath>/_tmp. Estimate from a build on a restored copy, or fromdb.coll.stats().indexSizeson a similar index. - Build memory:
maxIndexBuildMemoryUsageMegabytesdefaults to 200 MB percreateIndexescommand, shared across all indexes in that command. Past that, the build spills to disk. Raising it speeds large builds but takes memory from the WiredTiger cache's neighbours. It cannot be changed on Atlas.
db.adminCommand({ getParameter: 1, maxIndexBuildMemoryUsageMegabytes: 1 })
db.adminCommand({ setParameter: 1, maxIndexBuildMemoryUsageMegabytes: 1024 }) // on every member
- Oplog window comfortably exceeds the expected build time plus margin. A slow secondary falls behind during the build, and a short window can make it go stale.
rs.printReplicationInfo() // log length start to end
rs.printSecondaryReplicationInfo() // current lag per secondary
- Recent versions (7.1+) can abort an index build when free disk drops below
indexBuildMinAvailableDiskSpaceMB. Check the parameter and its default for your version withgetParameterrather than relying on it.
3. Commit quorum
The default commitQuorum is "votingMembers": every data-bearing voting member must finish its build before the index commits.
- All voting data-bearing members are healthy (
rs.status()). If one voting member is down, the build sits in a waiting state until it returns or you lower the quorum. - If any member has
buildIndexes: false, the default quorum cannot be used. Pass an explicit number or"majority". - You have chosen deliberately:
| commitQuorum | Effect | Use when |
|---|---|---|
"votingMembers" (default) | Commit only when all voting members are ready | Normal case; avoids a lagging member committing later |
"majority" | Commit when a majority are ready | A member is down for maintenance or chronically slow |
<n> | Commit when n members are ready | Specific topologies |
0 | No quorum; primary commits when it finishes | Rarely. Secondaries may then build at commit time and lag |
db.orders.createIndex(
{ customerId: 1, orderDate: -1 },
{ name: "customerId_1_orderDate_-1" },
"majority" // commitQuorum
)
// Change it while the build is running, e.g. a member went down
db.runCommand({
setIndexCommitQuorum: "orders",
indexNames: ["customerId_1_orderDate_-1"],
commitQuorum: "majority"
})
4. Run and monitor
- Started from a session that won't be killed by a client timeout. The build continues server-side either way, but your tooling should not retry and start a second one.
- Progress is being watched:
db.currentOp({
$or: [
{ op: "command", "command.createIndexes": { $exists: true } },
{ op: "none", msg: /^Index Build/ }
]
})
Look at msg and progress (done/total) on each member. Run it on secondaries too.
- Lag, cache pressure and disk are on a dashboard for the duration: replication lag per secondary, WiredTiger cache dirty %,
_tmpdirectory size, free disk. - mongod logs are filtered for the build's messages: index build started, scanning, committing, completion and failure.
Warning
A secondary can lag badly when it reaches the commit point and must drain its side writes. Writes during the build are recorded in a side table and applied at the end, so a long build on a write-heavy collection has a large drain. Prefer building during lower write volume.
5. Aborting safely
- You know the abort command, and that it must run on the primary:
db.orders.dropIndex("customerId_1_orderDate_-1") // aborts an in-progress build
- You do not use
killOpon secondaries to stop a build. Secondaries cannot abort on their own. The primary coordinates, and killing on a secondary can make the node fatal-assert. - You understand restarts: an unfinished build on a cleanly shut-down node resumes from its checkpoint (4.4+ resumable builds). After an unclean shutdown it may restart from scratch.
6. Sharded clusters
- Run
createIndexesthroughmongos. It builds on every shard that owns chunks for the collection. - Each shard is its own replica set with its own commit quorum, disk and lag. Check every shard, not just one.
- Verify consistency afterwards:
db.adminCommand({ checkMetadataConsistency: 1 }) // 7.0+; reports inconsistent indexes among other issues
On older versions, compare getIndexes() per shard.
- For a unique index on a sharded collection, the shard key is a prefix of the index. Otherwise uniqueness cannot be enforced.
7. When to do a rolling build instead
Prefer a rolling build, one member at a time with the node out of the replica set, when:
- the collection is so large that build time exceeds a safe oplog window, or
- the primary cannot absorb the extra I/O and cache pressure during peak hours, or
- secondaries are already near their lag limits.
The outline for each secondary:
- Shut it down cleanly.
- Restart it as a standalone on a different port, without
replication.replSetName, withdisableLogicalSessionCacheRefresh=true(as the MongoDB procedure for your version specifies). - Build the index.
- Restart it normally and wait until it has caught up.
Then rs.stepDown() the primary and repeat on it. For sharded clusters, stop the balancer first and repeat per shard.
Caution
A rolling build creates a window where members have different indexes. A unique index built this way can diverge if duplicates are written meanwhile. Follow the version-specific MongoDB procedure exactly, and do not use rolling builds for unique indexes unless writes that could violate them are stopped.
8. After the build
-
getIndexes()shows the index on every member, or every shard. -
explain()uses it for the target query. - Write latency and replication lag are back to baseline.
- Any temporary increase to
maxIndexBuildMemoryUsageMegabyteshas been reverted, if you want the default back. - The index definition is in source control and in your schema migration tool, so environments don't drift.
Prevent it next time
- Create indexes when collections are small. Ship indexes with the feature, not after the incident.
- Keep oplog sizing and free-disk targets that allow a full build of your largest index.
- Review
$indexStatsquarterly and drop unused indexes. Each one makes every future build and every write more expensive.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get