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 to dbPath/_tmp, saturating EBS gp3 IOPS 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 replSetResizeOplog to at least 2.5x estimated build duration, raise maxIndexBuildMemoryUsageMegabytes (e.g., 4,096 MB), and run with commitQuorum: "majority" (or use a rolling standalone build on IOPS-constrained tiers).
  • Watch out: Default commitQuorum is "votingMembers"—not "majority"—so one offline voting secondary stalls commit indefinitely unless overridden via setIndexCommitQuorum.

Size oplog, sort memory, and commit quorum before building at billion-row scale

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:

  1. External Sort Memory Exhaustion (_tmp Disk Spill): Key extraction sorts all generated index keys using a buffer governed by maxIndexBuildMemoryUsageMegabytes (default 200 MB per createIndexes command in MongoDB 4.4 through 8.0). Once extracted keys exceed 200 MB, MongoDB flushes sorted run files to dbPath/_tmp/. On baseline EBS gp3 volumes (3,000 IOPS, 125 MB/s), multi-pass merge sorting across hundreds of run files saturates disk queues.
  2. 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.
  3. 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.rs retention, the secondary falls off the oplog (RECOVERING) and requires a multi-day initial sync.

Simultaneous builds can push lagging secondaries off the oplog

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

StrategyTraffic ImpactEBS I/O ProfileFailover / Quorum RiskDecision
Legacy Foreground Build (Pre-4.2)Exclusive lock halts all reads & writesHigh burst on primary, then secondariesCauses immediate application outageRejected: Unacceptable downtime; removed in 4.4+
Replicated Hybrid (Default votingMembers)Concurrent reads & writes allowedSimultaneous across all nodesSingle offline secondary blocks commitRejected as Default: Risky if any voting node drops
Replicated Hybrid (commitQuorum: "majority")Concurrent reads & writes; zero stepdownsSimultaneous; requires 2.5x oplog + 4 GB sort RAMTolerates minority node outageChosen: Standard protocol when EBS IOPS have headroom
Rolling Standalone Secondary BuildConcurrent; requires planned stepDownIsolated to 1 node at a time off-clusterRequires careful voting quorum & priority managementChosen 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.

Replicated hybrid builds vs rolling standalone secondary builds

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.

Hybrid build coordinates scan, side writes, and commit quorum via oplog

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

  1. Phase 1 — Catalog Init: The primary acquires a brief intent lock, assigns a build UUID, and writes startIndexBuild to local.oplog.rs. Secondaries read this entry and launch local index build threads simultaneously.
  2. 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.
  3. Phase 3 — External Key Sort & Merge: Extracted keys fill the maxIndexBuildMemoryUsageMegabytes buffer. When full, sorted runs flush to dbPath/_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.
  4. Phase 4 — Side Writes Drain & Commit Quorum: The builder drains all intercepted mutations from the Side Writes Table into the B-tree, then writes voteCommitIndexBuild to the oplog. Once votes satisfy commitQuorum (default "votingMembers", or "majority" when explicitly configured), the primary writes commitIndexBuild and all nodes mark the index ready: 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

Four-gate rollout prevents mid-build abort or replication collapse

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):

  1. Phase 1 — Expand Oplog Online: Run db.adminCommand({ replSetResizeOplog: 1, size: 409600 }) (size in MB, here 400 GB) across nodes to guarantee >= 2.5x build duration headroom.
  2. Phase 2 — Raise Sort Memory Buffer: Increase maxIndexBuildMemoryUsageMegabytes (for example to 4096 MB on a 128 GB RAM host) so the sorter writes fewer, larger run files to _tmp/:
    db.adminCommand({ setParameter: 1, maxIndexBuildMemoryUsageMegabytes: 4096 });
    
  3. Phase 3 — Launch Serialized Build in tmux: Run one createIndexes command at a time with commitQuorum: "majority" (passed as the 3rd argument in createIndex(), or top-level in runCommand):
    db.orders.createIndex(
      { "account_id": 1, "created_at": -1, "status": 1 },
      { name: "idx_account_created_status" },
      "majority"
    );
    
  4. 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 via db.orders.dropIndex("idx_account_created_status") or adjust quorum with db.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. _tmp I/O Amplification: Per MongoDB’s maxIndexBuildMemoryUsageMegabytes documentation, the default 200 MB limit applies per createIndexes command 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 to dbPath/_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 before voteCommitIndexBuild is written. Because commitQuorum defaults to "votingMembers", a single unreachable or hardware-failed voting secondary prevents the primary from writing commitIndexBuild—keeping all nodes holding the index build state until the node recovers or an operator runs setIndexCommitQuorum to 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, and commitIndexBuild coordination entries to local.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 _tmp merge sort, its oplog applier falls behind the primary’s write rate, consuming the oplog retention window. If a lagging secondary drops into RECOVERING, 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 maxIndexBuildMemoryUsageMegabytes default and ignores legacy background: true as a safe no-op. However, MongoDB 8.0 improves secondary oplog throughput via parallel oplog writer/applier paths and enforces indexBuildMinAvailableDiskSpaceMB to halt an index build cleanly before _tmp spills exhaust the filesystem.

Where It Breaks

Four billion-row build failures and their recovery paths

Operational HazardPhysical Failure MechanismArchitectural ConsequenceSafe Mitigation Protocol
Unclean Crash During BuildOOM 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 SecondariesSecondary 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 DiskExternal 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 tmuxLaptop 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 IngestConcurrent 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 PressureHeavy 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 HangOne 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 VolumeRunning 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 resize local.oplog.rs online to >= 2.5x estimated build time.
  • Raise maxIndexBuildMemoryUsageMegabytes from its 200 MB default: Allocating 2–4 GB on memory-optimized EC2 nodes slashes _tmp disk run files and EBS merge-sort IOPS.
  • Override the "votingMembers" commitQuorum default: Pass "majority" (as the 3rd argument to createIndex()) so a single offline secondary cannot stall commit indefinitely.
  • Clean SIGTERM resumes; SIGKILL or 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 via dropIndex() if secondary lag threatens the oplog window.

What to Do Next

  • Problem: Large-collection index builds risk _tmp disk exhaustion, EBS I/O saturation, and secondary oplog rollover.
  • Solution: Standardize on a pre-flight gate that verifies >= 2x S_temp free disk, resizes the oplog to >= 2.5x build duration, bumps maxIndexBuildMemoryUsageMegabytes, and sets commitQuorum: "majority".
  • Proof: Check current oplog retention hours via local.oplog.rs and confirm maxIndexBuildMemoryUsageMegabytes via getParameter.
  • Action: Run the pre-flight verification script against your largest collection this week before scheduling its next compound index build.