Building Indexes on Billion-Document Collections Without Breaking Production
Building an index on a billion documents is an operational stress test that exercises every layer of database infrastructure: filesystem page caches, WiredTiger eviction threads, _tmp disk sort spills, and replica set oplog retention.
TL;DR
- Problem: Building an index on a multi-terabyte collection with the default 200 MB sort buffer (
maxIndexBuildMemoryUsageMegabytes) spills hundreds of run files todbPath/_tmp, saturating EBSgp3IOPS and pushing lagging secondaries off the oplog window.- Answer: Pre-calculate temporary disk space ($S_{\text{temp}} \times 2.0$), resize the oplog online via
replSetResizeOplogto at least2.5xestimated build duration, raisemaxIndexBuildMemoryUsageMegabytes(e.g., 4,096 MB), and run withcommitQuorum: "majority"(or use a rolling standalone build on IOPS-constrained tiers).- Watch out: Default
commitQuorumis"votingMembers"—not"majority"—so one offline voting secondary stalls commit indefinitely unless overridden viasetIndexCommitQuorum.
Production Scope: MongoDB 4.4 – 8.0 on AWS EC2 + EBS
gp3
Situation
Enterprise MongoDB replica sets on AWS EC2 (r6g.4xlarge with 128 GB RAM and EBS gp3 volumes) routinely host transactional, telemetry, and ledger collections exceeding one billion documents and multiple terabytes of uncompressed data. When product teams add new composite query filters, executing them without a matching compound index triggers collection scans that evict hot working-set pages from WiredTiger cache.
Creating a new B-tree index on a 3 TB collection requires scanning every document, extracting and sorting billions of keys, and writing a new index file—all while serving live reads and writes under strict p99 latency budgets. Without pre-flight capacity math and replication safeguards, the build itself triggers I/O starvation or forces secondaries into RECOVERING state.
The Problem
The Concurrency and Replication Collision
Prior to MongoDB 4.2, operators chose between foreground builds (which held an exclusive collection lock, halting all reads and writes) and background builds (which yielded to traffic but were single-threaded and produced fragmented B-trees). MongoDB 4.4 unified index creation into a simultaneous replicated hybrid build that holds only brief locks at the start and commit phases. However, at billion-document scale, three physical constraints still break production clusters:
- External Sort Memory Exhaustion (
_tmpDisk Spill): Key extraction sorts all generated index keys using a buffer governed bymaxIndexBuildMemoryUsageMegabytes(default 200 MB percreateIndexescommand in MongoDB 4.4 through 8.0). Once extracted keys exceed 200 MB, MongoDB flushes sorted run files todbPath/_tmp/. On baseline EBSgp3volumes (3,000 IOPS, 125 MB/s), multi-pass merge sorting across hundreds of run files saturates disk queues. - Side Writes Table Cache Pressure: While the collection scan traverses existing records, concurrent inserts, updates, and deletes are intercepted into an internal Side Writes Table backed by a WiredTiger structure. During a multi-hour scan under heavy write traffic, intercepted mutations consume WiredTiger cache and spill to temporary storage if memory limits are reached.
- Oplog Window Rollover on Secondaries: Replicated builds run simultaneously on the primary and all secondaries. Each secondary must execute the index scan and merge sort while simultaneously applying the live replication oplog stream. If secondary replication lag widens beyond
local.oplog.rsretention, the secondary falls off the oplog (RECOVERING) and requires a multi-day initial sync.
The core engineering question is: How can platform engineers build compound indexes on billion-document collections without exhausting _tmp disk space, saturating EBS IOPS, or pushing secondaries past the oplog retention window?
Options Considered
| Strategy | Traffic Impact | EBS I/O Profile | Failover / Quorum Risk | Decision |
|---|---|---|---|---|
| Legacy Foreground Build (Pre-4.2) | Exclusive lock halts all reads & writes | High burst on primary, then secondaries | Causes immediate application outage | Rejected: Unacceptable downtime; removed in 4.4+ |
Replicated Hybrid (Default votingMembers) | Concurrent reads & writes allowed | Simultaneous across all nodes | Single offline secondary blocks commit | Rejected as Default: Risky if any voting node drops |
Replicated Hybrid (commitQuorum: "majority") | Concurrent reads & writes; zero stepdowns | Simultaneous; requires 2.5x oplog + 4 GB sort RAM | Tolerates minority node outage | Chosen: Standard protocol when EBS IOPS have headroom |
| Rolling Standalone Secondary Build | Concurrent; requires planned stepDown | Isolated to 1 node at a time off-cluster | Requires careful voting quorum & priority management | Chosen for Tight IOPS: Best when EBS cannot sustain simultaneous sort |
Legacy foreground builds are unusable for 24/7 systems, and the default commitQuorum: "votingMembers" stalls indefinitely if a single secondary restarts or lags offline. Teams should choose Replicated Hybrid with commitQuorum: "majority" when EBS IOPS and oplog headroom can absorb simultaneous builds, and Rolling Standalone Builds when EBS throughput is tightly constrained or when validating unique indexes without risking a late primary abort.
The Hybrid Index Build Architecture: Phases, Side Writes, and Quorum
A replicated hybrid build coordinates state across the primary and all secondaries through four distinct phases over local.oplog.rs.
flowchart TD
Client["Application Ingest — Concurrent Writes"] --> Primary["mongod Primary Node"]
Primary --> Init["Phase 1: Catalog Init — Intent Lock & UUID"]
Init --> Scan["Phase 2: Collection Scan — Cursor Read"]
Scan --> ExtSort["Phase 3: External Sort — Spill to _tmp"]
ExtSort --> Drain["Phase 4: Side Writes Drain — Apply Buffered Writes"]
Client -.->|Intercepted Writes| SideTable["Side Writes Table"]
SideTable -.-> Drain
Primary -->|Oplog startIndexBuild| Sec1["Secondary 1 — Simultaneous Build"]
Primary -->|Oplog startIndexBuild| Sec2["Secondary 2 — Simultaneous Build"]
Drain --> Vote["Primary Ready — Awaiting Quorum"]
Sec1 -->|voteCommitIndexBuild| Vote
Sec2 -->|voteCommitIndexBuild| Vote
Vote -->|commitQuorum majority| Commit["Phase 5: commitIndexBuild — Index Ready"]
Deep Mechanics of the Four Phases
- Phase 1 — Catalog Init: The primary acquires a brief intent lock, assigns a build UUID, and writes
startIndexBuildtolocal.oplog.rs. Secondaries read this entry and launch local index build threads simultaneously. - Phase 2 — Collection Scan & Side Writes Interception: Each node scans its local collection via storage cursors. Concurrent writes targeting the collection are intercepted into the Side Writes Table (a temporary WiredTiger structure) so the scan sees a consistent baseline without holding a collection-wide write lock.
- Phase 3 — External Key Sort & Merge: Extracted keys fill the
maxIndexBuildMemoryUsageMegabytesbuffer. When full, sorted runs flush todbPath/_tmp/. After the scan finishes, MongoDB runs an N-way merge sort and inserts ordered keys sequentially into the new B-tree file (index-*.wt), avoiding random page splits. - Phase 4 — Side Writes Drain & Commit Quorum: The builder drains all intercepted mutations from the Side Writes Table into the B-tree, then writes
voteCommitIndexBuildto the oplog. Once votes satisfycommitQuorum(default"votingMembers", or"majority"when explicitly configured), the primary writescommitIndexBuildand all nodes mark the indexready: true.
Note on restarts: starting in MongoDB 4.4, clean shutdowns (SIGTERM or db.shutdownServer()) checkpoint hybrid build progress to disk and resume automatically on restart when commitQuorum is "votingMembers" or "majority". Only unclean crashes (SIGKILL, OOM killer, power loss) discard _tmp and restart the build from zero.
Sizing and Capacity Engineering Formulas
1. Temporary Disk Space ($S_{\text{temp}}$)
During Phase 3, external sort run files occupy temporary disk space in dbPath/_tmp/:
$$S_{\text{temp}} = N_{\text{documents}} \times \text{AvgKeySize} \times C_{\text{overhead}}$$
For $N_{\text{documents}} = 1,000,000,000$, $\text{AvgKeySize} \approx 64\text{ bytes}$ (e.g., { account_id: UUID, created_at: Date, status: String }), and framing overhead $C_{\text{overhead}} \approx 1.35$:
$$S_{\text{temp}} = 1,000,000,000 \times 64\text{ B} \times 1.35 \approx 86.4\text{ GB}$$
Ensure free disk space on the EBS volume hosting dbPath exceeds $S_{\text{temp}} \times 2.0$ (at least ~175 GB free for this example). The $2.0\times$ multiplier is non-negotiable because during Phase 3’s N-way external merge sort, the _tmp run files and the newly populated index-*.wt B-tree file coexist on disk simultaneously until the merge completes and _tmp is unlinked. Relying on MongoDB’s default indexBuildMinAvailableDiskSpaceMB (500 MB) as a safety net is too late—by the time free space drops to 500 MB, the node is already at risk of oplog or journal write failure.
2. Required Oplog Retention Window ($T_{\text{oplog}}$)
Size local.oplog.rs to hold at least $2.5\times$ the estimated build duration ($T_{\text{build}}$):
$$S_{\text{oplog}} = \text{WriteRate}{\text{MB/s}} \times (T{\text{build}} \times 2.5) \times 3,600\text{ s/hr}$$
At $2.5\text{ MB/s}$ average write ingest and an estimated 24-hour build ($60\text{ hours}$ retention):
$$S_{\text{oplog}} = 2.5\text{ MB/s} \times 60\text{ hr} \times 3,600\text{ s/hr} = 540,000\text{ MB} \approx 540\text{ GB}$$
Diagnostic Telemetry: currentOp and Oplog Window Monitoring
Track active build phase, completion percentage, and runtime via db.currentOp():
db.currentOp({ "command.createIndexes": { $exists: true } }).inprog.forEach((op) => {
const p = op.progress || {};
const pct = p.total ? ((p.done / p.total) * 100).toFixed(1) : "N/A";
print(`opid=${op.opid} msg="${op.msg}" progress=${pct}% hours=${(op.secs_running / 3600).toFixed(2)}`);
});
Monitor oplog retention hours and secondary lag continuously:
const status = rs.status();
const primary = status.members.find((m) => m.stateStr === "PRIMARY");
const oplog = db.getSiblingDB("local").oplog.rs;
const first = oplog.find().sort({ $natural: 1 }).limit(1).next();
const last = oplog.find().sort({ $natural: -1 }).limit(1).next();
print("Oplog Window (hrs):", ((last.ts.getHighBits() - first.ts.getHighBits()) / 3600).toFixed(2));
status.members.filter((m) => m.stateStr === "SECONDARY").forEach((m) => {
print(m.name, "lagSecs=", (primary.optimeDate.getTime() - m.optimeDate.getTime()) / 1000);
});
Pre-Flight Automation (mongo_index_preflight.py)
#!/usr/bin/env python3
import argparse, sys
from pymongo import MongoClient
from pymongo.errors import PyMongoError
def evaluate_preflight(client, namespace, est_hours):
db_name, coll_name = namespace.split(".", 1)
stats = client[db_name][coll_name].aggregate([{"$collStats": {"storageStats": {}}}]).next()["storageStats"]
oplog = client.local.oplog.rs
first = oplog.find().sort([("$natural", 1)]).limit(1).next()
last = oplog.find().sort([("$natural", -1)]).limit(1).next()
window_hrs = (last["ts"].time - first["ts"].time) / 3600.0
sort_mb = client.admin.command({"getParameter": 1, "maxIndexBuildMemoryUsageMegabytes": 1})["maxIndexBuildMemoryUsageMegabytes"]
active = client.admin.command("currentOp", {"command.createIndexes": {"$exists": True}}).get("inprog", [])
print(f"docs={stats['count']:,} sizeGB={stats['size']/1024**3:.1f} oplogHrs={window_hrs:.1f} sortMB={sort_mb} activeBuilds={len(active)}")
if window_hrs < est_hours * 2.5 or active:
sys.exit("PRE-FLIGHT FAILED: insufficient oplog window or concurrent build active")
How It Rolls Out
Execute replicated hybrid builds across four gated steps (or switch to rolling standalone builds on each secondary sequentially if EBS IOPS cannot sustain simultaneous sorting):
- Phase 1 — Expand Oplog Online: Run
db.adminCommand({ replSetResizeOplog: 1, size: 409600 })(size in MB, here 400 GB) across nodes to guarantee>= 2.5xbuild duration headroom. - Phase 2 — Raise Sort Memory Buffer: Increase
maxIndexBuildMemoryUsageMegabytes(for example to4096MB on a 128 GB RAM host) so the sorter writes fewer, larger run files to_tmp/:db.adminCommand({ setParameter: 1, maxIndexBuildMemoryUsageMegabytes: 4096 }); - Phase 3 — Launch Serialized Build in
tmux: Run onecreateIndexescommand at a time withcommitQuorum: "majority"(passed as the 3rd argument increateIndex(), or top-level inrunCommand):db.orders.createIndex( { "account_id": 1, "created_at": -1, "status": 1 }, { name: "idx_account_created_status" }, "majority" ); - Phase 4 — Monitor & Rollback Gate: Poll
db.currentOp()and secondary replication lag every 5 minutes. If secondary lag approaches 50% of the oplog window or an offline node blocks commit, abort cleanly viadb.orders.dropIndex("idx_account_created_status")or adjust quorum withdb.adminCommand({ setIndexCommitQuorum: "orders", indexNames: ["idx_account_created_status"], commitQuorum: "majority" }).
If EBS gp3 volumes on secondaries cannot sustain simultaneous merge sorting alongside live oplog writes, use Protocol B (Rolling Standalone Build) instead: remove one secondary from replication, restart it standalone on a non-default port without --replSet, run createIndex() locally with full host RAM, restart it with --replSet on its standard port to catch up on the oplog, repeat across all secondaries, and finally run rs.stepDown() on the primary to build on the former primary. Note that rolling builds cannot enforce unique: true across concurrent writes until all nodes are built, and each standalone window temporarily reduces replica set redundancy by one member.
In Practice
Documented MongoDB storage engine and replication behaviors explain why pre-flight sizing and commitQuorum selection govern billion-row index builds:
- Sort Buffer Size vs.
_tmpI/O Amplification: Per MongoDB’smaxIndexBuildMemoryUsageMegabytesdocumentation, the default 200 MB limit applies percreateIndexescommand and is shared equally if multiple indexes are created in one command. On billion-document collections, raising this parameter on hosts with ample RAM reduces the number of sorted run files spilled todbPath/_tmp/, cutting multi-pass random merge I/O on EBS volumes. Fewer run files also reduces the number of open file descriptors and sequential merge passes required before B-tree insertion begins. - Side Writes Table Drain and
commitQuorum: Per MongoDB’s hybrid index build architecture, concurrent writes during the collection scan are buffered in the Side Writes Table (a WiredTiger skiplist/B-tree structure) and applied before voting. On write-heavy collections, a multi-hour collection scan accumulates millions of intercepted mutations that must be drained into the new B-tree beforevoteCommitIndexBuildis written. BecausecommitQuorumdefaults to"votingMembers", a single unreachable or hardware-failed voting secondary prevents the primary from writingcommitIndexBuild—keeping all nodes holding the index build state until the node recovers or an operator runssetIndexCommitQuorumto lower the quorum to"majority"or an explicit integer count. - Oplog Entry Amplification During Builds: Unlike individual document writes, a replicated hybrid index build writes only
startIndexBuild,voteCommitIndexBuild, andcommitIndexBuildcoordination entries tolocal.oplog.rs—it does not replicate every B-tree key over the network. The oplog risk comes from the duration of the build: while a secondary’s CPU and EBS IOPS are saturated by its local_tmpmerge sort, its oplog applier falls behind the primary’s write rate, consuming the oplog retention window. If a lagging secondary drops intoRECOVERING, its only recovery path is a full initial sync or snapshot restore. - MongoDB 8.0 Replication & Disk Safeguards: MongoDB 8.0 retains the 200 MB
maxIndexBuildMemoryUsageMegabytesdefault and ignores legacybackground: trueas a safe no-op. However, MongoDB 8.0 improves secondary oplog throughput via parallel oplog writer/applier paths and enforcesindexBuildMinAvailableDiskSpaceMBto halt an index build cleanly before_tmpspills exhaust the filesystem.
Where It Breaks
| Operational Hazard | Physical Failure Mechanism | Architectural Consequence | Safe Mitigation Protocol |
|---|---|---|---|
| Unclean Crash During Build | OOM killer or SIGKILL terminates mongod mid-build. | Clean SIGTERM checkpoints progress (4.4+); hard crash discards _tmp and restarts from 0%. | Maintain RAM headroom; use systemctl stop (SIGTERM) for maintenance. |
| Oplog Rollover on Secondaries | Secondary merge sort + oplog apply lags past local.oplog.rs window. | Secondary enters RECOVERING and requires a full initial sync. | Expand oplog via replSetResizeOplog to >= 2.5x build duration first. |
Exhausting dbPath/_tmp Disk | External sort run files exceed free space on the EBS volume. | mongod crashes on disk full (or aborts in 8.0 at indexBuildMinAvailableDiskSpaceMB). | Verify free disk space exceeds $S_{\text{temp}} \times 2.0$ before starting. |
Shell Disconnect Without tmux | Laptop SSH drops mid-build; operator re-issues createIndex(). | Build continues on server; duplicate command creates confusion or contention. | Run inside tmux on a bastion host and track via db.currentOp(). |
| Unique Index Dupe on Ingest | Concurrent write inserts a duplicate key during Phase 2 scan. | Build aborts during final Side Writes drain, discarding hours of work. | Deduplicate data and enforce app-level uniqueness checks before building. |
| Side Writes Cache Pressure | Heavy write ingest during long scan fills WiredTiger cache. | Eviction stalls trigger flow control and throttle application writes. | Schedule builds off-peak or throttle batch ingest jobs during scan. |
Default votingMembers Hang | One voting secondary goes offline while build is in progress. | Primary waits indefinitely for the missing voteCommitIndexBuild. | Pass "majority" as commitQuorum or run setIndexCommitQuorum. |
| Parallel Builds on Same Volume | Running two createIndexes commands concurrently. | Sorters split the 200 MB buffer and compete for EBS IOPS, doubling lag. | Serialize index builds strictly: one active createIndexes per replica set. |
Key Takeaways
- Do the $S_{\text{temp}}$ and oplog math before running
createIndex(): Ensure free disk space exceeds $S_{\text{temp}} \times 2.0$ and resizelocal.oplog.rsonline to>= 2.5xestimated build time. - Raise
maxIndexBuildMemoryUsageMegabytesfrom its 200 MB default: Allocating 2–4 GB on memory-optimized EC2 nodes slashes_tmpdisk run files and EBS merge-sort IOPS. - Override the
"votingMembers"commitQuorumdefault: Pass"majority"(as the 3rd argument tocreateIndex()) so a single offline secondary cannot stall commit indefinitely. - Clean
SIGTERMresumes;SIGKILLor OOM restarts from zero: MongoDB 4.4+ checkpoints hybrid builds on clean shutdown, but hard crashes discard_tmp. - Serialize builds and keep
dropIndex()ready: Run one index build at a time per replica set, and abort viadropIndex()if secondary lag threatens the oplog window.
What to Do Next
- Problem: Large-collection index builds risk
_tmpdisk exhaustion, EBS I/O saturation, and secondary oplog rollover. - Solution: Standardize on a pre-flight gate that verifies
>= 2x S_tempfree disk, resizes the oplog to>= 2.5xbuild duration, bumpsmaxIndexBuildMemoryUsageMegabytes, and setscommitQuorum: "majority". - Proof: Check current oplog retention hours via
local.oplog.rsand confirmmaxIndexBuildMemoryUsageMegabytesviagetParameter. - Action: Run the pre-flight verification script against your largest collection this week before scheduling its next compound index build.