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-peak activeWindow in config.settings, and throttle background range deletion (rangeDeleterBatchSize / rangeDeleterBatchDelayMS) if disk await climbs.
  • Watch out: Never stop the balancer during removeShard draining, never terminate EC2 instances before removeShard returns state: "completed", and always run movePrimary for any dbsToMove.

Gate sh.addShard behind an off-peak activeWindow

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:

  1. 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 moveChunk operations. 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.
  2. 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.
  3. 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 iostat await latency sharply upward.
  4. Application Timeouts and Cascading Retries: As disk queues back up, client queries exceed socket timeouts, triggering CursorNotFound errors and application retry storms that further compound load on the very shards being scaled.

Balancer concurrency, 128 MB chunks, and EBS bandwidth bound scaling speed

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:

OptionPeak-Hour I/O ImpactRebalance PredictabilityOperational ConstraintDecision
24/7 Unthrottled BalancerHigh (cold scans during peak)Fastest raw completionEvicts hot WiredTiger cache during business hoursRejected for latency-sensitive production
Vertical EC2 Resize FirstNone (rolling secondary reboot)Zero chunk movementHits single-node instance/EBS ceilingsConditional; use as a short-term bridge only
activeWindow + Range ThrottleZero during daytime trafficMulti-night predictableRequires config.settings window and I/O tuningChosen 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 as 02:00 to 06:00 UTC) and tunes rangeDeleterBatchSize / rangeDeleterBatchDelayMS so 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.

Use activeWindow scheduling and range-deleter throttling over 24/7 balancing

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.

Balancer schedules chunk moves while asynchronous range deleter cleans orphans

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

  1. 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.
  2. 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.
  3. 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.
  4. 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 mongos routes traffic to the recipient, the donor purges the migrated documents asynchronously via its background range deleter (or via cleanupOrphaned for manual orphan sweeps). Because rangeDeleterBatchSize defaults to INT_MAX (2147483647) in modern MongoDB, unthrottled range deletion can generate heavy disk I/O and secondary replication lag unless bounded with rangeDeleterBatchSize and rangeDeleterBatchDelayMS.

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.

Four-step shard addition and safe decommissioning rollout

Adding Shards Safely

  1. 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 via sh.isBalancerRunning() or db.adminCommand({ balancerStatus: 1 }):
    sh.setBalancerState(false);
    
  2. Step 2 — Configure the Off-Peak activeWindow: Persist the allowed balancing window in config.settings (UTC). Because config.settings is 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 }
    );
    
  3. 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:
    sh.addShard("shard11/ip-10-0-1-10:27017,ip-10-0-2-10:27017,ip-10-0-3-10:27017");
    sh.setBalancerState(true);
    
    Rollback Gate: If donor iostat await or p99 latency spikes during the window, run sh.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, run db.adminCommand({ cleanupOrphaned: "telemetry.events" }) directly on that shard’s primary during a quiet window.
  4. Step 4 — Verify Convergence: Poll balancerCollectionStatus until balancerCompliant: true across all sharded collections.

Decommissioning Shards Safely via removeShard

  1. Start Draining: Run db.adminCommand({ removeShard: "shard08" }) with the balancer enabled.
  2. Keep Balancer Running: Never disable the balancer while a shard is in ongoing / draining state, or chunk evacuation stalls indefinitely.
  3. Relocate Primary Databases (dbsToMove): Any unsharded collections on a database whose primary shard is shard08 will appear in dbsToMove. Move each one explicitly: db.adminCommand({ movePrimary: "reporting", to: "shard01" }).
  4. Terminate Only After state: "completed": Re-run removeShard until 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 new moveChunk scans immediately, allowing active client queries to re-warm the working set in cache without background sequential scan interference.
  • Why removeShard Stalls on dbsToMove: Sharded chunk evacuation is handled automatically by the balancer, but unsharded collections belong to each database’s designated primary shard. Until movePrimary reassigns those databases, removeShard remains in state: "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

Three failure modes during cluster scaling and shard removal

ConditionBreaks HowDetectMitigate
Adding Shards During Peak HoursImmediate chunk scans evict hot cache and saturate EBS gp3 IOPSiostat await > 15 ms and p99 read latency spikesRun sh.setBalancerState(false) first; enforce activeWindow
Stopping Balancer During removeShardDraining shard cannot evacuate remaining chunksremoveShard stays in state: "ongoing" indefinitelyKeep balancer enabled during drain; widen activeWindow
Terminating EC2 Before completedRemaining chunks on the host are permanently lostMissing shard data and broken catalog routingWait strictly for removeShard to return state: "completed"
Skipped movePrimary on dbsToMoveUnsharded collections remain stranded on draining shardremoveShard output lists dbsToMoveRun db.adminCommand({ movePrimary: db, to: target })
Unthrottled Range DeleterDefault INT_MAX rangeDeleterBatchSize spikes dirty cache and lagSecondary replication lag climbs after chunk commitsSet rangeDeleterBatchSize (e.g., 128) and rangeDeleterBatchDelayMS
Jumbo Chunks Blocking BalanceOversized indivisible chunks cannot migrate to new shardsbalancerCollectionStatus shows imbalance with no movesSplit 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:

  1. 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.
  2. Automated Chunk Merging via AutoMerger (MongoDB 7.0 / 8.0): Replaces manual 6.0 defragmentCollection runs with the background AutoMerger (sh.enableAutoMerger, autoMergerIntervalSecs, autoMergerThrottlingMS), automatically merging adjacent under-utilized chunks on the same shard.
  3. Flow Control Integration: Recipient shards with active Flow Control (flowControlTargetLagSeconds default 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)) before sh.addShard() and gate migrations behind an off-peak activeWindow.
  • 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 balancerCollectionStatus with its real 6.0+ fields: Check balancerCompliant, chunkSize, and firstComplianceViolation rather than non-existent chunksToMove counters.
  • Throttle the range deleter if secondary lag spikes after migrations: Tune rangeDeleterBatchSize and rangeDeleterBatchDelayMS so post-move orphan cleanup does not overwhelm WiredTiger dirty cache.
  • Never terminate a draining shard early: Keep the balancer running, move every database in dbsToMove via movePrimary, and wait for removeShard to return state: "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-peak activeWindow in config.settings, and tuning range-deleter batching.
  • Proof: Monitor balancerCollectionStatus for balancerCompliant: true and verify with iostat -xz that donor read await stays below 15 ms during balancing windows.
  • Action: Audit your production sharded clusters for an active activeWindow, test mongo_cluster_scaler.py --dry-run against staging, and verify homogeneous EC2/EBS sizing across all shards.