Choosing a MongoDB Shard Key: Range, Hashed, Zones, Cardinality, and Hot Shards
Adding shards to a MongoDB cluster does not scale write throughput if every insert routes to the MaxKey chunk on a single shard; an unexamined shard key turns a distributed cluster into a single-primary bottleneck.
TL;DR
- Problem: Monotonic keys (
_id: 1, timestamps, counters) send 100% of inserts to one shard, while pure hashed keys (_id: "hashed") scatter-gather tenant reads across every shard (SHARD_MERGE).- Answer: Use a compound hashed shard key (
{ tenant_id: 1, _id: "hashed" }) so reads route toSINGLE_SHARDand writes hash evenly across chunks.- Watch out: Online resharding (
sh.reshardCollection) requires((collection_storage_size + index_size) * 2) / shard_countfree disk per shard and a brief write-blocking commit phase.
Situation
When a single MongoDB replica set hits vertical limits on CPU, WiredTiger working-set memory, or EBS IOPS, platform teams scale out to a sharded cluster: multiple replica-set shards, a 3-node Config Server Replica Set (CSRS), and distributed mongos query routers. Because every document already has a unique _id (defaulting to a 12-byte ObjectId), teams frequently enable sharding with { _id: 1 } as the range shard key.
In low-volume staging environments, { _id: 1 } appears to work. Under sustained production ingestion, however, every newly generated ObjectId starts with a 4-byte Unix epoch timestamp that increases monotonically. Instead of distributing writes across all shards, the cluster routes every insert to the single shard holding the upper-bound chunk [lastSplit, MaxKey). The cluster may have eight or sixteen shards provisioned, yet write throughput remains bounded by the single primary node owning that upper chunk.
Compound and hashed shard keys solve this write hotspot, but they introduce a second failure mode if designed without query-routing telemetry: scatter-gather reads (SHARD_MERGE) that multiply mongos fan-out by the number of shards in the cluster. Choosing a shard key therefore requires balancing write distribution, targeted read routing, chunk divisibility, and future resharding cost.
The Problem
Shard key design is governed by three hard mathematical and operational constraints:
- Monotonic range convergence: MongoDB partitions ranged shard keys into contiguous intervals
[MinKey, ..., MaxKey]. Because newObjectIds or timestamps always exceed prior values, 100% of inserts hit the single shard owning theMaxKeychunk, saturating its CPU, EBS IOPS, and WiredTiger write tickets while peer shards sit idle. - Hashed key space vs. range order: Hashed sharding computes an MD5-based 64-bit signed integer hash across
[-2^63, 2^63 - 1]. While that uniformly scatters monotonic inserts, it destroys range ordering and forcesmongosto broadcast queries that omit the hashed field (SHARD_MERGEscatter-gather across all shards). - Hashed index constraints: Within a compound shard key (supported since MongoDB 4.4), at most one field can be
"hashed", hashed indexes cannot enforceunique: true, and shard key fields cannot contain arrays (multikey indexes are disallowed). - Resharding storage headroom: Replacing a bad shard key online via
sh.reshardCollection()(5.0+) clones the collection and its indexes in parallel. MongoDB’s documented per-shard free disk requirement is((collection_storage_size + index_size) * 2) / shard_count(for example, a 2 TB collection with 400 GB of indexes across 4 shards requires((2 TB + 400 GB) * 2) / 4 = 1.2 TBfree per shard).
The core architectural question is: How do platform engineers design or migrate shard keys to eliminate monotonic write hotspots while keeping high-frequency application reads targeted to a single shard?
Options Considered
Four shard key patterns cover nearly all production sharding workloads, each with explicit failure boundaries:
| Strategy | Key Example | What It Gets Right | Where It Breaks | Decision |
|---|---|---|---|---|
| Monotonic Range | { _id: 1 } or { createdAt: 1 } | Efficient range scans on time or ID | 100% of new inserts hit the MaxKey shard | Reject for write-heavy ingest |
| Pure Hashed | { _id: "hashed" } | Uniform write distribution across all shards | Tenant or entity reads trigger SHARD_MERGE across all shards | Use only for point-lookup by _id |
| Compound Hashed (4.4+) | { tenant_id: 1, _id: "hashed" } | Targeted SINGLE_SHARD prefix reads + hashed write spread | Queries omitting tenant_id still scatter-gather | Recommended default |
| Zone Sharding | { region: 1, _id: "hashed" } | Pins data to regional shards for compliance or latency | Overlapping ranges or skewed regions create hot zones | Use when residency is required |
Pure hashed sharding is tempting because it fixes write hotspots immediately, but in multi-tenant systems where reads filter by tenant_id rather than _id, every read fans out to every shard. Conversely, range sharding on { tenant_id: 1 } alone fails when one large tenant exceeds the chunk threshold and creates an indivisible jumbo chunk. Compound hashed sharding solves both: tenant_id isolates reads, and _id: "hashed" spreads writes across chunks.
The Shard Key and Routing Architecture
Understanding how mongos and the CSRS route queries explains why shard key order and metadata caching directly determine cluster latency.
1. CSRS Metadata Catalog and mongos Routing Cache
The Config Server Replica Set stores cluster routing metadata in the config database (config.shards, config.databases, config.collections, and config.chunks). Each mongos instance caches this routing table in memory and serves client connections using that local map:
- Targeted routing (
SINGLE_SHARD): When a query includes the shard key or its leading prefix (such astenant_id),mongosbinary-searches its local chunk cache and dispatches the operation only to the shard(s) owning matching chunks. This keeps connection fan-out constant regardless of how many shards the cluster contains. - Scatter-gather (
SHARD_MERGE): When a query omits the shard key prefix—or uses a negated operator like$neor$nin—mongoscannot prune shards. It broadcasts the query to every shard in the cluster, waits for the slowest shard to respond, and merges or sorts the streams in theSHARD_MERGEstage. If the query also specifies asort()without an index or includes askip(),mongosmust buffer and sort results across all shards before returning the first batch. - Stale cache recovery (
StaleConfigException): After a chunk migration commits to the CSRS, the collection’s metadata version increments. Amongosholding a cached older version routes to the former owner shard, which rejects the operation withStaleConfigException. Themongosrouter then refreshes its routing table from the CSRS primary (or secondaries) and retries the operation transparently. Under normal migration rates this is invisible, but if the CSRS is starved for IOPS, routing table refreshes add tail-latency jitter across allmongosinstances.
2. Compound Hashed Shard Keys and Pre-Splitting (MongoDB 4.4+)
Enable compound hashed sharding by placing the dominant equality predicate first and the high-cardinality hashed field second. When sharding an empty collection with a hashed field, specify numInitialChunks so MongoDB pre-creates and distributes chunks across all shards immediately rather than starting with a single chunk on the primary shard:
sh.shardCollection(
"telemetry.events",
{ tenant_id: 1, _id: "hashed" },
false,
{ numInitialChunks: 8192 }
);
Any query filtering by { tenant_id: "ORG_4410" } targets only the chunks belonging to that tenant, while inserts for that tenant hash across multiple chunks instead of piling onto one MaxKey boundary. Note that numInitialChunks applies only when the collection is empty at shardCollection time; for populated collections, MongoDB splits and balances ranges incrementally or during reshardCollection.
3. Zone Sharding Mechanics for Residency and Locality
When regulatory compliance or latency requires pinning subsets of data to specific shards, Zone Sharding associates shard tags with contiguous key ranges via sh.addShardToZone() and sh.updateZoneKeyRange(). Because zone bounds are evaluated by the CSRS balancer against the shard key prefix, the residency attribute (such as region or country) must be the leading field in the shard key ({ region: 1, _id: "hashed" }). Leaving gaps between zone ranges or defining overlapping bounds causes the balancer to skip migrations or fail to converge.
3. Auditing Write Distribution and Query Targeting (mongosh)
Check insert distribution across shard primaries using serverStatus().opcounters.insert, and verify read targeting with explain("executionStats"):
// Verify whether a candidate query is targeted or scatter-gather
const exp = db.events.find({ tenant_id: "ORG_4410", status: "PROCESSED" }).explain("executionStats");
const stage = exp.queryPlanner.winningPlan.stage;
print("Root Stage: " + stage); // Expect SINGLE_SHARD; SHARD_MERGE indicates scatter-gather
4. Version-Safe Shard Key Evaluator (pymongo)
Because config.chunks switched from ns to uuid in MongoDB 5.0, the evaluator resolves the collection uuid from config.collections first (falling back to ns on 4.4) and checks explain() stages:
#!/usr/bin/env python3
import argparse, sys
from bson.max_key import MaxKey
from pymongo import MongoClient
def evaluate(client, namespace):
cfg = client.config
db_name, coll_name = namespace.split(".", 1)
coll_meta = cfg.collections.find_one({"_id": namespace})
if not coll_meta or coll_meta.get("dropped"):
sys.exit(f"Namespace {namespace} is not sharded.")
key = coll_meta["key"]
match = {"uuid": coll_meta["uuid"]} if "uuid" in coll_meta else {"ns": namespace}
dist = list(cfg.chunks.aggregate([{"$match": match}, {"$group": {"_id": "$shard", "n": {"$sum": 1}}}]))
for row in dist:
print(f"Shard {row['_id']}: {row['n']} chunks")
lead = next(iter(key))
max_chunk = cfg.chunks.find_one({**match, f"max.{lead}": MaxKey()})
if max_chunk:
print(f"MaxKey chunk resides on: {max_chunk['shard']}")
sample = client[db_name][coll_name].find_one()
if sample and lead in sample:
stage = client[db_name][coll_name].find({lead: sample[lead]}).explain()["queryPlanner"]["winningPlan"]["stage"]
print(f"Targeted query stage ({lead}): {stage}")
if __name__ == "__main__":
p = argparse.ArgumentParser()
p.add_argument("--mongos-uri", required=True)
p.add_argument("--ns", required=True)
a = p.parse_args()
evaluate(MongoClient(a.mongos_uri, serverSelectionTimeoutMS=5000), a.ns)
How It Rolls Out
Replacing a live shard key without downtime requires four gated phases so resharding never exhausts disk space or breaks query routing.
Phase 1: Sample Workload and Validate Candidate Key
On MongoDB 7.0+, enable query sampling via configureQueryAnalyzer and run analyzeShardKey to measure cardinality, monotonicity, and scatter-gather impact before touching production data:
db.adminCommand({ configureQueryAnalyzer: "telemetry.events", mode: "full", samplesPerSecond: 10 });
db.getSiblingDB("telemetry").events.analyzeShardKey({ tenant_id: 1, _id: "hashed" });
- Validation gate: Confirm
keyCharacteristics.isUniqueor cardinality/frequency metrics show no single value dominates chunk capacity, andreadWriteDistributionconfirms top queries include the leading key. - Rollback: Disable sampling with
mode: "off".
Phase 2: Verify Per-Shard Disk and Oplog Headroom
Calculate ((collection_storage_size + index_size) * 2) / shard_count across all shards and ensure EBS volumes and oplog retention windows cover the full clone duration.
- Validation gate: Every shard has at least the calculated free space plus a safety buffer, and replication lag is near zero.
- Rollback: Expand EBS
gp3volumes online before starting resharding.
Phase 3: Execute Online Resharding (sh.reshardCollection)
Run sh.reshardCollection() (MongoDB 5.0+) to create the temporary collection, clone documents, and stream concurrent writes via oplog/change-stream sync:
sh.reshardCollection("telemetry.events", { tenant_id: 1, _id: "hashed" });
- Validation gate: Monitor
db.getSiblingDB("admin").aggregate([{ $currentOp: { allUsers: true, localOps: false } }, { $match: { desc: "ReshardingCoordinatorService" } }])until cloning and oplog application converge. - Rollback: Before the final commit phase,
sh.abortReshardCollection("telemetry.events")cancels the operation and drops the temporary collection with zero impact on live traffic.
Phase 4: Verify Routing and Clean Up
After the atomic metadata cutover completes, run explain("executionStats") on primary application queries and inspect opcounters.insert across all shard primaries.
- Validation gate: Critical reads show
SINGLE_SHARDinstead ofSHARD_MERGE, and insert counts distribute across all shards. - Rollback: Reverting a committed shard key requires another
sh.reshardCollection()pass.
In Practice
Documented MongoDB engine behaviors explain why shard key mistakes compound under production load:
- Why monotonic keys defeat horizontal scaling: In MongoDB’s chunk model, a ranged key only splits when a range grows beyond the chunk size threshold. Because every new
ObjectIdor timestamp is strictly greater than all existing keys, all inserts land in the singleMaxKeychunk on one shard. Even as the balancer asynchronously splits and migrates older historical chunks to other shards, the active write edge remains pinned to one primary, capping cluster write throughput at a single node’s CPU and EBS IOPS. - Why pure hashed keys overload
mongos: In a sharded cluster withNshards, every scatter-gather query (SHARD_MERGE) opensNparallel cursors and forcesmongosto merge and sort results in memory. AsNgrows, router connection pools and CPU scale linearly withQPS * Ninstead of staying constant per query. - Why compound hashed keys resolve the tradeoff: Placing an equality-filtered field (
tenant_id: 1) ahead of a hashed suffix (_id: "hashed") restrictsmongosrouting to only the shard(s) holding that tenant’s chunks (SINGLE_SHARDwhen the tenant fits on one shard) while hashing writes across chunks to prevent single-chunk monotonic pileups. - Why
refineCollectionShardKeyis cheaper thanreshardCollectionwhen the prefix is sound: If a collection already uses{ tenant_id: 1 }and reads already filter bytenant_id, the prefix is valid—only its cardinality is insufficient. Building a compound index{ tenant_id: 1, _id: 1 }and runningrefineCollectionShardKey(4.4+) updates only the shard key metadata without cloning or rewriting documents. By contrast, replacing a monotonic prefix like{ _id: 1 }requiressh.reshardCollection()(5.0+), which rewrites the entire collection and its indexes across all shards.
Where It Breaks
| Condition | Breaks How | Detect | Mitigate |
|---|---|---|---|
Monotonic key ({ _id: 1 }) on write-heavy ingest | All inserts hit MaxKey chunk on one shard; peer shards sit idle | One shard at 100% CPU / high opcounters.insert | Reshard to { prefix: 1, _id: "hashed" } or { _id: "hashed" } |
Inverted compound key ({ _id: "hashed", tenant_id: 1 }) | Leading hash scatters writes, but tenant_id queries cannot use prefix | explain() shows SHARD_MERGE on tenant_id queries | Put equality query predicate first, hashed field second |
Low-cardinality prefix without suffix ({ tenant_id: 1 }) | One large tenant exceeds chunk limit and becomes an un-splittable jumbo chunk | config.chunks shows jumbo: true | Use refineCollectionShardKey (4.4+) to append _id |
| Queries omitting shard key prefix | mongos broadcasts to all shards (SHARD_MERGE), inflating router CPU and p99 | SHARD_MERGE in explain() / high mongos fan-out | Align shard key prefix with top read predicates |
| Mutating shard key values (4.2+) | Updating shard key requires cross-shard two-phase commit (delete + insert) | Elevated lock time and transaction aborts on updates | Choose immutable fields for the shard key |
Insufficient disk during reshardCollection | Temporary clone fills shard disk and aborts resharding | Disk usage alerts or resharding failure in logs | Verify ((data + index) * 2) / shards free space first |
| Overlapping or gap-ridden Zone Sharding rules | Chunks violate residency tags or balancer fails to converge | sh.status() shows misplaced chunks or balancer errors | Validate contiguous zone ranges in staging first |
April 2026 Update
MongoDB 7.0 and 8.0 added concrete tooling to validate and change shard keys with less operational risk:
- Workload analysis with
analyzeShardKey(MongoDB 7.0+): After enabling query sampling viaconfigureQueryAnalyzer,db.collection.analyzeShardKey()evaluates candidate keys against live read/write traffic, reporting key cardinality, frequency, monotonicity, and projected scatter-gather percentages before sharding. - Same-key redistribution in
reshardCollection(MongoDB 8.0): MongoDB 8.0 allowsreshardCollectionusing the same existing shard key (forceRedistribution) to rebalance skewed data across newly added shards without waiting for incremental chunk migrations. - Early resharding commit (
commitReshardCollection, MongoDB 8.0): Operators can issuesh.commitReshardCollection()to force an in-progress resharding operation to enter its write-blocking commit phase immediately when traffic is quiet.
Key Takeaways
- Never use monotonic range keys (
{ _id: 1 }, timestamps) for high-velocity ingest: Every new document lands on theMaxKeyshard, capping cluster write throughput at a single primary. - Avoid pure hashed keys when reads filter by an entity ID: Pure hashing fixes write skew at the cost of
SHARD_MERGEscatter-gather fan-out across every shard. - Default to compound hashed keys (
{ partition_key: 1, _id: "hashed" }): Put the dominant equality read predicate first and the hashed field second, respecting the one-hashed-field limit and non-unique constraint. - Size disk before running
sh.reshardCollection(): Confirm every shard has at least((collection_storage_size + index_size) * 2) / shard_countfree space. - Validate with
analyzeShardKey(7.0+) andexplain(): VerifySINGLE_SHARDexecution plans and balancedopcounters.insertafter every change.
What to Do Next
- Problem: Identify whether your sharded collection suffers from a
MaxKeywrite hotspot orSHARD_MERGEscatter-gather reads. - Solution: Design a compound hashed shard key (
{ tenant_id: 1, _id: "hashed" }) aligned with your primary query predicate and transition viash.reshardCollection(). - Proof: Compare
serverStatus().opcounters.insertacross all shard primaries and confirmexplain("executionStats")reportsSINGLE_SHARDon top read queries. - Action: On MongoDB 7.0+, enable
configureQueryAnalyzerand rundb.collection.analyzeShardKey()against your busiest sharded collection this week.