When the Shard Key Was Wrong: RefineShardKey, Live Resharding, and analyzeShardKey
A sharded database is only as scalable as its shard key; when application access patterns outgrow legacy shard key boundaries, a cluster degrades into an expensive, high-latency scatter-gather query broadcast engine.
TL;DR
- Problem: When high-frequency queries omit the shard key prefix,
mongosbroadcasts every read to all shards, saturating routerSHARD_MERGECPU and evicting WiredTiger caches across the fleet.- Answer: Validate a replacement key with
configureQueryAnalyzerandanalyzeShardKey(7.0+), userefineCollectionShardKey(4.4+) if only a suffix is needed, or runsh.reshardCollection(5.0+) to change the key online.- Watch out: Live resharding requires
((storageSize + indexSize) * 2) / shardCountfree disk space across shards, a 24–48h oplog window, andretryWrites=trueon all drivers to survive the critical section write pause.
Situation
In horizontally partitioned MongoDB clusters on AWS EC2, the shard key dictates how documents are distributed across replica sets and how mongos routers direct application requests. Each mongos instance caches the collection’s chunk-to-shard routing table from the Config Server replica set and refreshes it lazily when shards return a StaleConfig exception. Initial shard key choices—such as { customer_id: 1 }—typically reflect early single-tenant access patterns where every query filters on customer_id, allowing mongos to route reads and writes to a single shard.
As platforms mature, product requirements introduce cross-tenant reporting, global search, order-status dashboards, and time-windowed analytics. When high-frequency queries filter by status or created_at without including the shard key prefix, mongos can no longer target a single shard. Instead, the router dispatches every query to every shard simultaneously, turning a targeted distributed store into a cluster-wide broadcast engine.
The Problem
When primary query predicates diverge from the shard key, cluster capacity degrades non-linearly across four dimensions:
- Distributed Query Fan-Out: Because incoming filters omit the shard key prefix—or use range predicates against a
hashedshard key—mongoscannot prune shards from its cached chunk map. A read that should consume one execution thread on one shard instead consumes $N$ concurrent threads across the entire fleet. - Router
SHARD_MERGEBottleneck: Each shard scans its local indexes and streams matching documents back tomongos. When queries include.sort()or.skip()on non-shard-key fields,mongosmust buffer, merge-sort, and discard records across all $N$ streams in memory (SHARD_MERGEstage), drivingmongosCPU toward saturation and exhausting client connection pools. - Fleet-Wide WiredTiger Cache Eviction: Even when each shard returns only a handful of documents, scanning local B-trees pages cold data into WiredTiger caches across all shards simultaneously, evicting hot transactional working sets and spiking EBS gp3 read IOPS.
- Storage and Oplog Constraints During Correction: Prior to MongoDB 4.4, shard keys were strictly immutable, forcing multi-day offline
mongodumpandmongorestorecycles. Modern online resharding (reshardCollection) eliminates downtime, but requires at least 2x the collection’s storage and index footprint distributed across recipient shards (((storageSize + indexSize) * 2) / shardCount) plus an oplog window large enough to cover the entire clone phase.
The core architectural question is: How can platform teams validate candidate shard keys against live traffic using analyzeShardKey, choose between refineCollectionShardKey and sh.reshardCollection, and execute multi-terabyte resharding without exhausting disk space or dropping client writes?
Options Considered
MongoDB provides four mechanisms for changing or retiring a sharded collection’s partitioning scheme, each with distinct version, storage, and downtime constraints:
| Option | Version | Key Change Scope | Data Movement / Cost | Decision |
|---|---|---|---|---|
refineCollectionShardKey | 4.4+ | Append suffix fields only | Metadata-only; zero immediate data copy | Chosen when the existing prefix is still queried |
sh.reshardCollection | 5.0+ | Arbitrary new key or hash | Online clone; requires 2x footprint across shards | Chosen when queries miss the existing prefix |
sh.unshardCollection | 8.0+ | Removes shard key entirely | Moves all chunks onto one target shard | Conditional; only if data fits on a single shard |
mongodump / mongorestore | All | Arbitrary new key | Multi-day write downtime on multi-TB collections | Rejected for 24/7 production clusters |
refineCollectionShardKey(MongoDB 4.4+): Appends one or more suffix fields to the existing shard key (for example,{ customer_id: 1 }to{ customer_id: 1, created_at: 1 }). Before runningrefineCollectionShardKey, you must create the supporting compound index matching the new key on the collection. It is an instant metadata-only operation that fixes low-cardinality jumbo chunks without moving data immediately, leaving chunk splits and migrations to the balancer. However, it cannot change or remove the existing prefix field or switch between range and hashed sharding.sh.reshardCollection(MongoDB 5.0+): Creates an internal temporary collection with the new shard key, clones data online, tails donor oplogs via change streams, and swaps catalog metadata atomically. Usingdb.adminCommand({ reshardCollection: ... }), operators can also passnumInitialChunksandzonesto pre-split and place ranges across shards during the clone. In MongoDB 8.0+, passingforceRedistribution: truealso allows rebalancing data across shards or zones using the same shard key.sh.unshardCollection(MongoDB 8.0+): Consolidates a sharded collection back onto a single shard (the shard with the least data by default, or an explicittoShard), useful when a collection no longer justifies sharding overhead and its total footprint fits comfortably on one replica set.- Offline
mongodumpandmongorestore: Rejected for production systems because it requires halting application writes for hours or days while dumping, dropping, and restoring terabytes of BSON, and forces full secondary index rebuilds during restore.
The Live Resharding Architecture: The Coordinator, Cloning, and Commit Protocol
Introduced in MongoDB 5.0, Live Resharding (sh.reshardCollection) orchestrates a distributed state machine led by the ReshardingCoordinator on the Config Server replica set primary.
flowchart TD
Client["Application Clients — Continuous Traffic"] --> Router["mongos Router Fleet"]
Router -->|Writes during clone| Donor["Donor Shard — Old Key"]
Coord["ReshardingCoordinator — Config Primary"] --> Donor
Coord --> Recipient["Recipient Shard — New Key"]
Donor -.->|Snapshot Clone & Oplog Tail| Recipient
Coord -->|Critical Section & Catalog Swap| Router
Mechanics of the Resharding State Machine
- Initialization & Pre-Flight: The
ReshardingCoordinatoron the Config Server primary records state inconfig.reshardingOperations, verifies cluster health and disk/oplog prerequisites, pauses the balancer automatically, and creates temporary internal namespaces on recipient shards. - Initial Data Clone: Recipient shards open WiredTiger snapshot cursors against donor shards to copy documents belonging to their assigned new chunk ranges, inserting them in bulk and building all secondary indexes concurrently.
- Oplog Application: While cloning runs, application writes continue on donor shards. Recipient shards tail donor oplogs and apply post-snapshot mutations continuously so data converges toward real time.
- The Critical Section: Once oplog catch-up lag drops to a small threshold, the coordinator acquires an exclusive write lock across the collection, pauses new writes briefly while drivers with
retryWrites=truebuffer/retry, and drains the remaining trailing oplog entries. - Catalog Commit & Cleanup: The coordinator atomically swaps the routing metadata in the Config Server catalog so
mongosroutes to the new key layout, releases the write lock, and triggers asynchronous background deletion of the old collection files on donor shards.
Capacity, Chunk Distribution, and Oplog Engineering Formulas
Before starting sh.reshardCollection, verify both storage headroom and oplog retention mathematically:
$$\text{Storage Requirement Per Shard} = \frac{(\text{storageSize} + \text{indexSize}) \times 2}{\text{shardCount}}$$
Because old and new collections coexist until cleanup completes, every shard must hold enough free EBS space for its share of twice the collection’s data plus index footprint. Additionally, if the collection uses Zone Sharding (sh.addTagRange / sh.updateZoneKeyRange) to pin tenant or regional data to specific shards, you must supply updated zones definitions in the reshardCollection command; otherwise, existing zone boundaries are dropped when the new shard key takes effect.
Similarly, estimate minimum clone duration from network bandwidth:
$$T_{\text{clone}} = \frac{S_{\text{data}}}{\text{NetworkThroughput}_{\text{MB/s}}}$$
For a 2 TB collection transferring at 150 MB/s, $T_{\text{clone}} \approx 13,333\text{ seconds}$ (3.7 hours). Size the oplog retention window on every donor shard to at least $3 \times T_{\text{clone}}$—and standardize on 24 to 48 hours via replSetResizeOplog—so transient network slowdowns never cause a recipient shard to fall off a donor oplog mid-clone. Setting numInitialChunks (default depends on estimated collection size, minimum 1 per shard) ensures the new collection starts with evenly split ranges across recipient shards rather than dumping all initial inserts onto a single primary shard.
Diagnostic Telemetry: High-Resolution Resharding Forensics
Monitor ReshardingCoordinator and recipient progress in real time via $currentOp and config.reshardingOperations:
// Execute on mongos or Config Server primary
(function() {
const adminDB = db.getSiblingDB("admin");
const ops = adminDB.aggregate([
{ $currentOp: { allUsers: true, localOps: false } },
{ $match: {
type: "op",
$or: [
{ "desc": /Resharding/ },
{ "originatingCommand.reshardCollection": { $exists: true } }
]
} }
]).toArray();
if (ops.length === 0) {
print("[INFO] Checking config.reshardingOperations...");
const activeOp = db.getSiblingDB("config").reshardingOperations.findOne();
printjson(activeOp || { status: "No resharding operation currently active." });
return;
}
ops.forEach(function(op) {
print("Component: " + op.desc + " | Elapsed: " + (op.secs_running / 3600).toFixed(2) + "h");
if (op.bytesCopied !== undefined && op.approxBytesToCopy) {
const copiedGB = (op.bytesCopied / (1024 ** 3)).toFixed(2);
const totalGB = (op.approxBytesToCopy / (1024 ** 3)).toFixed(2);
print(" Progress: " + copiedGB + " GB / " + totalGB + " GB");
}
});
})();
How It Rolls Out
Execute live resharding as a five-step staged rollout with explicit validation gates and a pre-commit abort path:
- Step 1 — Enable Query Sampling (MongoDB 7.0+): Start
configureQueryAnalyzeron the target collection during representative traffic (maximum 50 samples/sec):db.sales.configureQueryAnalyzer({ mode: "full", samplesPerSecond: 5 }); - Step 2 — Score Candidate Key and Stop Sampling: After capturing representative read/write traffic, run
analyzeShardKeyand turn sampling off:
Gate: Confirm high cardinality, low frequency of single key values, and that top read predicates hit the new key prefix.db.sales.analyzeShardKey( { customer_id: 1, created_at: 1 }, { keyCharacteristics: true, readWriteDistribution: true, sampleRate: 0.1 } ); db.sales.configureQueryAnalyzer({ mode: "off" }); - Step 3 — Pre-Flight Disk, Oplog, and Driver Audit: Confirm
((storageSize + indexSize) * 2) / shardCountfree EBS space on every shard, expand oplogs to 48 hours viareplSetResizeOplog, freeze CI/CD DDL migrations, and verifyretryWrites=truein all client URIs. - Step 4 — Execute
sh.reshardCollection: Pass the namespace and new shard key document directly (do not nest inside{ key: ... }when using thesh.helper):
Rollback Gate: If disk headroom shrinks dangerously or latency spikes before Phase 5 catalog commit, abort safely without data loss usingsh.reshardCollection("commerce.sales", { customer_id: 1, created_at: 1 });sh.abortReshardCollection("commerce.sales"). - Step 5 — Verify Targeted Routing and Cleanup: Run
explain("executionStats")on previously slow reporting queries to confirmSHARD_MERGEis gone andwinningPlantargets a single shard (shardsarray inqueryPlannerlists only the owning shard). Confirm viash.status()that the updated shard key is active and monitor donor shard disk usage as Phase 6 asynchronously drops the temporary/old collection files. Remember that WiredTiger retains freed extent space internally rather than shrinking.wtfiles back to the OS filesystem immediately, so monitorstorageSizevs.freeStorageSizerather thandf -halone.
Automated Pre-Flight Validator
#!/usr/bin/env python3
"""
MongoDB Production Resharding Pre-Flight Validator & Orchestrator
Usage:
python3 mongo_resharding_orchestrator.py --mongos-uri "mongodb://admin:pass@mongos1:27017" \
--ns "commerce.sales" --new-key '{"customer_id": 1, "created_at": 1}' --dry-run
"""
import argparse
import json
import sys
from pymongo import MongoClient
from pymongo.errors import PyMongoError
def preflight_reshard_check(client, namespace, new_key_dict, dry_run):
config_db = client.config
admin_db = client.admin
db_name, coll_name = namespace.split(".", 1)
target_coll = client[db_name][coll_name]
coll_meta = config_db.collections.find_one({"_id": namespace})
if not coll_meta or coll_meta.get("dropped", False):
print(f"[FATAL] Namespace {namespace} is not currently sharded!")
sys.exit(1)
shard_count = max(config_db.shards.count_documents({}), 1)
try:
stats = list(target_coll.aggregate([{"$collStats": {"storageStats": {}}}]))
storage_gb = sum(s.get("storageStats", {}).get("storageSize", 0) for s in stats) / (1024**3)
index_gb = sum(s.get("storageStats", {}).get("totalIndexSize", 0) for s in stats) / (1024**3)
except PyMongoError as e:
print(f"[FATAL] Failed to retrieve collection storage stats: {e}")
sys.exit(1)
required_per_shard_gb = ((storage_gb + index_gb) * 2.0) / shard_count
print(f"Total Storage + Index : {storage_gb + index_gb:.2f} GB across {shard_count} shards")
print(f"Required Free / Shard : {required_per_shard_gb:.2f} GB (2x official formula)")
if config_db.reshardingOperations.find_one():
print("[FATAL] A resharding operation is already active.")
sys.exit(1)
if not dry_run:
res = admin_db.command({"reshardCollection": namespace, "key": new_key_dict})
print(f"[SUCCESS] Resharding completed: {res}")
else:
print(f"[DRY RUN] Would execute: sh.reshardCollection('{namespace}', {new_key_dict})")
def main():
parser = argparse.ArgumentParser(description="MongoDB Resharding Orchestrator")
parser.add_argument("--mongos-uri", required=True)
parser.add_argument("--ns", required=True)
parser.add_argument("--new-key", required=True)
parser.add_argument("--dry-run", action="store_true")
args = parser.parse_args()
client = MongoClient(args.mongos_uri, serverSelectionTimeoutMS=5000)
preflight_reshard_check(client, args.ns, json.loads(args.new_key), args.dry_run)
if __name__ == "__main__":
main()
In Practice
The operational tradeoffs of resharding follow directly from MongoDB’s routing and storage engine mechanics (CARL B/C — derived from documented system behavior, not personal benchmark claims):
- Scatter-Gather Elimination: When a query includes the shard key prefix,
mongosconsults its cached chunk map from the Config Server and dispatches the operation to only the owning shard(s), eliminatingSHARD_MERGEbuffering and cutting cross-shard index scans proportionally to shard count. - Evaluating Candidate Keys with
analyzeShardKey: Before committing to a multi-hour clone,analyzeShardKeyinspects two dimensions:keyCharacteristics(evaluating cardinality, frequency of the most common values, and monotonicity) andreadWriteDistribution(measuring what percentage of sampled reads and writes are single-shard vs. scatter-gather). Choosing a compound key with a high-cardinality prefix and a query-aligned suffix avoids trading scatter-gather reads for hot-shard monotonic write bottlenecks. - Clone I/O vs. Production Cache: During
reshardCollectioncloning, donor shards read collection data via WiredTiger snapshot cursors while recipient shards build indexes concurrently. Becauseconfig.reshardingOperationspersists coordinator state on the Config Server replica set, the operation survives Config Server primary failovers, though scheduling cloning during off-peak hours prevents index-build dirty cache pressure from throttling live writes. - Driver Resilience Across the Critical Section: Because
ReshardingCoordinatorbriefly blocks writes during the critical section before committing the catalog swap, drivers configured withretryWrites=true(the default in modern MongoDB 4.2+ drivers) transparently retry affected writes once the catalog swap completes.
Where It Breaks
| Condition | Breaks How | Detect | Mitigate |
|---|---|---|---|
| Insufficient 2x Disk Space | Coexisting old and new collections fill EBS volume during clone | EBS free space drops below ((storage + index) * 2) / N | Provision 2x free footprint across shards before starting |
| Oplog Rollover During Clone | Donor oplog overwrites entries before recipient finishes tailing | ReshardingCoordinator aborts with oplog position lost | Resize donor oplogs to 48h via replSetResizeOplog |
Drivers With retryWrites=false | Client writes during critical section fail immediately instead of retrying | Application write errors spike during cutover | Enforce retryWrites=true in all client connection strings |
| Concurrent DDL / Index Builds | Schema or index changes conflict with resharding metadata locks | DDL commands rejected or coordinator stalls | Freeze schema migrations in CI/CD during resharding |
| Unique Key Violation | Resharding with unique: true hits duplicate values in existing data | Clone phase aborts and discards progress | Pre-check uniqueness with an aggregation $group pipeline |
Leaving configureQueryAnalyzer On | Continuous query sampling adds overhead after analysis finishes | config.settings or server metrics show active sampling | Run configureQueryAnalyzer({ mode: "off" }) immediately |
April 2026 Update
MongoDB 7.0 and 8.0 expand shard key management beyond initial 5.0 resharding:
- Pre-Migration Validation (MongoDB 7.0+):
configureQueryAnalyzerandanalyzeShardKeymeasure key cardinality, monotonicity, and read/write routing distribution against live traffic before committing to a multi-hour clone. - Same-Key Redistribution (MongoDB 8.0+): Passing
forceRedistribution: truetoreshardCollectionredistributes chunks across newly added shards or zones without changing the shard key itself. - Collection Unsharding (MongoDB 8.0+):
sh.unshardCollection()consolidates an over-sharded collection back onto a single shard when cluster topology simplifies.
Key Takeaways
- Use
refineCollectionShardKey(4.4+) before reaching forreshardCollection: If queries still hit the existing prefix and you only need to break up jumbo chunks, appending a suffix is metadata-only and instant. - Verify
sh.reshardCollectionsyntax and 2x disk math up front: Pass the key document directly tosh.reshardCollection(ns, key)and confirm((storageSize + indexSize) * 2) / shardCountfree space per shard. - Always pair
analyzeShardKeywithconfigureQueryAnalyzer: Sample traffic first, runanalyzeShardKey, and explicitly setmode: "off"afterward. - Treat
retryWrites=trueand 48h oplog windows as mandatory prerequisites: They protect live writes during the critical section and prevent multi-hour clones from aborting on oplog rollover. - Keep
sh.abortReshardCollectionready until Phase 5: You can cancel an in-flight resharding safely without data loss anytime before the catalog swap commits.
What to Do Next
- Problem: Identify whether application query evolution has turned targeted shard lookups into cluster-wide
SHARD_MERGEscatter-gather broadcasts. - Solution: Evaluate candidate keys with
configureQueryAnalyzerandanalyzeShardKey(7.0+), refine suffixes withrefineCollectionShardKeywhere possible, or runsh.reshardCollectiononline. - Proof: Run
explain("executionStats")on top slow queries after cutover to confirmSHARD_MERGEis replaced by single-shard targeting. - Action: Audit client connection strings for
retryWrites=true, runmongo_resharding_orchestrator.py --dry-runagainst your target collection, and verify 2x disk headroom before scheduling the window.
Interactive tools for this topic