Production MongoDB
Sharding
Horizontal scaling, shard keys, and why a bad key is worse than no sharding.
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 })- 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
findincludes 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?
When one replica set cannot hold the working set or write volume — after indexes and schema. A good shard key has high cardinality, avoids a monotonic hotspot, and appears in the filters you actually run so queries hit one shard. status or createdAt-only are common bad keys. A bad key is worse than not sharding.