Introduction to sharding
Split data across machines when one primary can no longer hold the writes or the dataset.
16 min readWhen you need to shard
Caches and replicas scale reads, but every write still lands on one primary, and the whole dataset must fit on it. Sharding, also called partitioning, splits the data into independent pieces, each owned by a different primary with its own replicas. Ten shards give roughly ten times the write throughput and storage. Sharding adds real complexity, so reach for it only when estimates show you need it: sustained writes beyond what a single primary handles, or a dataset growing past what one machine can store and back up comfortably.
Choosing a shard key
The shard key decides which shard owns each row, and it is the most important choice in a sharded design. A good key spreads data and traffic evenly and keeps the data a typical query needs on a single shard.
- user_id for a social app: all of one user's data is together, queries by user hit one shard
- Short code for a URL shortener: every lookup goes straight to one shard
- Bad: created_at, because all new writes land on the newest shard
- Bad: country, because a few countries hold most users
Range, hash and consistent hashing
Range sharding assigns contiguous key ranges to shards, which keeps range scans efficient but risks hot spots when keys are sequential. Hash sharding applies a hash to the key and takes it modulo the number of shards, spreading load evenly but making range queries span every shard. Plain modulo has a nasty property: changing from 10 to 11 shards remaps almost every key. Consistent hashing places shards and keys on a ring so adding a shard moves only about 1/N of the keys, which is why distributed caches and many databases use it.
What sharding costs
Queries that do not include the shard key must ask every shard and merge the results, which is slow and scales badly. Joins and transactions across shards are hard or unavailable. Hot keys, such as one celebrity account, can still overload a single shard. Rebalancing data when you add shards takes careful tooling. Many teams delay sharding with caching, replicas and better indexes, then shard along one obvious key. In SystCode problems, add partitions when the Feedback panel shows the write path or storage of a single node as the bottleneck.
Key takeaways
- Shard when writes or data size outgrow a single primary, not before
- Pick a shard key that spreads load evenly and keeps common queries on one shard
- Consistent hashing moves only a small fraction of keys when shards change
- Cross-shard queries, joins and hot keys are the price of sharding
Sign in to track lessons and earn badges.