We sharded our events table by time and sent every write to one shard
After sharding a high-volume events collection on a timestamp-based key, write throughput did not improve at all. One shard took every insert while the others sat idle. Why monotonic shard keys create a hot shard, how we confirmed it, and the checklist we now use to choose keys.
Our product analytics pipeline writes user events (page views, clicks, searches) into a MongoDB collection. At around 25,000 inserts per second at peak, the single replica set was struggling, so we moved to a sharded cluster with four shards. We expected roughly four times the write capacity.
We got none. Peak write throughput stayed at about 25,000 per second, latency at peak got slightly worse, and the ingestion queue backed up exactly as before.
The shard key had been chosen to make time-range queries efficient:
sh.shardCollection("analytics.events", { createdAt: 1 })
Where the writes were going
Per-shard metrics made it obvious. Over one hour at peak:
shard inserts/s CPU disk write MB/s
shard-a 0 6% 1
shard-b 0 5% 1
shard-c 0 7% 2
shard-d 24,870 97% 182
Every insert landed on shard-d. The balancer was moving chunks off it constantly, which added load on
shard-d instead of relieving it. sh.status() showed the chunk ranges:
analytics.events
shard key: { createdAt: 1 }
chunks:
shard-a 212
shard-b 211
shard-c 212
shard-d 214
{ createdAt: ISODate("2026-10-27T08:12:00Z") } -->> { createdAt: MaxKey } on : shard-d
The chunk counts were balanced. The data at rest was balanced. But the last chunk, from the most recent
timestamp to MaxKey, lived on shard-d, and every new event has a createdAt later than everything
before it.
How range sharding routes writes
With a ranged shard key, MongoDB splits the key space into contiguous chunks and assigns each chunk to a shard. A document goes to the shard that owns the chunk containing its key value.
For a key that only ever increases, such as a timestamp, an auto-increment number, or an ObjectId (whose
first bytes are a timestamp), every new value is greater than all existing values. Every insert therefore
falls into the chunk that ends at MaxKey, and that chunk lives on one shard. The MongoDB documentation
describes this exact case: a monotonically changing shard key concentrates inserts on a single chunk and
therefore a single shard.
The balancer tries to help by splitting and migrating chunks, but it is always behind. As soon as the top chunk moves to a new shard, that shard becomes the hot one. Migrations also consume I/O on both source and destination, so the hot shard does its normal work plus migration work.
Reads were fine, which hid it
The key was great for the queries analysts run: "events for the last seven days" goes to the few shards that hold that time range. That is why nobody questioned it in review. A shard key has to serve writes and reads, and the two goals often conflict.
The same principle applies outside MongoDB: range partitioning a relational table by date puts all inserts in the newest partition (fine on one server, a hotspot if partitions live on different nodes), and systems like Cassandra or DynamoDB suffer the same with a time-based partition key.
Environment
| Item | Value |
|---|---|
| MongoDB | 7.0 sharded cluster, 4 shards (3-member replica sets) |
| Collection | analytics.events, 9 billion documents, about 25k inserts/s at peak |
| Shard key | { createdAt: 1 } (ranged) |
| Main queries | time range per tenant, time range per user |
The candidates
We evaluated three keys on a copy of a day's traffic replayed against a test cluster:
| Shard key | Write distribution | "Last 7 days for tenant T" query | "Events for user U" query |
|---|---|---|---|
{ createdAt: 1 } |
one shard | targeted | all shards |
{ _id: "hashed" } |
even | all shards | all shards |
{ tenantId: 1, createdAt: 1 } |
uneven: large tenants dominate | targeted | all shards |
{ tenantId: 1, userId: "hashed" } |
even | targeted to tenant's chunks | targeted |
A hashed key on a high-cardinality field spreads inserts evenly, because consecutive values hash to unrelated positions. But queries by time range must then go to every shard (scatter-gather).
A compound key with a tenant prefix kept queries targeted, but our largest tenant produces 30 percent of all events. All of that tenant's inserts at any moment would still go to one chunk, recreating a smaller hot spot.
What we chose
sh.shardCollection("analytics.events_v2", { tenantId: 1, userId: "hashed" })
MongoDB supports compound shard keys with one hashed field (since 4.4). The ranged tenantId prefix keeps
queries for one tenant on that tenant's chunks. The hashed userId spreads each tenant's writes across
many chunks, so even the largest tenant's traffic is distributed. Time-range queries within a tenant use a
secondary index on { tenantId: 1, createdAt: -1 } on each shard.
For a new collection with a hashed component, MongoDB can pre-split chunks at creation so writes are distributed from the first second, instead of waiting for the balancer.
Migrating
Changing the shard key of a live collection is possible with reshardCollection (MongoDB 5.0 and later).
It copies the data into the new distribution in the background and switches over with a short write block.
For 9 billion documents and our retention of 90 days, we chose a simpler route: write new events to
events_v2, keep reading from both collections, and let the old one age out. A view unioned the two for
analysts during the transition.
1. Write distribution. At the next peak, with the same traffic:
shard inserts/s CPU
shard-a 7,410 41%
shard-b 7,290 40%
shard-c 7,520 42%
shard-d 7,380 41%
Total peak throughput rose to about 29,600 per second (the traffic had grown) with headroom to spare. A load test against the test cluster reached 88,000 inserts per second before any shard saturated, close to four times the single replica set's limit.
2. Query targeting. We checked the main analyst queries with explain():
db.events_v2.find({ tenantId: "t-311", createdAt: { $gte: ISODate("2026-11-01") } })
.explain("queryPlanner").queryPlanner.winningPlan.shards.length
// 2 (only the shards holding t-311's chunks)
3. Alerting on imbalance. We alert when any shard's share of inserts exceeds 40 percent for 15 minutes. Chunk counts alone are not enough, as this incident showed: the chunks were perfectly balanced while the writes were not.
4. Security and isolation. Prefixing the key with tenantId has a useful side effect: every query
without a tenant filter is a scatter-gather query across all shards, which shows up clearly in our slow
query metrics. We use that as a signal for code that might be missing its tenant scope.
Shard key checklist
What we now go through before sharding anything:
- Cardinality: does the key have many distinct values? A low-cardinality key (country, status) limits how many chunks can exist.
- Frequency: is any single value very common? One tenant or one user with a huge share becomes a hot chunk.
- Monotonicity: does the key increase over time (timestamps, counters, ObjectIds)? If so, inserts will hit one shard unless it is hashed or not the leading field.
- Query shape: which queries must be targeted? Put their equality fields first.
- Growth: what does the distribution look like when the largest customer is ten times bigger?
- Changeability: resharding exists but is expensive. Test the key with replayed real traffic first.
Takeaways
- A monotonically increasing shard key sends every insert to the shard holding the top chunk.
- Balanced chunk counts do not mean balanced writes. Measure inserts per shard.
- Hash the part of the key that needs to spread writes, keep a ranged prefix for targeted queries.
- Choose shard keys against both write distribution and your main queries, with real traffic.
References: MongoDB choose a shard key, Hashed sharding, Reshard a collection.
Add a label
Embed this post
<iframe src="https://hibug.me/hot-shard-sequential-shard-key" width="700" height="420" frameborder="0" loading="lazy"></iframe>
I work on performance and capacity for a marketplace with heavy read traffic and sharp daily peaks. My days are split between caches, Redis, document stores, connection pools and the load tests that tell us whether any of it will hold. Most of the problems I write about looked like scaling issues and turned out to be something smaller: a cache that refilled itself with stale data, a single command that froze Redis, a pool drained by one leaked connection, a load test that measured its own generator instead of the system. I try hard to measure before changing anything, so each post includes how we gathered numbers, what they showed and how we confirmed the fix under realistic load. I also include the optimisations that made things worse, because those taught me the most.
Related Stories
One NULL in a subquery made our NOT IN report return zero customers
Comments
0No comments yet. Be the first to comment!
Sign In to post a comment.