Sharding
Overview
Replication copies the same data to more machines, which helps with reads and availability. But if the data is too big for one machine, or there are too many writes for one leader, copying doesn’t help. You have to split the data. That’s sharding (also called horizontal partitioning): each shard holds a subset of the rows, and together they hold everything.
Sharding is powerful and expensive in complexity, so it usually comes after you’ve exhausted bigger machines, caching and read replicas.
How it works
Each row has a shard key. A router maps the key to a shard. The router can be:
- a library in the application,
- a proxy layer (Vitess for MySQL, Citus for PostgreSQL, mongos for MongoDB),
- built into the database (Cassandra, DynamoDB, CockroachDB, Spanner).
Each shard is usually itself replicated: a leader and followers.
Choosing the shard key
This is the most important decision, and the hardest to change later. A good shard key:
- Appears in most queries, so most requests go to one shard.
- Has many distinct values (high cardinality):
user_id, notcountry. - Spreads load evenly, in both data size and traffic.
- Keeps data that changes together on the same shard, so transactions stay local (all of a user’s orders with the user).
Examples: user_id for a social app, tenant_id for a B2B SaaS app, conversation_id for messages.
Range vs hash sharding
Range sharding assigns contiguous key ranges to shards: A–F, G–M, or January, February.
- Range queries stay on one or a few shards.
- Hot spots: if keys are timestamps, all new writes hit the newest shard; some ranges are simply more popular.
Hash sharding hashes the key and assigns by hash value.
- Spreads data and load evenly, even for sequential keys.
- Range queries over the key must visit every shard.
Some systems combine them: hash on one part of the key, range on another (Cassandra’s partition key plus clustering key).
Directory-based sharding keeps a lookup table from key (or tenant) to shard. It’s flexible, since you can move a big tenant to its own shard, but the directory must be fast and highly available.
The costs of sharding
- Cross-shard queries: “top 10 products by sales across all users” must ask every shard and merge (scatter-gather). It’s slow and gets worse as shards are added. Answer such questions from a separate analytics store instead.
- Cross-shard transactions: moving money between users on different shards needs distributed transactions or sagas.
- No global constraints: a unique email across all shards needs a separate lookup table.
- Joins across shards must be done in the application.
- Operations: backups, schema changes and monitoring multiply by the number of shards.
Hot spots
Even with hashing, one key can be very hot: a celebrity user, a giant tenant, a viral post. Options:
- cache that key’s data,
- give big tenants dedicated shards (directory-based),
- split the hot key with a suffix (
user_id#1..#10) and combine on read, - rate-limit abusive traffic.
Resharding
Data grows, so you’ll need more shards. With hash(key) % N, changing N moves almost every key, which means a huge migration. Better approaches:
- Many logical shards from day one: for example 1,024 logical shards mapped onto 8 physical servers; later you move whole logical shards to new servers without rehashing.
- Consistent hashing: adding a node moves only a small fraction of keys (next lesson).
- Online migration: copy data to new shards while writing to both, verify, then switch reads and writes.
In an interview
Shard only when your estimates demand it, and show the arithmetic: “50 TB and 80,000 writes per second exceed one database, so I’ll shard messages by conversation_id into 16 shards, each with replicas. Listing a user’s conversations uses a separate table sharded by user_id.” Then mention the hot-conversation risk and your resharding plan.
Recap
Sharding splits data across databases so storage and writes can grow beyond one machine. The shard key decides everything: it should match your main queries, have many values and spread load. Range sharding helps range scans but risks hot spots; hash sharding spreads load but scatters ranges. Expect cross-shard queries, transactions and resharding to be the hard parts, and plan for them from the start.
Shard a messaging app
A messaging app stores 50 TB of messages and handles 80,000 message writes per second at peak; one database server can handle about 10 TB and 10,000 writes per second comfortably. Main queries: load the latest messages in a conversation; list a user's conversations. (a) Roughly how many shards do you need? (b) What shard key would you choose for messages, and why not user_id or message_id? (c) How would you serve 'list a user's conversations'? (d) What happens with a group chat that has 100,000 members and is very active?
(a)
(b)
(c)
(d)(a) Storage: 50 TB / 10 TB = 5. Writes: 80,000 / 10,000 = 8. Take the larger, add
headroom for growth and uneven load: ~12-16 shards (each with replicas).
Many teams start with many logical shards (e.g. 256) on fewer machines so they can
move them later.
(b) conversation_id. Loading a conversation is the hottest query, and with this key
all its messages live on one shard, sorted by time.
- user_id doesn't work: a message belongs to a conversation with several users.
- message_id (hashed) spreads writes evenly but scatters one conversation across
all shards, so every load becomes a scatter-gather query.
(c) Keep a separate table/index "conversations_by_user", sharded by user_id, updated
whenever a conversation gets a new message (denormalized, one entry per member).
(d) It's a hot shard: one conversation_id gets a huge share of writes and reads.
Options: cache recent messages for that chat, split its storage by time bucket
(conversation_id + day) or by sub-bucket, rate-limit, and fan out delivery through
a separate path rather than per-member writes.Summary
- Sharding (horizontal partitioning) splits rows across several databases, each holding a subset of the data.
- The shard key decides placement: it should appear in most queries, have many distinct values and spread load evenly.
- Range sharding keeps ranges together but risks hot spots; hash sharding spreads load but loses range scans across shards.
- Queries without the shard key must ask every shard (scatter-gather); cross-shard transactions are hard.
- Plan for resharding from the start, for example with many logical shards or consistent hashing.