At some point a single database server stops being enough. You add indexes, cache hot reads, move reads to replicas, buy a bigger machine. All of that helps, but one thing does not move: every write still lands on one primary, and all the data still has to fit on one machine. When writes or data size outgrow the biggest server you can reasonably run, the next step is sharding.
What sharding is
Sharding splits one logical database into several smaller databases, called shards, each running on its own server. Every shard has the same schema but holds a different subset of the rows. Together, the shards contain all the data.
Example: an app with 40 million users. Instead of one users table on one server, you run four servers. Users 1 to 10 million live on shard 1, the next 10 million on shard 2, and so on. Each server stores a quarter of the data and handles about a quarter of the writes.
That is the whole point. Replication copies the same data to more machines, which helps reads. Sharding splits different data across machines, which helps writes and storage. In practice each shard is usually also replicated, so you get both.
The shard key
Every sharded table needs a rule that decides which shard owns a row. That rule is based on a column called the shard key (or partition key). The choice of shard key is the most important decision in a sharded design, because it is hard to change later.
A good shard key:
- spreads data and traffic evenly, so no shard becomes a hot spot;
- matches your most common queries, so most queries touch one shard only;
- rarely or never changes for a given row, because changing it means moving the row to another shard.
For a SaaS app, tenant_id (the customer company) is a common choice: almost every query is scoped to one tenant, so it hits one shard. For a social app, user_id is common.
Three ways to map keys to shards
Range-based. Each shard owns a range of key values: A to F, G to M, and so on, or dates by month. Range queries are efficient, since neighbouring keys sit together. The risk is hot spots: if the key grows over time (an auto-increment ID or a timestamp), all new writes go to the last shard.
Hash-based. Compute a hash of the key and use it to pick a shard. This spreads keys evenly and avoids the "newest data on one shard" problem. The cost: range queries now have to visit every shard. And a naive hash(key) % N has a nasty property: when you change N from 4 to 5, most keys map to a different shard and must move. Systems avoid this with consistent hashing or with many small fixed slots (say 1024 virtual shards) that are mapped onto physical servers, so adding a server only moves some slots.
Directory-based. A lookup table records which shard holds each key (or each tenant). It is the most flexible: you can move one large tenant to its own shard. The directory itself must be fast and highly available, since every request consults it, so it is usually cached.
A small routing function with fixed slots might look like this:
SLOTS = 1024 slot_to_shard = load_slot_map() # e.g. {0: "shard-a", 1: "shard-a", ..., 1023: "shard-d"} def shard_for(tenant_id: int) -> str: slot = hash_of(tenant_id) % SLOTS # use a stable hash, not Python's built-in hash() return slot_to_shard[slot] Where the routing happens
Something has to send each query to the right shard. There are three common places:
- In the application, through a library that knows the shard map (the code above).
- In a proxy or router between the app and the databases. Vitess for MySQL and MongoDB's
mongosrouters work this way. - In the database itself. Some distributed SQL databases, and extensions like Citus for PostgreSQL, shard tables for you and route queries internally.
Built-in or proxy-based sharding saves you from writing and maintaining the routing logic, which is a large part of the work.
What gets harder
Sharding solves a scaling problem and creates several new ones.
Cross-shard queries. A query that does not include the shard key must ask every shard and merge the results (scatter-gather). That is slower and more fragile. Global sorting, pagination and aggregates across all data become real work.
Joins. Joining two tables that live on different shards is expensive. A common fix is to shard related tables by the same key (orders and order items both by tenant_id) so their rows sit on the same shard. Small reference tables, like countries, can be copied to every shard.
Transactions. A transaction inside one shard works as usual. A transaction that touches two shards needs a distributed protocol such as two-phase commit, or a different design (sagas, idempotent retries). Most teams design so that transactions stay within one shard.
Unique IDs. An auto-increment column per shard gives duplicates across shards. Use UUIDs, or an ID scheme that includes a shard or machine number.
Rebalancing. Data grows unevenly. One shard fills up, or one tenant becomes huge. Moving data between shards while the system is live, without losing writes, needs careful tooling.
Operations. Backups, schema migrations and monitoring now run on N databases. A migration that fails on shard 3 of 8 leaves you in a mixed state.
Common mistakes
- Sharding too early. One well-tuned server with replicas, good indexes and caching goes a long way. Sharding is a cost you pay forever.
- A monotonically increasing range key. All inserts hit the last shard, and you have rebuilt a single-server bottleneck.
- A key your queries do not use. If most queries lack the shard key, most queries become scatter-gather.
-
hash % Nwith no plan for growth. Adding one server then moves most of the data. - Ignoring the big customer. With
tenant_idas the key, one very large tenant can outgrow its shard. Directory-based placement lets you isolate it.
Before you shard
Check the simpler options first: query and index tuning, caching, read replicas, a larger machine, archiving old data, and partitioning large tables inside one server. Also consider whether the data can be split by feature instead, moving one domain (say, analytics events) to its own database. If you still need to shard, prefer a database or proxy that does it for you.
In short
- Sharding splits rows across several databases so writes and storage can grow beyond one server.
- The shard key decides everything: even spread, query locality, stability.
- Range sharding keeps ranges together but risks hot spots; hash sharding spreads load but scatters ranges; a directory gives flexibility at the cost of a lookup.
- Cross-shard queries, joins, transactions and rebalancing are the price.
- Shard late, and let a proven tool do the routing when you can.
Watch the animated version: https://youtu.be/wBKvcJw8N9I
Originally published at abdeldjalilchougui.biz.

