What it is
Sharding (horizontal partitioning) splits the rows of a dataset across several independent databases called shards. Every row belongs to exactly one shard, chosen by its shard key: a customer id, a tenant id, an order id. Together the shards hold the whole dataset; each one holds only a slice of it and serves only the queries for that slice.
Why it exists
A single database server has limits: how many writes per second it can commit, how much data fits on its disks and in its memory, how many connections it can serve. Vertical scaling (a bigger machine) raises those limits until it becomes too expensive or simply impossible. Read replicas help with reads, but every write still goes to one primary and is then replayed on every replica, so replicas do nothing for write throughput or for total data size. Sharding is the way to scale writes and storage beyond one machine: each shard handles only its share.
How it works
Choosing the shard. Every query must carry the shard key so the system can find the right shard. Common strategies:
- Hash-based: shard = f(hash(key)). Spreads keys evenly and avoids hot ranges, but range queries ("orders from last week") must ask every shard.
- Range-based: keys in [A–F] go to shard 1, [G–M] to shard 2, and so on. Range scans stay on one shard, but sequential keys (timestamps, auto-increment ids) pile up on the last shard.
- Directory-based: a lookup table maps keys (or tenants) to shards. Flexible, lets you move single tenants, but the directory is one more critical component.
Routing. A router sits in the query path (a proxy such as Vitess or a Citus coordinator), or the application uses a shard-aware client library. Either way, the same key always reaches the same shard.
Hashing and resharding. With hash(key) % N, changing N moves almost every key: going from 4 to 5 shards relocates about 80% of the data. Consistent hashing places shards at many points on a hash ring, so adding a shard moves only the keys in the ring slices it takes over (about 1/N of the data). Many systems instead create many small logical partitions up front (say 1,024) and move whole partitions between machines, which turns resharding into moving files rather than rehashing rows.
Moving data. Whatever the scheme, the rows must be copied to their new shard while the old one keeps serving traffic, then reads and writes switch over, and only then are the old copies deleted. Doing that online, without losing writes that happen during the copy, is the hard part of running a sharded database.
When to use it
- Write throughput or dataset size has outgrown the largest practical single machine.
- Data divides naturally by a key that most queries include: tenant id in a SaaS product, user id in a social app, account id in a ledger.
- You need to isolate tenants from each other (noisy neighbours, data residency).
When not to
- When a bigger machine, read replicas, a cache, better indexes or archiving old data would do. Each of these is far cheaper to operate.
- When most important queries need data from many keys at once (analytics, global search, rich joins); every one of them becomes a cross-shard query.
- Early in a product's life, before the access patterns and the right shard key are known. A wrong shard key is very hard to change.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| Hash sharding | Even spread, no hot ranges | Range queries hit every shard |
| Range sharding | Efficient range scans | Hot spots on sequential keys; manual rebalancing |
| Directory sharding | Move individual tenants freely | An extra lookup and a critical metadata store |
| Many small partitions | Cheap rebalancing by moving partitions | More objects to manage; a fixed upper bound on shards |
| Fine-grained key (e.g. customer + order) | Spreads hot customers | A customer's data spans shards; per-customer queries fan out |
Alternatives
- Vertical scaling: a larger machine. Simple, no application changes, finite.
- Read replicas: scale reads, not writes or storage.
- Caching: take repeated reads off the database entirely.
- Functional partitioning: separate databases per domain (orders, users, catalogue) instead of splitting one table.
- Distributed SQL / managed partitioned stores (CockroachDB, Spanner, DynamoDB, Cassandra): the database shards and rebalances for you, at the cost of their own consistency and data-modelling rules.
Failure modes
- Hot shard: a celebrity user or a huge tenant sends a large share of traffic to one shard. More shards do not help because one key cannot be split; you need a finer key, special handling for the hottest keys (a dedicated shard, caching, write batching), or salting the key.
- Shard outage: when a shard is down, every key on it is unavailable. The rest of the system works, which is better than a total outage, but each shard still needs its own replicas and failover.
- Cross-shard queries: a scatter-gather query asks every shard. Run sequentially, its latency is the sum of all of them; in parallel, the slowest shard. Either way it adds load everywhere and fails if any shard fails.
- Distributed transactions: an update touching two shards needs two-phase commit or a saga; without either, a crash can leave the shards inconsistent.
- Unbalanced growth: some shards grow faster than others and fill up first.
- Resharding gone wrong: lost writes during a migration, or a double write that leaves two versions of a row.
In production
Pick the shard key from the most frequent access pattern and include it in every query. Start with more logical partitions than machines so you can rebalance by moving partitions. Replicate every shard. Keep global or cross-shard data (reports, search) in separate systems fed asynchronously, such as a warehouse or a search index. Monitor per-shard load, storage and latency, not only the totals, so a hot shard shows up before it fails. Rehearse resharding before you need it.
Common misconceptions
- "Sharding spreads load evenly." It spreads keys. If key popularity is skewed, load is skewed too.
- "Replication and sharding solve the same problem." Replication copies data for availability and read scaling; sharding splits it for write and storage scaling. Large systems use both.
- "Consistent hashing makes resharding free." It limits how much data moves. The data still has to be copied and switched over safely.
- "We can pick the shard key later." Changing it means rewriting every row and every query that depends on it.
Interview angle
Interviewers want to see that you reach for sharding only when needed and with numbers: "write rate is 50k/s and the dataset is 20 TB, beyond one primary." Then they probe the shard key (what does it optimise, where are the hot keys?), routing, how you reshard, how cross-shard queries and transactions are handled, and how each shard stays available. Naming hot partitions and how you would mitigate them, and moving analytics off the shards, are strong signals.
Model assumptions
The simulation is a simplified model, not a benchmark. Each database has a pool of 8 connections; reads take 20 ms and writes 40 ms on average (lognormal, cv 0.4) and 20% of queries are writes, so one database serves roughly 330 queries per second; a query that waits more than 300 ms for a connection fails. The router is a load balancer with a consistent-hash ring of 64 virtual nodes per shard, so shard shares are only roughly equal. Data migration is not modelled: when a shard is added, traffic moves instantly. Skewed traffic uses a Zipf distribution (exponent 1.5) over 5,000 keys. The reports service queries shards one after another. Numbers show behaviour and orders of magnitude only.