All academies
Roadmap
LEVEL 8 · SHARDING

Sharded Clusters

12 min read

Sharding splits a collection across multiple replica sets (shards), so no single machine holds all the data. A sharded cluster has three parts: mongos routers (query entry point), config servers (metadata), and the shards themselves. Explore the sharding simulator to see chunks migrate live.

The shard key

The shard key determines which shard stores each document. Documents are grouped into chunks by key ranges, and the balancer migrates chunks between shards to even out load. A good shard key has: high cardinality, even frequency, and non-monotonic values (a steadily increasing key like a timestamp sends all inserts to one 'hot' shard).

mongosh (against a mongos)
sh.enableSharding("shop")
sh.shardCollection("shop.orders", { userId: "hashed" })

Targeted vs scatter-gather

Queries that include the shard key are targeted to one shard. Queries without it are scatter-gather: every shard must answer. Design your shard key around your most common query pattern.

Check your understanding

Q1.

Which component routes client queries in a sharded cluster?

Q2.

Why is a monotonically increasing shard key (like a timestamp) problematic?

Q3.

A query that doesn't include the shard key must be sent to all shards.