Scaling a MongoDB Sharded Cluster on EC2 Without Letting the Balancer Crush Production
Adding a new shard to an overloaded MongoDB cluster feels like opening a pressure relief valve; in reality, unthrottled chunk migrations push source shard disk IOPS and WiredTiger cache eviction into immediate production collapse.
TL;DR
- Problem: Executing
sh.addShard()on a busy cluster triggers immediate background migrations of 128 MB chunks (6.0+ default), evicting hot working sets from donor WiredTiger caches and saturating EBS gp3 read bandwidth.- Answer: Pause the balancer (
sh.setBalancerState(false)) before adding shards, enforce an off-peakactiveWindowinconfig.settings, and throttle background range deletion (rangeDeleterBatchSize/rangeDeleterBatchDelayMS) if diskawaitclimbs.- Watch out: Never stop the balancer during
removeSharddraining, never terminate EC2 instances beforeremoveShardreturnsstate: "completed", and always runmovePrimaryfor anydbsToMove.
Situation
Operating horizontally scaled MongoDB clusters on AWS EC2 allows platform teams to scale storage and write throughput beyond the physical limits of a single replica set. In multi-tenant SaaS and telemetry deployments running on memory-optimized instances backed by EBS gp3 volumes, sustained dataset growth gradually pushes existing shards toward CPU saturation, rising WiredTiger cache eviction pressure, and elevated disk write queues.
To relieve pressure on the existing fleet, engineers provision new replica sets and execute sh.addShard() to expand the cluster, expecting immediate linear relief. In distributed storage systems, however, registering an empty shard does not reduce load right away. Instead, it creates a sharp topological imbalance that triggers aggressive background data movement across the existing overloaded shards.
The Problem
Executing sh.addShard() during peak application traffic introduces four compounding operational constraints:
- Immediate Imbalance Detection and $\lfloor n/2 \rfloor$ Concurrency: A newly registered shard holds zero chunks. The balancer—running on the Config Server replica set primary—detects the imbalance immediately and schedules concurrent
moveChunkoperations. Because each shard can participate in at most one migration at a time (inbound or outbound), an $n$-shard cluster can run up to $\lfloor n/2 \rfloor$ simultaneous chunk transfers across donor and recipient pairs. - Cold 128 MB Chunk Scans and Cache Eviction: Starting in MongoDB 6.0, the default chunk size doubled from 64 MB to 128 MB to reduce metadata overhead. To migrate each 128 MB chunk, the donor shard primary reads all documents in that key range from disk. When migrating older, colder chunks, WiredTiger’s LRU eviction algorithm treats those newly read pages as active, flushing hot transactional working-set pages out of RAM.
- EBS gp3 Bandwidth Contention: Streaming gigabytes of cold chunks from donor primaries consumes sequential read bandwidth against EBS gp3 limits (125 MB/s baseline unless provisioned higher). Application queries that previously hit in-memory cache now incur synchronous disk reads, driving Linux
iostatawaitlatency sharply upward. - Application Timeouts and Cascading Retries: As disk queues back up, client queries exceed socket timeouts, triggering
CursorNotFounderrors and application retry storms that further compound load on the very shards being scaled.
The core architectural question is: How can platform architects expand or contract a production sharded cluster on AWS EC2, govern balancer migration windows and range-deletion I/O, and prevent chunk movement from cannibalizing live application cache and EBS bandwidth?
Options Considered
When an existing sharded cluster approaches storage or CPU saturation, teams typically evaluate three scaling and balancing strategies:
| Option | Peak-Hour I/O Impact | Rebalance Predictability | Operational Constraint | Decision |
|---|---|---|---|---|
| 24/7 Unthrottled Balancer | High (cold scans during peak) | Fastest raw completion | Evicts hot WiredTiger cache during business hours | Rejected for latency-sensitive production |
| Vertical EC2 Resize First | None (rolling secondary reboot) | Zero chunk movement | Hits single-node instance/EBS ceilings | Conditional; use as a short-term bridge only |
activeWindow + Range Throttle | Zero during daytime traffic | Multi-night predictable | Requires config.settings window and I/O tuning | Chosen standard for EC2 shard scaling |
- 24/7 Unthrottled Balancing: Maximizes migration speed by running $\lfloor n/2 \rfloor$ transfers continuously, but puts donor WiredTiger caches and EBS read queues in direct competition with peak user traffic.
- Vertical EC2 Resize First: Upgrading existing shard instances (for example, to larger memory-optimized EC2 types or higher provisioned gp3 IOPS) via rolling secondary restarts avoids chunk movement altogether, buying headroom when a cluster is already too saturated to survive even off-peak migrations.
- Off-Peak
activeWindow+ Range-Deleter Throttling: Restricts chunk migrations to verified low-traffic hours (such as02:00to06:00UTC) and tunesrangeDeleterBatchSize/rangeDeleterBatchDelayMSso post-migration cleanup does not spike replication lag or dirty cache pages. Combined with Zone Sharding (sh.updateZoneKeyRange), this also keeps regional chunks pinned to shards in the same AWS Availability Zone to avoid unnecessary cross-AZ transfer charges.
The Shard Scaling Architecture: The Balancer Lifecycle and Active Windows
Understanding the four physical stages of a moveChunk operation explains why unbounded balancing degrades concurrent application throughput.
flowchart TD
Admin["Platform Operator — sh.addShard()"] --> ConfigServer["Config Server Balancer"]
ConfigServer --> Window{"Within activeWindow?"}
Window -->|No| Pause["Suppress Migrations — Zero Day Impact"]
Window -->|Yes| Donor["Donor Shard — Scan 128 MB Chunk"]
Donor -->|Stream Docs & Oplog| Recipient["Recipient Shard — Ingest & Index"]
Recipient --> Commit["Update Config Catalog"]
Commit --> RangeDel["Donor Async Range Deleter"]
Mechanics of the Four Chunk Migration Phases
- Donor Scan and Network Streaming: The donor shard queries the chunk range
[min, max], reads matching BSON documents from WiredTiger/EBS, and streams them across the VPC to the recipient shard. Cold chunks pulled from disk displace warm transactional pages in the donor’s cache. - Recipient Ingestion and Index Build: The recipient shard inserts incoming documents into its local WiredTiger table and updates all secondary indexes concurrently, generating dirty cache bytes and consuming write tickets.
- Migration Oplog Catch-Up: While cloning runs, client writes to that chunk continue on the donor shard. The recipient tails and applies those mutations from the donor’s oplog until lag falls below a tight threshold.
- Critical Section, Commit, and Async Range Deletion: The donor acquires a brief exclusive lock on the chunk range, transfers the final oplog delta, and commits the updated chunk ownership to the Config Server catalog. Once
mongosroutes traffic to the recipient, the donor purges the migrated documents asynchronously via its background range deleter (or viacleanupOrphanedfor manual orphan sweeps). BecauserangeDeleterBatchSizedefaults toINT_MAX(2147483647) in modern MongoDB, unthrottled range deletion can generate heavy disk I/O and secondary replication lag unless bounded withrangeDeleterBatchSizeandrangeDeleterBatchDelayMS.
Capacity and Cross-AZ Transfer Math
When adding $M$ new shards to a cluster of $N$ existing shards holding $D_{\text{total}}$ gigabytes of data, the balancer migrates roughly:
$$\text{Data to Migrate} = D_{\text{total}} \times \left( \frac{M}{N + M} \right)$$
For a 10-shard cluster holding 20 TB ($20,000\text{ GB}$) expanded by 2 new shards:
$$\text{Data to Migrate} = 20,000\text{ GB} \times \left( \frac{2}{12} \right) \approx 3,333\text{ GB}$$
At an aggregate off-peak transfer rate of $100\text{ MB/s}$:
$$T_{\text{rebalance}} = \frac{3,333,000\text{ MB}}{100\text{ MB/s}} = 33,330\text{ seconds} \approx 9.25\text{ hours}$$
With a 4-hour nightly activeWindow (02:00–06:00 UTC), the cluster converges across 2.3 nights without touching daytime traffic. In multi-AZ AWS deployments, also account for cross-AZ data transfer charges ($C_{\text{transfer}} = \text{Data Migrated (GB)} \times \text{Rate}_{\text{cross-AZ}}$) when sizing shards or designing Zone Sharding boundaries. Using sh.addShardToZone() and sh.updateZoneKeyRange(), operators can pin regional or tenant key ranges to shards residing in the same Availability Zone, preventing the balancer from shuffling chunks across AZ boundaries unnecessarily.
Also account for jumbo chunks: if a shard key has low cardinality and a single key value grows past the 128 MB chunk limit without a split point, MongoDB marks the chunk as jumbo and the balancer refuses to migrate it. Resolving jumbo chunks requires either appending a higher-cardinality suffix via refineCollectionShardKey or changing the key via sh.reshardCollection before new shards can absorb that data.
Diagnostic Telemetry: High-Resolution Balancer Forensics
Inspect collection balancing compliance and underlying EBS disk queues before and during every scaling window.
1. Collection Compliance via balancerCollectionStatus
Introduced in MongoDB 4.4 and enhanced in 6.0+, balancerCollectionStatus reports whether a collection is balanced (balancerCompliant) and, if not, the exact violation (firstComplianceViolation):
// Execute on mongos to inspect balancing compliance
(function() {
const adminDB = db.getSiblingDB("admin");
const colls = ["telemetry.events", "commerce.orders"];
colls.forEach(function(ns) {
try {
const res = adminDB.runCommand({ balancerCollectionStatus: ns });
print("Namespace: " + ns + " | Chunk Size: " + res.chunkSize + " MB");
print(" Balancer Compliant : " + res.balancerCompliant);
if (!res.balancerCompliant) {
print(" First Violation : " + res.firstComplianceViolation);
if (res.details) {
printjson(res.details);
}
}
} catch (e) {
print("Error checking " + ns + ": " + e);
}
});
})();
2. Monitoring Donor Disk Latency (iostat)
Track EBS read await and device utilization on donor shard primaries during active balancing windows:
# Monitor disk await latency and utilization on donor shard primaries
iostat -xz 1 10 | awk '{print $1, $8, $9, $10, $14}'
If read await climbs past 15 ms or %util approaches saturation during an active window, narrow activeWindow, stop the balancer (sh.setBalancerState(false)), or throttle rangeDeleterBatchSize and rangeDeleterBatchDelayMS.
How It Rolls Out
Execute cluster expansion and shard decommissioning as deterministic four-step runbooks with explicit gates.
Adding Shards Safely
- Step 1 — Pause the Balancer Pre-Emptively: Halt balancing before registering the new shard so
sh.addShard()does not trigger an immediate migration storm, and confirm no in-flight migrations remain active viash.isBalancerRunning()ordb.adminCommand({ balancerStatus: 1 }):sh.setBalancerState(false); - Step 2 — Configure the Off-Peak
activeWindow: Persist the allowed balancing window inconfig.settings(UTC). Becauseconfig.settingsis stored on the Config Server replica set, the window applies cluster-wide across all shards and persists across router restarts:db.getSiblingDB("config").settings.updateOne( { "_id": "balancer" }, { $set: { activeWindow: { start: "02:00", stop: "06:00" } } }, { upsert: true } ); - Step 3 — Register the New Shard and Re-Enable Balancer: Ensure the new replica set uses identical EC2 instance classes, WiredTiger cache sizing, and EBS gp3 IOPS/throughput tiers before adding it:
Rollback Gate: If donorsh.addShard("shard11/ip-10-0-1-10:27017,ip-10-0-2-10:27017,ip-10-0-3-10:27017"); sh.setBalancerState(true);iostatawaitor p99 latency spikes during the window, runsh.setBalancerState(false)immediately; in-flight migrations abort safely at the next chunk boundary or commit cleanly without data loss. If an abrupt crash leaves orphaned documents on a donor shard, rundb.adminCommand({ cleanupOrphaned: "telemetry.events" })directly on that shard’s primary during a quiet window. - Step 4 — Verify Convergence: Poll
balancerCollectionStatusuntilbalancerCompliant: trueacross all sharded collections.
Decommissioning Shards Safely via removeShard
- Start Draining: Run
db.adminCommand({ removeShard: "shard08" })with the balancer enabled. - Keep Balancer Running: Never disable the balancer while a shard is in
ongoing/ draining state, or chunk evacuation stalls indefinitely. - Relocate Primary Databases (
dbsToMove): Any unsharded collections on a database whose primary shard isshard08will appear indbsToMove. Move each one explicitly:db.adminCommand({ movePrimary: "reporting", to: "shard01" }). - Terminate Only After
state: "completed": Re-runremoveSharduntil it returns{ state: "completed" }, then decommission the EC2 instances.
Automated Cluster Scaler CLI
#!/usr/bin/env python3
"""
MongoDB Safe Cluster Expansion & Balancer Orchestrator
Usage:
python3 mongo_cluster_scaler.py --mongos-uri "mongodb://admin:pass@mongos1:27017" \
--new-shard-replica "shard11/ip-10-0-1-10:27017,ip-10-0-2-10:27017,ip-10-0-3-10:27017" \
--window-start "02:00" --window-stop "06:00" --dry-run
"""
import argparse
import sys
from pymongo import MongoClient
from pymongo.errors import PyMongoError
def orchestrate_shard_addition(client, new_shard_string, window_start, window_stop, dry_run):
admin_db = client.admin
config_db = client.config
shards = list(config_db.shards.find())
print(f"Current Cluster Shards : {len(shards)}")
balancer_status = admin_db.command("balancerStatus")
print(f"Balancer Mode : {balancer_status.get('mode', 'UNKNOWN')}")
if not dry_run:
try:
admin_db.command("balancerStop")
config_db.settings.update_one(
{"_id": "balancer"},
{"$set": {"activeWindow": {"start": window_start, "stop": window_stop}}},
upsert=True
)
res = admin_db.command("addShard", new_shard_string)
print(f"[SUCCESS] Shard registered: {res.get('shardAdded')}")
admin_db.command("balancerStart")
print(f"[SUCCESS] Balancer started with activeWindow {window_start}-{window_stop} UTC.")
except PyMongoError as e:
print(f"[FATAL] Cluster scaling failed: {e}")
sys.exit(1)
else:
print(f"[DRY RUN] Would stop balancer, set window {window_start}-{window_stop}, addShard, and start balancer.")
def main():
parser = argparse.ArgumentParser(description="MongoDB Cluster Scaler")
parser.add_argument("--mongos-uri", required=True)
parser.add_argument("--new-shard-replica", required=True)
parser.add_argument("--window-start", default="02:00")
parser.add_argument("--window-stop", default="06:00")
parser.add_argument("--dry-run", action="store_true")
args = parser.parse_args()
client = MongoClient(args.mongos_uri, serverSelectionTimeoutMS=5000)
orchestrate_shard_addition(client, args.new_shard_replica, args.window_start, args.window_stop, args.dry_run)
if __name__ == "__main__":
main()
In Practice
The operational behaviors above derive directly from MongoDB’s balancer, range deleter, and WiredTiger cache mechanics (CARL B/C — derived from documented engine behavior, not personal benchmark claims):
- Why
sh.setBalancerState(false)Restores Latency Quickly: When migrations saturate donor EBS read queues and evict hot WiredTiger pages, stopping the balancer halts newmoveChunkscans immediately, allowing active client queries to re-warm the working set in cache without background sequential scan interference. - Why
removeShardStalls ondbsToMove: Sharded chunk evacuation is handled automatically by the balancer, but unsharded collections belong to each database’s designated primary shard. UntilmovePrimaryreassigns those databases,removeShardremains instate: "ongoing"to prevent silent data loss. - Why Homogeneous Shard Hardware Matters: Because the balancer distributes data evenly across shards (by data size in 7.0+ and chunk count in earlier versions), mixing smaller-IOPS shards with larger ones forces the weakest shard to throttle overall cluster write throughput.
Where It Breaks
| Condition | Breaks How | Detect | Mitigate |
|---|---|---|---|
| Adding Shards During Peak Hours | Immediate chunk scans evict hot cache and saturate EBS gp3 IOPS | iostat await > 15 ms and p99 read latency spikes | Run sh.setBalancerState(false) first; enforce activeWindow |
Stopping Balancer During removeShard | Draining shard cannot evacuate remaining chunks | removeShard stays in state: "ongoing" indefinitely | Keep balancer enabled during drain; widen activeWindow |
Terminating EC2 Before completed | Remaining chunks on the host are permanently lost | Missing shard data and broken catalog routing | Wait strictly for removeShard to return state: "completed" |
Skipped movePrimary on dbsToMove | Unsharded collections remain stranded on draining shard | removeShard output lists dbsToMove | Run db.adminCommand({ movePrimary: db, to: target }) |
| Unthrottled Range Deleter | Default INT_MAX rangeDeleterBatchSize spikes dirty cache and lag | Secondary replication lag climbs after chunk commits | Set rangeDeleterBatchSize (e.g., 128) and rangeDeleterBatchDelayMS |
| Jumbo Chunks Blocking Balance | Oversized indivisible chunks cannot migrate to new shards | balancerCollectionStatus shows imbalance with no moves | Split via refineCollectionShardKey or sh.reshardCollection |
April 2026 Update
Modern MongoDB releases (6.0, 7.0, and 8.0) modernize chunk sizing, balancing criteria, and defragmentation:
- 128 MB Default Chunks & Data-Size Balancing (MongoDB 6.0 / 7.0+): Doubling the default chunk size to 128 MB halves migration frequency for large collections, while MongoDB 7.0+ balances based on actual data size variation rather than raw chunk counts.
- Automated Chunk Merging via AutoMerger (MongoDB 7.0 / 8.0): Replaces manual 6.0
defragmentCollectionruns with the background AutoMerger (sh.enableAutoMerger,autoMergerIntervalSecs,autoMergerThrottlingMS), automatically merging adjacent under-utilized chunks on the same shard. - Flow Control Integration: Recipient shards with active Flow Control (
flowControlTargetLagSecondsdefault 10s) pace incoming chunk writes if secondary replication lag rises during migrations.
Key Takeaways
- Adding shards adds migration I/O before it adds capacity: Always pause the balancer (
sh.setBalancerState(false)) beforesh.addShard()and gate migrations behind an off-peakactiveWindow. - Account for 128 MB chunks and $\lfloor n/2 \rfloor$ concurrency: In MongoDB 6.0+, each chunk move streams 128 MB of potentially cold data across up to $\lfloor n/2 \rfloor$ shard pairs simultaneously.
- Inspect
balancerCollectionStatuswith its real 6.0+ fields: CheckbalancerCompliant,chunkSize, andfirstComplianceViolationrather than non-existentchunksToMovecounters. - Throttle the range deleter if secondary lag spikes after migrations: Tune
rangeDeleterBatchSizeandrangeDeleterBatchDelayMSso post-move orphan cleanup does not overwhelm WiredTiger dirty cache. - Never terminate a draining shard early: Keep the balancer running, move every database in
dbsToMoveviamovePrimary, and wait forremoveShardto returnstate: "completed".
What to Do Next
- Problem: Unthrottled chunk migrations during cluster scaling evict hot WiredTiger pages and saturate EBS read IOPS, degrading live application latency.
- Solution: Standardize scaling runbooks on pausing the balancer before
sh.addShard(), enforcing an off-peakactiveWindowinconfig.settings, and tuning range-deleter batching. - Proof: Monitor
balancerCollectionStatusforbalancerCompliant: trueand verify withiostat -xzthat donor readawaitstays below 15 ms during balancing windows. - Action: Audit your production sharded clusters for an active
activeWindow, testmongo_cluster_scaler.py --dry-runagainst staging, and verify homogeneous EC2/EBS sizing across all shards.
Interactive tools for this topic