Database Sharding
By Ankur NayakReviewed
Sharding splits one large dataset across many database servers, each holding a subset of the rows chosen by a shard key. It lets storage and write throughput grow beyond what a single machine can handle.
How it works
A single database server eventually runs out of disk, memory or write capacity. Sharding (horizontal partitioning) spreads rows across many servers. A shard key, such as a user ID or channel ID, decides where each row lives: by hashing the key, by key ranges, or by looking it up in a directory.
The shard key is the most important decision. Queries that include the key go to one shard and stay fast; queries that don't must scatter to every shard and gather the results. A good key spreads load evenly and keeps data that is read together on the same shard.
Hot keys (one celebrity, one huge channel) can still overload a shard. Common fixes are splitting a hot key into buckets (for example by time window), caching it, or giving it a dedicated shard.
Key points
- Shard key decides data placement and which queries are cheap
- Hash sharding spreads load; range sharding keeps scans efficient
- Cross-shard joins and transactions are expensive or unavailable
- Plan resharding up front: consistent hashing or many small logical shards
When to use it, and pitfalls
Use it for
- Data or write volume beyond one machine
- Workloads where most queries include a natural key (user, tenant, channel)
Watch out for
- A low-cardinality or skewed key (country, date) creating hot shards
- Secondary indexes on non-key fields become global and eventually consistent
- Resharding live data is operationally hard; over-provision logical shards
Trade-offs
Hash vs. range sharding
Hash by the access key unless range scans dominate.
Pros: Hash: even distribution, no hot ranges; Range: efficient ordered scans and time-based queries
Cons: Hash: range queries hit every shard; Range: sequential keys (timestamps) pile onto one shard
Used in
Related building blocks
Frequently asked questions
What is the difference between sharding and replication?
Sharding splits data so each server holds a different part, which scales storage and writes. Replication copies the same data to several servers, which adds read capacity and fault tolerance. Large systems do both: every shard is replicated.
How do you pick a shard key?
Pick the key that most queries filter on and that has many evenly used values: user ID, tenant ID or conversation ID are typical. Avoid keys that grow monotonically or concentrate traffic, such as timestamps or country codes.
Sources
- Sharding pattern · Microsoft Azure Architecture Center
- Designing Schemaless, Uber Engineering's Scalable Datastore Using MySQL · Uber Engineering
- How Discord Stores Trillions of Messages · Discord Engineering