Skip to content

Production MongoDB

Sharding

Horizontal scaling, shard keys, and why a bad key is worse than no sharding.

AdvancedAbout 6 minutes

Sharding splits a collection across shards (each shard is a replica set). mongos routes queries. You pick a shard key. A bad key is worse than staying on one replica set: hot shards, scatter-gather on every find, and pain moving data. Shard when working set and write volume no longer fit one primary — not because Atlas showed you a diagram.

// Range on ObjectId / createdAt — all new orders hit one chunk
sh.shardCollection("app.orders", { createdAt: 1 })

// Better for 'Rahul's orders': partition by the field you filter
sh.shardCollection("app.orders", { userId: 1, createdAt: 1 })
userId is high cardinality and matches how you query orders. createdAt alone is a hotspot.
  • Cardinality. Few distinct values (status) → huge chunks on one shard.
  • Monotonic keys. ObjectId, createdAt — inserts pile on the max chunk (hot shard).
  • Query isolation. If every find includes the shard key, mongos hits one shard. If not, it asks all of them.
  • Hashed keys spread writes; range queries on that field get worse. Trade-off, not a default.

The balancer moves chunks. You still need indexes per shard. Unique indexes must include the shard key (or be _id). Changing a shard key used to be a rewrite; modern MongoDB can reshard, still not a casual afternoon. Transactions across shards are allowed and more expensive. Prefer a bigger replica set and better indexes first (Query Performance).

Interview question

When do you shard MongoDB, and what makes a good shard key?

Think about it first.