Jumbo Chunks, Stuck Migrations, and MongoDB Balancer Incidents
When a shard key lacks sufficient cardinality or write velocity outpaces splitting on MongoDB 4.4 and 5.0, chunks cross the maximum range threshold into an un-splittable jumbo state that freezes the balancer and pins load onto a single shard.
TL;DR
- Problem: Once
config.chunksmarks a rangejumbo: true, the balancer skips it permanently, leaving one shard saturated on CPU, IOPS, and WiredTiger cache while peer shards sit underutilized.- Answer: Stop the balancer, separate divisible chunks (fix with
splitFind+clearJumboFlag) from cardinality-exhausted chunks (fix withrefineCollectionShardKeyorreshardCollection), then resume balancing inside an off-peakactiveWindow.- Watch out: Calling
clearJumboFlagwithout shrinking or splitting an oversized chunk triggers an endless loop of failedmoveChunktransfers, cross-AZ bandwidth saturation, andchunk too big to moveaborts.
Situation
Sharded MongoDB clusters distribute collection data across shards as contiguous key ranges called chunks. On MongoDB 4.4 and 5.0, the default maximum chunk size is 64 MB, and the auto-splitter on the primary shard evaluates whether a chunk needs splitting after writes accumulate. Starting in MongoDB 6.0, the default range size doubled to 128 MB, and in MongoDB 6.0.3+ automatic chunk splitting was removed altogether in favor of data-size balancing across shards.
Despite that architectural shift in 6.0.3+, production estates running 4.4 or 5.0—or clusters upgraded from earlier versions with legacy low-cardinality shard keys—still hit jumbo chunk deadlocks. On cloud infrastructure such as AWS EC2 with EBS gp3 volumes, a single un-migratable range concentrates all writes and working-set reads for a large tenant onto one replica set. Because the cluster balancer runs on the primary member of the config server replica set (CSRS, moved there in MongoDB 3.4) and explicitly refuses to schedule moveChunk on any chunk flagged jumbo: true, adding more shards does nothing to relieve the hot shard.
The Problem
Jumbo chunks arise from two distinct mechanisms—auto-split lag and shard key cardinality exhaustion—and treating them identically makes incidents worse.
- Chunk size and document-count ceilings: On MongoDB 4.4 and 5.0, a chunk becomes ineligible for automatic migration when its size exceeds the configured
chunkSize(default 64 MB; 128 MB in 6.0+) or when it exceeds the legacy document-count ceiling of 250,000 documents for a 64 MB chunk. Small-document workloads (such as 200-byte telemetry events) hit the document-count cap at roughly250,000 * 200 B = 50 MB, before reaching the byte ceiling. - Cardinality exhaustion: When a collection is sharded on a low-cardinality prefix such as
{ tenant_id: 1 }, every document for a single tenant shares the exact same shard key value. Because MongoDB cannot split documents with identical shard key values across two chunks,splitVectorreturns zero split points. If a single tenant exceeds 64 MB (or 128 MB on 6.0+), the chunk becomes mathematically indivisible. - Auto-split starvation under burst ingest (4.4 / 5.0): Even when a compound key has sufficient cardinality, high-velocity bulk loads can grow a chunk past the migration threshold before the primary executes
splitVector. OncemoveChunkattempts to migrate the oversized range and fails, MongoDB flags the chunkjumbo: trueinconfig.chunks. - Metadata schema divergence across versions: Prior to MongoDB 5.0,
config.chunkskeyed documents by the namespace stringns. Starting in MongoDB 5.0,config.chunksreplacednswith the collectionuuidfromconfig.collections. Runbook queries written againstconfig.chunks.find({ ns: ... })silently return zero rows on 5.0+ clusters, masking active jumbo chunks during an incident.
The operational question is: How do platform engineers distinguish transient split lag from shard-key cardinality exhaustion, resolve jumbo: true chunks without triggering migration thrashing, and restore balanced shard utilization online?
Options Considered
When a chunk is flagged jumbo: true, four intervention paths exist. Choosing the wrong one either fails immediately or saturates cross-AZ bandwidth and WiredTiger cache.
| Option | When It Works | Where It Breaks | Decision |
|---|---|---|---|
clearJumboFlag alone | Deletes already shrank chunk below chunkSize | Oversized chunk triggers moveChunk, saturates I/O, aborts, re-flags jumbo | Reject unless size verified |
splitFind + clearJumboFlag | Divisible chunk (4.4/5.0 split lag or post-refine) | Fails when all documents share one shard key value | Default for divisible chunks |
refineCollectionShardKey (4.4+) | Existing prefix is sound; needs high-cardinality suffix | Requires pre-built supporting index; cannot remove a bad prefix | Default for low cardinality |
reshardCollection (5.0+) | Existing shard key prefix itself is broken | Needs ~2x free disk space, heavy oplog/I/O, brief write block at commit | Last resort for bad prefixes |
Running moveChunk with forceJumbo: true is a fifth tactical escape hatch when a single oversized chunk must move off a full disk, but it does not fix the underlying divisibility problem and carries high catch-up abort risk under active writes. Similarly, running clearJumboFlag without first verifying that the chunk is divisible or has shrunk below the configured range size is an anti-pattern: the CSRS balancer immediately picks up the chunk on the next round, streams gigabytes across AZs, fails to converge, and resets the flag.
The Chunk Lifecycle and Remediation Architecture
Diagnosing and fixing jumbo chunks requires understanding how the CSRS balancer, splitVector, and moveChunk interact across the control plane and data plane.
1. Control Plane: CSRS Balancer and Metadata Catalog
Since MongoDB 3.4, the balancer runs as a background thread on the primary member of the config server replica set (CSRS), eliminating the distributed lock contention that existed when mongos routers competed for the balancer lock. The CSRS primary reads balancing configuration from config.settings (including activeWindow and per-collection settings) and chunk metadata from config.chunks. Any chunk with jumbo: true is excluded from balancing rounds.
2. How splitVector Finds Split Points
When a shard primary splits a chunk (either via the legacy auto-splitter in 4.4/5.0 or manual splitFind / splitAt commands), it runs the internal splitVector command:
- Index scan:
splitVectortraverses the shard-key index between the chunk’sminandmaxbounds. - Median estimation: Using the collection’s average object size (
avgObjSize), it accumulates estimated bytes until it reaches half the targetchunkSize(for example, 32 MB on a 64 MB configuration) and records candidate split keys. - Cardinality failure: If every document in the range maps to the same shard key value, the index scan finds no intermediate key boundary.
splitVectorreturns an empty split list, leaving the chunk indivisible.
3. Data Plane: moveChunk Cloning, Catch-Up, and Critical Section
When the balancer schedules a migration from a donor shard to a recipient shard:
- Cloning: The recipient shard reads documents within the chunk bounds from the donor and inserts them into its local WiredTiger storage.
- Catch-up: Concurrently, the donor buffers incoming writes targeting that range; the recipient pulls and applies those buffered changes.
- Critical section: Once catch-up lag drops to a minimal threshold, the donor enters a brief critical section that blocks writes to the migrating range, transfers the final delta, updates
config.chunkson the CSRS, and releases the lock. - Range deletion: After
orphanCleanupDelaySecs(historically 900 seconds; raised to 3,600 seconds in MongoDB 8.2 to protect long-running secondary reads), the donor’s range deleter asynchronously deletes the migrated documents.
4. Version-Safe Diagnostic Script (mongosh)
Because config.chunks uses uuid in MongoDB 5.0+ and ns in MongoDB 4.4, diagnostic scripts must resolve the collection UUID from config.collections first and fall back to ns only on older versions:
// Run via mongosh connected to mongos
(function() {
const cfg = db.getSiblingDB("config");
const jumboChunks = cfg.chunks.find({ jumbo: true }).toArray();
print("Total jumbo chunks: " + jumboChunks.length);
const uuidToNs = {};
cfg.collections.find({}, { _id: 1, uuid: 1 }).forEach(c => {
if (c.uuid) uuidToNs[c.uuid.toString()] = c._id;
});
jumboChunks.forEach(c => {
const ns = c.ns || (c.uuid ? uuidToNs[c.uuid.toString()] : "unknown");
print(`NS: ${ns} | Shard: ${c.shard} | Min: ${JSON.stringify(c.min)}`);
});
cfg.changelog.find({ what: "moveChunk.from", "details.errmsg": { $exists: true } })
.sort({ time: -1 }).limit(5).forEach(e => {
print(`${e.time.toISOString()} | ${e.ns} | ${e.details.errmsg}`);
});
})();
5. Automated Triage and Split Script (pymongo)
For collections with many jumbo chunks, automate splitFind and clearJumboFlag (using bounds: [min_bound, max_bound], which works for both ranged and hashed shard keys) with a mandatory --dry-run mode:
#!/usr/bin/env python3
import argparse
from pymongo import MongoClient
from pymongo.errors import PyMongoError
def resolve_jumbo_chunks(client, namespace, dry_run):
cfg, admin = client.config, client.admin
db_name, coll_name = namespace.split(".", 1)
coll_meta = cfg.collections.find_one({"_id": namespace})
query = {"jumbo": True}
query["uuid" if coll_meta and "uuid" in coll_meta else "ns"] = (
coll_meta["uuid"] if coll_meta and "uuid" in coll_meta else namespace
)
for chunk in cfg.chunks.find(query):
min_b, max_b = chunk["min"], chunk["max"]
doc_q = {
k: {**({"$gte": min_b[k]} if str(type(min_b[k]).__name__) != "MinKey" else {}),
**({"$lt": max_b[k]} if str(type(max_b[k]).__name__) != "MaxKey" else {})}
for k in min_b
}
doc_q = {k: v for k, v in doc_q.items() if v}
sample = client[db_name][coll_name].find_one(doc_q)
if not sample:
continue
coords = {k: sample[k] for k in min_b if k in sample}
if dry_run:
print(f"[DRY-RUN] split + clearJumboFlag at {coords}")
continue
try:
admin.command("split", namespace, find=coords)
admin.command("clearJumboFlag", namespace, bounds=[min_b, max_b])
except PyMongoError as exc:
print(f"[ERROR] {chunk['shard']}: {exc}")
if __name__ == "__main__":
p = argparse.ArgumentParser()
p.add_argument("--mongos-uri", required=True)
p.add_argument("--ns", required=True)
p.add_argument("--dry-run", action="store_true")
args = p.parse_args()
resolve_jumbo_chunks(MongoClient(args.mongos_uri, serverSelectionTimeoutMS=5000), args.ns, args.dry_run)
How It Rolls Out
Execute jumbo chunk remediation in four gated phases so metadata changes and data movement never collide with peak application traffic.
Phase 1: Isolate the Balancer
Stop the CSRS balancer to halt any in-flight or retrying moveChunk operations that compete for IOPS and cross-AZ network bandwidth:
sh.setBalancerState(false);
- Validation gate: Run
sh.isBalancerRunning()(ordb.adminCommand({ balancerStatus: 1 })) and wait untilinBalancerRoundisfalsebefore touching chunk metadata. - Rollback: Re-enable
sh.setBalancerState(true)if no further action is taken.
Phase 2: Refine Shard Key Cardinality (Only If Indivisible)
If config.chunks shows jumbo chunks where min and max share the exact same key value, splitFind cannot divide them. On MongoDB 4.4+, append a high-cardinality suffix (such as _id) using refineCollectionShardKey after building the supporting compound index across all shards:
db.events.createIndex({ tenant_id: 1, _id: 1 }, { commitQuorum: "majority" });
db.adminCommand({ refineCollectionShardKey: "telemetry.events", key: { tenant_id: 1, _id: 1 } });
- Validation gate: Confirm
sh.status()displays the new compound shard key on the collection before splitting. - Rollback: Index creation is online;
refineCollectionShardKeyis a one-way metadata change and cannot be reverted withoutreshardCollection, so verify query patterns before running.
Phase 3: Split Chunks and Clear the Jumbo Flag
With sufficient cardinality in place, run sh.splitFind() (or db.adminCommand({ split: ns, find: ... })) on each jumbo chunk, then clear the flag via db.adminCommand({ clearJumboFlag: ns, bounds: [chunk.min, chunk.max] }). Note that clearJumboFlag with find is disallowed on hashed shard keys; using bounds works across both ranged and hashed collections.
- Validation gate: Query
config.chunksforjumbo: trueand verify the count is0. - Rollback: Chunk splits are metadata-only operations on the shard primary and CSRS; if a split lands poorly, the balancer can merge adjacent small chunks later (or via
configureCollectionBalancingwithdefragmentCollection: trueon 6.0+).
Phase 4: Re-Enable the Balancer Inside an Active Window
Re-enable the balancer and bound migrations to an off-peak maintenance window in config.settings so moveChunk cloning and donor range deletion do not contend with daytime transactional latency:
db.getSiblingDB("config").settings.updateOne(
{ _id: "balancer" },
{ $set: { activeWindow: { start: "02:00", stop: "06:00" } } },
{ upsert: true }
);
sh.setBalancerState(true);
- Validation gate: Monitor
sh.status()and$shardedDataDistribution(6.0+) over subsequent windows to confirm data size converges across shards without migration aborts. - Rollback: If daytime or window IOPS saturate, immediately run
sh.setBalancerState(false)or throttle range deletion withrangeDeleterBatchSizeandrangeDeleterBatchDelayMS.
In Practice
The operational behaviors above are derived from documented MongoDB sharding and WiredTiger internals rather than synthetic benchmarks:
- WiredTiger cache pressure during concurrent migrations: MongoDB’s WiredTiger storage engine targets keeping dirty cache bytes below 5% and triggers application-thread eviction stalls when dirty bytes cross 20% (or total cache usage hits the 95% eviction trigger against the 80% target). During a
moveChunktransfer, the donor shard reads cold chunk pages into cache while applying live writes, and the recipient inserts cloned documents into its own cache. Running unbounded migrations during peak write traffic pushes both shards closer to the 20% dirty-byte stall threshold, elevating application p99 latency. - Range deletion and secondary read safety: After a migration commits, the donor shard retains the migrated range for
orphanCleanupDelaySecs(900 seconds by default in earlier releases, increased to 3,600 seconds in MongoDB 8.2) before the range deleter purges orphaned documents. If the donor deletes millions of orphaned documents from a formerly jumbo chunk in unthrottled batches, B-tree page modifications spike dirty cache and replication lag on secondaries. TuningrangeDeleterBatchSizeandrangeDeleterBatchDelayMSspreads that I/O across the maintenance window. - Why
activeWindowprevents cascading aborts: On write-heavy collections,moveChunkmust drain buffered writes during the catch-up phase before entering the critical section. Scheduling migrations during off-peak hours lowers the incoming write rate on the donor, allowing catch-up to converge without repeated aborts.
Where It Breaks
| Condition | Breaks How | Detect | Mitigate |
|---|---|---|---|
Blind clearJumboFlag on oversized chunk | Balancer triggers moveChunk, saturates cross-AZ I/O, aborts (chunk too big to move), re-flags jumbo | config.changelog moveChunk.from errors; rising network TX/RX | Split chunk first (splitFind) or verify deletes shrank it below chunkSize |
refineCollectionShardKey without index | Command fails immediately; shard key remains un-splittable | Command error IndexNotFound on mongos | Build compound index with commitQuorum: "majority" first |
| 24/7 balancing under peak writes | moveChunk cloning and catch-up compete with live writes for WiredTiger dirty cache and EBS IOPS | WiredTiger dirty % approaching 20%; rising p99 write latency | Set activeWindow in config.settings to off-peak hours |
| Catch-up non-convergence | Donor write rate exceeds recipient oplog apply speed; migration aborts repeatedly | config.changelog shows repeated moveChunk.from aborts | Throttle bulk ingest or move balancer window to low-write hours |
Lowering chunkSize globally on live cluster | Smaller chunkSize multiplies chunk count and config metadata overhead, triggering migration storms | Surge in config.chunks count and CSRS memory usage | Keep default chunkSize (64 MB on 4.4/5.0, 128 MB on 6.0+) |
| Unthrottled range deletion on large chunks | Donor purges orphaned docs rapidly, causing dirty-cache stalls and secondary replication lag | Replication lag spike after moveChunk commit | Set rangeDeleterBatchSize and rangeDeleterBatchDelayMS |
5.0+ script querying config.chunks by ns | Returns 0 jumbo chunks because 5.0+ keys config.chunks by uuid | sh.status() shows jumbo chunks while script reports 0 | Join config.collections _id to uuid before querying config.chunks |
April 2026 Update
MongoDB 6.0, 7.0, and 8.0 changed how sharded clusters split, merge, and reshard data, making legacy 4.4/5.0 runbooks partially obsolete:
- 128 MB default range size and removal of auto-splitting (MongoDB 6.0.3+): The default range size is 128 MB, and starting in MongoDB 6.0.3 automatic chunk splitting is no longer performed (
sh.enableAutoSplit()andsh.disableAutoSplit()exist only as no-ops for backward compatibility). The CSRS balancer distributes data by shard data size rather than chunk count, so ranges can exceed 128 MB without penalty as long as shards remain balanced. - Collection defragmentation and automatic merging (MongoDB 6.0–8.0): Operators can enable per-collection defragmentation with
configureCollectionBalancing(defragmentCollection: true) and monitor progress viabalancerCollectionStatus. In MongoDB 7.0 and 8.0, automatic chunk merging keeps metadata fragmentation low without manual intervention. - Same-key resharding and early commit (MongoDB 8.0):
reshardCollectionin MongoDB 8.0 supports resharding to the same shard key (forceRedistribution) to redistribute skewed data quickly across newly added shards, andcommitReshardCollectionallows operators to force an in-progress resharding operation to enter its write-blocking commit phase immediately.
Key Takeaways
- Separate split lag from cardinality exhaustion before acting: Use
splitFindwhen distinct shard key values exist inside a jumbo chunk; userefineCollectionShardKey(4.4+) orreshardCollection(5.0+) when every document shares the same key. - Never run
clearJumboFlagblindly: Clearing the flag on an oversized chunk forces the CSRS balancer into an abort loop that wastes cross-AZ bandwidth and IOPS. - Query
config.chunksbyuuidon MongoDB 5.0+: Resolve the collection UUID fromconfig.collectionsfirst, becausenswas removed fromconfig.chunksin MongoDB 5.0. - Bound balancing and range deletion to protect p99 latency: Configure
activeWindowinconfig.settingsand tunerangeDeleterBatchSize/rangeDeleterBatchDelayMSso background data movement never pushes WiredTiger toward its 20% dirty-cache stall threshold. - Account for MongoDB 6.0.3+ behavior: Modern clusters default to 128 MB ranges, disable auto-splitting, and balance by shard data size rather than chunk count.
What to Do Next
- Problem: Identify whether your sharded MongoDB cluster has
jumbo: truechunks stalling the CSRS balancer and pinning writes onto a single shard. - Solution: Halt the balancer, inspect
config.chunksviaconfig.collectionsUUID lookup, refine low-cardinality shard keys where needed, split divisible chunks withsh.splitFind(), and clear flags withclearJumboFlagusingbounds. - Proof: Confirm
config.chunks.countDocuments({ jumbo: true })returns0and verify balanced data distribution viash.status()or$shardedDataDistribution. - Action: Add an alert on
config.chunks(jumbo: true) andconfig.changelog(moveChunk.fromerrors), and configure an off-peakactiveWindowinconfig.settingsthis week.
Interactive tools for this topic