Tradeoff
Sign inGet started

GuidesDatabase sharding

Database sharding explained: when, how and when not to

10 min read · Updated 1 December 2026

Your app stores every order in one database. It started with a few hundred orders a day. Now it takes 30,000 writes a second at peak, and the table is 12 TB and growing. The database server is at 95% CPU, backups take all night, and every new index takes hours to build.

You have already bought the biggest machine your cloud sells. There is no bigger one. So what now?

The answer is to split the data across several databases, each holding a slice. This is called sharding. It is one of the most powerful scaling tools you have, and one of the most expensive to live with. This guide explains how it works, how to choose the key that decides where each row goes, and how to tell when you should not shard at all.

Key takeaways

  • Shard only after scaling up, read replicas, caching and archiving have run out. It is the last step, not the first.
  • Replication copies the same data to more machines. Sharding splits different data across machines. Most real systems do both.
  • The shard key is the big decision: it should spread load evenly and keep the data one request needs on one shard.
  • Hash sharding spreads load well but makes range queries expensive. Range sharding is the reverse.
  • Plan for resharding from day one, usually with many small logical shards that can move between machines.

When one database stops being enough

A single well-tuned database server can do a lot. Depending on the hardware and the queries, it can often take thousands to tens of thousands of simple writes a second and hold a few terabytes comfortably. Most apps never outgrow that.

But let's put numbers on an app that does. Say each write takes a little CPU and disk time, and your server tops out around 10,000 writes a second. Your peak is 30,000. The extra 20,000 queue up, and users wait for them. That is what people mean when they say the database is the bottleneck.

Size hurts too. At 12 TB, a restore from backup takes many hours, and a schema change that rewrites the table can run for a day.

You will usually hit one of these walls first:

  • Write throughput: one primary cannot accept writes fast enough.
  • Storage: the data no longer fits on one machine, or is painful to back up and restore.
  • Memory: the hot data no longer fits in RAM, so reads slow down.

Notice what is not on the list: lots of reads. Reads have cheaper fixes, which we will come to.

Scaling up, scaling out, and where replication fits

There are two ways to get more capacity.

Vertical scaling (scaling up) means moving to a bigger machine: more CPU, more memory, faster disks. It needs no code changes, which makes it the right first move. But it has a ceiling, and prices climb steeply near the top.

Horizontal scaling (scaling out) means adding more machines and sharing the work between them. There is no hard ceiling, but the machines now have to coordinate, and your code has to know about them.

Within scaling out, two ideas often get mixed up:

  • Replication puts the same data on several machines. One primary takes the writes and copies them to read replicas. This multiplies read capacity and gives you a standby if the primary dies. It does not help writes, because every replica still has to apply every write.
  • Sharding puts different data on different machines. Shard 1 holds customers A to F, shard 2 holds G to M, and so on. Each shard takes only its share of the writes and stores only its share of the data.

Think of a record room. Replication is photocopying the whole archive into three offices. Sharding is splitting it by surname so each office files only its own letters.

In practice you do both: every shard is its own small primary with a replica or two, so losing one machine does not lose a slice of your data.

App serversShard routerkey → shardShard 1users A–FShard 2users G–MShard 3users N–Z

Route each row by its key

The app hands a query to the shard router (a library or proxy that knows which shard owns which keys). A write for user Maya goes to shard 2, and only shard 2.

Choosing a shard key

Every row needs a rule that says which shard it lives on. The column that rule uses is the shard key. It is the single most important decision in a sharded design, because changing it later means moving almost every row.

A good shard key does two jobs:

  1. 1.Spreads the load evenly. Writes and storage should land on all shards, not pile up on one.
  2. 2.Keeps related data together. The data one request needs should sit on one shard, so most queries touch exactly one machine.

Let's try some keys for an online shop's orders table:

  • order_id: spreads perfectly, but "show me all orders for customer 42" now has to ask every shard.
  • created_at: today's orders all land on the newest shard, so one machine takes every write. Bad.
  • customer_id: a customer's orders, cart and addresses all live on one shard, and customers are many and fairly even. Usually the best pick.

Remember this important point: pick the key from your most common query, not from the table's primary key. If 90% of requests are "for this user", shard by user.

Range, hash and directory sharding

Once you have a key, you need a rule to turn it into a shard. There are three common ones.

Range sharding gives each shard a continuous range of keys: IDs 1 to 10 million on shard 1, the next 10 million on shard 2. Range queries ("orders from last week", "users M to P") hit one or two shards. But ranges follow real data, so they get lumpy, and an increasing key sends every new row to the last shard.

Hash sharding runs the key through a hash function and uses the result to pick a shard, for example hash(customer_id) mod 8. Even neighbouring keys land on different shards, so load spreads well. The cost is that range queries now have to ask every shard. A plain mod N also makes adding shards painful, because changing N moves most keys. Consistent hashing is the usual fix.

Directory sharding keeps a lookup table: key or key range → shard. The router reads it (and caches it). You can move any tenant to any shard just by updating a row, which is great for large customers who need their own shard. The cost is one more component that must be fast and always available.

ApproachHow a key finds its shardGood atWeak at
RangeKey falls inside a shard's rangeRange scans, simple to reason aboutHot spots, especially with increasing keys
Hashhash(key) picks the shardEven spread of writes and dataRange queries hit every shard
DirectoryLook the key up in a tableMoving single tenants, uneven customersExtra lookup service to run and keep available

