System Design · 03. Data & Storage · 10 min · Intermediate

Sharding

Split one huge database across many machines, and pick how to split it.

In short

Sharding splits rows across servers, so 1.6B rows become 400M per shard on 4 shards. The shard key decides everything: range keys keep ranges together but make hot spots, hash keys spread the load but scatter ranges.

Keep common queries inside one shard, expect to ask all shards for the rest, and plan how to add shards before you need to.

Key ideas

  • Replication copies the same data. Sharding splits different data across machines. (step 1)
  • Range sharding is good for range scans and bad for hot spots; hash sharding is the opposite. Choose by your main queries. (step 6)
  • Plan for growth from day one: start with many small logical shards on few machines, so you can move whole shards later. (step 9)

Good to know

  • Now both the data and the writes are spread out. This is how a database scales past one machine's writes. (step 2)
  • Range queries stay on one or a few shards, because neighbouring keys live together. (step 3)
  • Pick a key with many different values that are used about equally often. (step 5)
  • A directory gives full control over placement. Many systems use it for a few special keys and hashing for the rest. (step 7)

Watch out

  • Any key that grows steadily (time, an auto-increment id) sends all new writes to the last range. (step 4)
  • Keep things that are used together on the same shard, for example all of a customer's orders and addresses. (step 8)
UsersRouterShard 1Shard 2Shard 3Shard 4

Key numbers

Shards
4
Rows per shard
400M
Hottest shard
25%

Terms

Sharding
Splitting the rows of one big table across several database servers, each holding a slice.
Shard key
The column the router uses to decide which shard a row belongs to.
Range sharding
Each shard owns a continuous range of the shard key, which keeps range scans on few shards.
Hot shard
A shard that gets far more traffic than the others, so adding shards does not help.
Hash sharding
Choosing the shard from a hash of the key, which spreads rows and traffic evenly.
Scatter-gather
Asking every shard the same query and merging the answers, needed when the key is not known.
Directory-based sharding
A lookup table says which shard holds each key, so keys can be placed and moved freely.
Cross-shard query
A query or transaction that touches several shards, which is slower and harder to keep correct.
Resharding
Changing the number of shards, which moves data; with hash % N most rows move.
Logical shards (buckets)
Many fixed small partitions mapped onto servers, so a new server takes whole buckets instead of reshuffling everything.