Sharding (horizontal partitioning) splits one logical dataset across many database servers so that each server, or shard, stores and serves only a slice of the rows. It is how systems grow past the write throughput, storage and memory of the biggest single machine. The price is real complexity: routing, cross-shard queries, distributed transactions, hot spots and rebalancing all become your problem.
Think of it like
A multi-volume encyclopedia
No single book could hold every entry, so the encyclopedia is split into volumes: A to C, D to F, and so on. To look something up you first pick the right volume (routing), then search inside it. If a huge number of entries start with S, that volume becomes fat and everyone queues for it (a hot spot). When a new edition adds pages, the publisher has to decide how to re-split the volumes without reprinting the whole set (rebalancing).
Why shard at all?
A single database server has hard ceilings: disk capacity, RAM for the working set, CPU and, above all, write throughput. Database Replication scales reads by copying the data to more machines, but every replica still stores the full dataset and every write still lands on the leader. Sharding is the tool that scales writes and storage, because each shard owns a disjoint subset of the data.
Dataset
40 TB
5 years of orders
Usable per node
4 TB
leaving headroom for indexes and compaction
Peak writes
150k /s
one primary handles ~15k /s for this workload
Shards needed
≥ 10
max(40 ÷ 4, 150k ÷ 15k), plus growth headroom
- Shard / partition
- A subset of the rows, stored on one node (usually replicated for availability). Cassandra and Kafka say partition; MongoDB and Vitess say shard.
- Shard key / partition key
- The column(s) whose value decides which shard a row lives on, such as
user_idortenant_id. - Router
- The component that maps a key to a shard: a client library, a proxy (Vitess VTGate, MongoDB mongos) or the database itself.
- Hot spot
- A shard that receives a disproportionate share of data or traffic.
- Rebalancing
- Moving data between nodes when shards grow, nodes are added or load is uneven.
Vertical vs horizontal partitioning
Vertical partitioning
- Split by columns or tables: different data goes to different databases
- Example: user profiles in one database, user photos metadata in another, payments in a third
- Often follows service boundaries (functional partitioning)
- Easy first step, but each piece can still outgrow one machine
Horizontal partitioning (sharding)
- Split by rows: every shard has the same schema
- Example: users 0 to 9,999,999 on shard 1, the next 10 million on shard 2
- Scales almost without limit if the key distributes well
- Brings routing, cross-shard queries and rebalancing problems
In practice teams do both: first split the monolith's database by feature (vertical), then shard the few tables that keep growing (horizontal). The rest of this lesson is about horizontal partitioning. Use the simulation above to route keys to shards and watch how each strategy spreads them.
Partitioning strategies
Range-based
Each shard owns a contiguous range of key values, for example A-F, G-M, N-S, T-Z, or timestamps by month. Because neighboring keys live together, range scans are cheap: "all orders for user 42 in March" touches one shard. The danger is skew. A monotonically increasing key such as a timestamp or auto-increment ID sends every new write to the last shard while the others sit idle.
Hash-based
Apply a hash function to the key and assign by the hash: shard = hash(user_id) mod N, or better, assign ranges of the hash space to shards. A good hash spreads keys uniformly, so data and load are balanced even when the keys themselves are sequential. The cost is that range queries scatter across every shard, because adjacent keys hash to unrelated places.
Directory-based (lookup table)
A lookup service stores an explicit mapping key → shard, for example tenant 1187 → shard 7. This is the most flexible scheme: you can move one large tenant to a dedicated shard without touching anyone else. The directory is an extra hop and a critical dependency, so it must be highly available and cached aggressively by routers.
Geographic
Rows are placed by the user's region: EU users in Frankfurt, US users in Virginia. This cuts latency and helps with data residency laws such as GDPR. Shards are naturally uneven (regions differ in size), and users who travel or move need special handling. Geographic partitioning is usually combined with hash or range sharding inside each region.
| Strategy | Strengths | Weaknesses | Seen in |
|---|---|---|---|
| Range | Efficient range scans; easy to split a range in two | Hot spots with sequential keys; uneven sizes | HBase, Bigtable, CockroachDB, MongoDB ranged sharding |
| Hash | Even spread of data and writes | Range queries hit every shard; naive mod N rebalances badly | Cassandra, DynamoDB, Redis Cluster, MongoDB hashed sharding |
| Directory | Arbitrary placement; move single tenants | Extra lookup; the directory must never be down | Multi-tenant SaaS, Vitess lookup vindexes |
| Geographic | Low latency; data residency compliance | Uneven regions; cross-region queries are slow | Global SaaS, Spanner and CockroachDB locality settings |
Routing a query
Applications rarely talk to shards directly. A router (proxy or smart client) holds a cached copy of the shard map and forwards each query. Queries that include the shard key go to exactly one shard; queries that do not must be broadcast. Press play on each flow to compare.
Choosing a shard key
The shard key is the most consequential decision in a sharded design because it is expensive to change later. A good key satisfies several properties at once.
- High cardinality: many distinct values, so data can be spread over many shards.
countryhas about 200 values;user_idhas billions. - Even distribution of data and traffic: no value should own a large share of rows or requests.
- Matches the dominant access pattern: the most frequent queries should include the key, so they hit one shard.
- Keeps related data together: sharding all of a tenant's tables by
tenant_idlets joins and transactions stay on one shard (co-location). - Immutable: changing a row's key means physically moving it between shards.
| Workload | Good key | Risky key | Why |
|---|---|---|---|
| Multi-tenant SaaS | tenant_id | created_at | Tenant queries stay local; but plan for whale tenants |
| Social posts | author_id | post_date | Timelines read by author; a date key makes today's shard hot |
| Chat messages | (channel_id, time_bucket) | channel_id alone | Bucketing caps how large one busy channel's partition can grow |
| IoT metrics | (device_id, day) | timestamp | Timestamp alone sends all writes to one shard |
| E-commerce orders | customer_id | order_status | Status has a handful of values and skews heavily to "delivered" |
Hot spots and the celebrity problem
Even a perfect hash cannot fix skewed access to a single key. When a celebrity with 100 million followers posts, every read and like for that post targets one key, and one key always maps to one shard. Hash partitioning balances the number of keys, not the popularity of each key.
- Key salting (splitting): append a suffix to a hot key (
post:991#0topost:991#9) so writes spread over 10 shards. Reads must gather all 10 and combine them, so only salt keys you know are hot. - Cache hot reads: a read-heavy hot key is best absorbed by a cache tier or CDN in front of the shard.
- Aggregate writes: buffer counter increments (likes, views) in memory or a stream and apply them in batches.
- Dedicated shards: isolate whale tenants or celebrity accounts on their own hardware via a directory entry.
- Adaptive splitting: DynamoDB, Bigtable and CockroachDB detect hot ranges and split them automatically ("split for heat").
import random
SALT_BUCKETS = 10
def increment_likes(db, post_id: int) -> None:
# Each write picks a random sub-key, so they land on different shards.
salt = random.randrange(SALT_BUCKETS)
db.incr(f"likes:{post_id}#{salt}")
def read_likes(db, post_id: int) -> int:
# Reads pay the price: gather every sub-key and add them up.
keys = [f"likes:{post_id}#{s}" for s in range(SALT_BUCKETS)]
return sum(int(v or 0) for v in db.mget(keys))Cross-shard queries, joins and transactions
Queries and joins
A join between two tables sharded on different keys has to pull data from many shards into one place. The standard ways around it, roughly in order of preference:
- 1Co-locate: shard related tables by the same key (
ordersandorder_itemsboth bycustomer_id) so joins are local. Vitess and Citus call these shared or co-located keyspaces. - 2Reference tables: replicate small, rarely changing tables (countries, currencies, plans) to every shard.
- 3Denormalize: store the fields you need with the row (the author's name inside each post), accepting update fan-out.
- 4Application-side joins: query one shard, collect the foreign keys, then batch-fetch from the others.
- 5Offload analytics: stream changes to a warehouse or search engine for ad-hoc queries instead of running them against shards.
Transactions
A transaction on one shard keeps full ACID guarantees. A transaction that spans shards (transfer money from a user on shard A to a user on shard B) needs a coordination protocol such as two-phase commit, which adds latency and can block when the coordinator fails, or a saga with compensating actions. See Distributed Transactions. The design goal is to make cross-shard transactions rare by choosing the key so that most business operations touch a single shard.
Unique IDs
Per-shard AUTO_INCREMENT columns collide: shard A and shard B both produce ID 1. Sharded systems use globally unique IDs instead, such as Snowflake-style IDs or UUIDv7. See Unique ID Generation.
Secondary indexes
Looking up rows by a column other than the shard key (orders by coupon, users by email) needs a secondary index, and there are two ways to partition one.
Local (document-partitioned) index
- Each shard indexes only its own rows
- Writes are cheap: update one shard's index in the same transaction
- Reads by the indexed column must scatter-gather to every shard
- Used by MongoDB, Cassandra secondary indexes, Elasticsearch
Global (term-partitioned) index
- The index itself is partitioned by the indexed value (
emailhash) - Reads hit exactly one index partition
- A single row write may update index partitions on other shards
- Usually maintained asynchronously, so it is eventually consistent (DynamoDB GSIs)
Rebalancing
Data grows, nodes are added and some shards get hot, so data must move. A good rebalancing scheme moves as little data as possible, keeps serving reads and writes during the move, and spreads load fairly afterwards.
Why hash mod N is a trap
With shard = hash(key) mod N, going from 4 to 5 shards keeps a key in place only if h mod 4 = h mod 5, which is true for just 1 in 5 keys. About 80% of all rows must move to add one machine, and going from 10 to 11 moves about 91%.
| Approach | How it works | Pros | Cons | Used by |
|---|---|---|---|---|
| Fixed number of partitions | Create many more partitions than nodes (e.g. 1,024 on 8 nodes). Key → partition never changes; whole partitions move between nodes. | Simple, predictable; only moved partitions copy data | Must choose the count up front; too few means giant partitions | Elasticsearch, Redis Cluster (16,384 slots), Couchbase, Kafka |
| Dynamic splitting | A partition that exceeds a size threshold splits in two; small neighbors merge. | Adapts to data volume and skew automatically | Starts with one partition unless pre-split; splits cost I/O | HBase (10 GB regions by default), MongoDB chunks, CockroachDB, Bigtable |
| Consistent hashing | Nodes and keys on a hash ring; each node owns the arc before it, often via many virtual nodes. | Adding a node moves only about K/N keys | Range queries scatter; balance needs virtual nodes | Cassandra, Dynamo, Riak, many caches |
- 1
Copy a snapshot
Bulk-copy the moving partition from the source shard to the target while the source keeps serving traffic.
- 2
Stream the changes
Tail the source's replication log (binlog, WAL, oplog) and apply every write that happened during and after the copy.
- 3
Verify
Compare row counts and checksums until the target has caught up to within milliseconds.
- 4
Cut over
Briefly pause writes to that partition, apply the last changes, then atomically update the shard map so routers send traffic to the target.
- 5
Clean up
After a safety period, delete the data from the source. Vitess automates this with
MoveTablesandReshardworkflows built on VReplication.
Real-world examples
| System | Design |
|---|---|
| Instagram (PostgreSQL) | Several thousand logical shards (Postgres schemas) mapped onto far fewer physical servers. IDs are 64 bits: 41-bit millisecond timestamp, 13-bit logical shard ID, 10-bit per-shard sequence. Any ID tells you its shard, and moving a logical shard to a new server only changes the logical-to-physical map. |
| Notion (PostgreSQL) | 480 logical shards spread over 32 physical databases, keyed by workspace ID so that all of a workspace's blocks live together. 480 divides evenly by many machine counts, which makes later expansion simple. |
| Vitess (MySQL) | Born at YouTube, now used by Slack, GitHub and PlanetScale. VTGate routes queries, a VTTablet sidecar fronts each MySQL, and a topology service (etcd, ZooKeeper or Consul) holds the shard map. A vindex maps a column to a keyspace ID; shards own keyspace ID ranges named like -80 and 80-. |
| MongoDB | mongos routers, a replicated config server set and shards that are themselves replica sets. Data is split into chunks by ranged, hashed or zone sharding; a balancer migrates chunks between shards. Since 5.0 a collection can be resharded online with a new key. |
Implementation
Keys hash to one of 4,096 fixed logical shards; a small map assigns logical shards to physical databases. Rebalancing edits the map, never the hash.
import hashlib
LOGICAL_SHARDS = 4096
class ShardRouter:
def __init__(self, physical: list[str]):
# Start with logical shards spread round-robin over physical databases.
self.assignment = {s: physical[s % len(physical)] for s in range(LOGICAL_SHARDS)}
@staticmethod
def logical_shard(key: str) -> int:
# A stable hash (never Python's built-in hash(), which is randomized per process)
digest = hashlib.md5(key.encode()).digest()
return int.from_bytes(digest[:4], "big") % LOGICAL_SHARDS
def route(self, key: str) -> str:
return self.assignment[self.logical_shard(key)]
def move(self, logical: int, target: str) -> None:
# Called after the data copy for this logical shard has caught up.
self.assignment[logical] = target
router = ShardRouter(["db-0", "db-1", "db-2", "db-3"])
print(router.route("user:42")) # e.g. "db-1"
router.move(ShardRouter.logical_shard("user:42"), "db-4")
print(router.route("user:42")) # "db-4": only this logical shard movedKey takeaways
- Replication scales reads; sharding scales writes and storage by giving each node a disjoint slice of the data.
- Range sharding favors range scans but hot-spots on sequential keys; hash sharding balances load but scatters range queries.
- The shard key should have high cardinality, spread traffic evenly and appear in the most frequent queries.
- Hash partitioning cannot fix one very popular key: salt it, cache it or give it dedicated capacity.
- Never rebalance with
hash mod N; use many fixed logical partitions, dynamic splitting or consistent hashing. - Design so that most queries and transactions touch a single shard; everything else costs scatter-gather or 2PC.
Common pitfalls
- Sharding on a monotonically increasing key (timestamp, auto-increment) with range partitioning, which sends every write to the newest shard.
- Choosing a low-cardinality key such as country or status, which caps the number of useful shards and skews them.
- Relying on per-shard auto-increment IDs that collide across shards.
- Ignoring the queries that do not include the shard key until scatter-gather latency explodes at 100 shards.
- Sharding too early, before indexes, caching and read replicas have been exhausted.
Interview tips
- Justify sharding with a quick estimate of data size or write QPS versus a single node's limits.
- Name your shard key and test it against the two or three most important queries out loud.
- Bring up hot keys and rebalancing before the interviewer does; mention logical shards or consistent hashing.
- Distinguish local and global secondary indexes when asked how to query by a non-key column.
Real-world applications
- User and tenant data in large SaaS products (sharded by user or tenant ID).
- Wide-column and key-value stores such as Cassandra, DynamoDB and Bigtable, which shard internally.
- Search clusters (Elasticsearch indices split into shards) and message logs (Kafka partitions).
- MySQL and PostgreSQL at scale via Vitess, Citus or application-level routing.
Test yourself
Your orders table is range-sharded on created_at. What problem should you expect?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.