Hot shards

Even with a good key, one shard can end up doing far more work than the others. This is a hot shard, and it is the most common trouble in sharded systems.

Here is how it happens. You shard a social app by user_id with a hash. Load looks even. Then one account with 40 million followers posts, and every like and comment on that post hits the shard holding it. That shard sees 50 times its normal traffic while the rest are quiet. Adding more shards does not help, because the hot data is one key.

Ways to cope, from simplest:

  • Cache the hot reads. A cache in front of the shard absorbs repeated reads of the same post. See caching strategies.
  • Split the key. Add a small suffix to hot keys, such as post_123#0 to post_123#9, so writes spread over ten shards. Reads then have to gather all ten pieces and add them up.
  • Split or move the shard. With range or directory sharding, carve the hot range out onto its own machine.
  • Buffer writes. Put counters through a queue and apply them in batches, so 50,000 likes become a few hundred updates.

In an interview, say it directly: "Hashing evens out the keys, but not traffic on a single key. For celebrity-style keys I would cache reads and split the key for writes."

Cross-shard queries and joins

On one database, joining orders to customers is one query. Once they live on different shards, the database cannot do that join for you.

Say you shard by customer_id and want "the 20 best-selling products this week". Every shard holds some of the orders, so the router must send the query to all shards, wait for each to answer, and merge the results. This is called scatter-gather. With 16 shards, the query is only as fast as the slowest of the 16, and it puts load on every machine.

Transactions get harder too. Moving money between two customers on two shards needs both writes to succeed or both to fail. Doing that across machines needs a protocol such as two-phase commit (a coordinator first asks every shard "can you commit?", then tells them all to commit). It works, but it is slow and blocks if the coordinator fails at the wrong moment.

So sharded designs try to avoid these cases:

  • Co-locate: shard related tables by the same key, so a customer's orders and payments sit together.
  • Denormalise: copy the few fields you need (product name, price) into the row, so you do not need a join.
  • Precompute: build reports like "best sellers" in a separate analytics store, fed by events, rather than querying the shards live.
  • Replicate small tables: a 10,000-row country table can be copied in full to every shard.

Resharding without downtime

Sooner or later you need more shards. That means moving data while the app keeps running, which is the hardest operation in a sharded system.

The most common trick is to over-split from the start. Instead of 4 shards, create 1,024 small logical shards and place 256 on each of 4 machines. When you add a fifth machine, you move whole logical shards to it. No row has to be re-hashed. Only the map from logical shard to machine changes.

Moving one logical shard usually goes like this:

  1. 1.Copy its existing rows to the new machine in the background.
  2. 2.Stream every new change to the new copy as well, until it catches up.
  3. 3.Briefly pause writes for that logical shard, flip the router's map, and resume.
  4. 4.Check the copies match, then delete the old one.

Tools such as Vitess (a sharding layer for MySQL) and Citus (an extension for PostgreSQL) handle routing and help move data between shards. The steps above still explain where your app may see slow or failed requests during a move.

Sharding vs partitioning, and when not to shard

Partitioning means splitting a table into pieces, which can all live inside one database server, as with PostgreSQL's partitioning by month. Sharding is partitioning across separate machines, each with its own CPU, memory and disk. All sharding is partitioning; not all partitioning is sharding. Horizontal partitioning splits rows (what sharding does); vertical partitioning splits columns or tables.

Before you shard, try these, in roughly this order:

  1. 1.Fix the queries. Add the missing index. Remove the query that scans a whole table.
  2. 2.Scale up. A bigger machine is cheap compared with engineers' time.
  3. 3.Add read replicas and a cache if reads are the problem.
  4. 4.Archive old data or partition by date inside the one database, so hot data stays small.
  5. 5.Split by feature. Move search, analytics or logs into their own databases.

Shard when writes or data size truly exceed one machine and the steps above have run out. A sharded database costs you joins, simple transactions, easy schema changes and easy operations. That is a fair price at 30,000 writes a second. It is a bad deal at 300. Do the arithmetic first; the back-of-the-envelope estimation guide shows how.

Questions people ask

What is database sharding in simple terms?

Sharding splits one large database into several smaller ones, each holding a slice of the rows. A shard key, such as the user ID, decides which database each row goes to. Each shard handles only its share of the reads, writes and storage.

What is the difference between sharding and partitioning?

Partitioning splits a table into pieces, which can all live on one database server. Sharding is partitioning across separate machines, so each piece gets its own CPU, memory and disk. Sharding scales writes and storage past one server; partitioning inside one server mostly makes big tables easier to manage.

What is the difference between sharding and replication?

Replication copies the same data to several machines, which adds read capacity and gives you a backup if one fails. Sharding puts different data on different machines, which adds write capacity and storage. Most large systems replicate each shard.

How do you choose a good shard key?

Pick a key that spreads load evenly and keeps the data for your most common request on one shard. For most apps that is the user, customer or tenant ID. Avoid keys that always increase, such as timestamps, because every new row lands on the same shard.

When should you not shard a database?

When better indexes, a bigger machine, read replicas, caching or archiving old data can still carry the load. Sharding makes joins, transactions and schema changes much harder, so it is worth it only when writes or data size genuinely exceed one machine.