Course contents

05. Distributed Databases Lesson 7 of 10

Database Sharding

See how a shard router splits data by key, why skewed keys create hot shards, what resharding costs, and why cross-shard queries are slow and fragile.

15 minIntermediate8 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Sharding splits rows across databases by a shard key; each shard stores and serves only its keys.
  • A router (or smart client) hashes or looks up the key to find the shard for every query.
  • Sharding spreads keys, not load: popular keys create hot shards that more shards cannot fix.
  • Consistent hashing moves only a fraction of keys when shards change, but the data still has to be copied.
  • Queries, joins and transactions across shards are slow, costly and fail when any shard is down.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

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.

The lesson as textEvery step of the simulation, written out.
  1. 1. All data lives in one database

    The application tier sends about 150 queries per second to a single database. It has a pool of 8 connections; a read takes about 20 ms and a write about 40 ms.

    At this load the database is a bit under half busy. Queries rarely wait for a connection.

    Scene: The app tier sends queries to one database, which is a little under half busy. Every query succeeds.

    Key idea: A single database has a ceiling set by its connections and how long each query holds one.

  2. 2. The database hits its ceiling

    Traffic triples to 450 queries per second, more than the roughly 330 one database can serve. Every connection is busy all the time and queries queue for the pool.

    A query that waits longer than 300 ms gives up with a pool timeout. Read replicas would help with reads, but every write still has to go to the one primary.

    Scene: At 450 queries per second the single database is saturated: all 8 connections are busy, queries wait and some fail with pool timeouts.

    Key idea: When writes or data size outgrow one machine, copying the data (replication) is not enough; you have to split it.

  3. 3. Split the data into three shards

    We split the rows across three databases (shards). Each one holds only the keys assigned to it. A shard router reads the key of every query, hashes it and sends the query to the shard that owns that key.

    Here every query is for a different user, so the keys spread evenly: each shard gets about a third of the traffic and the pool timeouts stop.

    Scene: A shard router sends each query to Shard 1, 2 or 3 based on a hash of its key. Each shard gets about a third of the traffic and nothing fails.

    Key idea: Sharding splits data by key, so each shard stores and serves only part of the load.

  4. 4. Adding a fourth shard

    We add Shard 4. With plain hash(key) % N, going from 3 to 4 shards would move about three quarters of all keys. The router uses a consistent-hash ring instead, so the new shard takes over only its own slices of the ring: roughly a quarter of the keys.

    The simulation moves traffic instantly. A real database would first have to copy those rows to Shard 4 while still serving them, then switch over. That migration is the hard part of resharding.

    Scene: Shard 4 joins the ring and receives roughly a quarter of the queries; the other three shards each get less than before.

    Key idea: Consistent hashing limits how many keys move when shards change, but moving data is still a careful, slow operation.

  5. 5. One shard runs hot

    Traffic grows to 800 queries per second, well within four shards’ total capacity, but it is no longer uniform: queries go to 5,000 customers with a Zipf popularity, so a handful of them (a celebrity, a huge retailer) send a large share of all queries.

    All queries for one key go to the same shard. The shard that owns the hottest keys runs out of connections and starts failing queries while the other shards have plenty of room. Adding shards does not help: a single key cannot be split.

    Scene: At 800 queries per second with skewed keys, one shard receives far more queries than the others, runs out of connections and fails some queries, while the rest stay lightly loaded.

    Key idea: Sharding spreads keys, not load. A skewed key distribution creates hot shards.

  6. 6. A shard fails

    Traffic falls back to 300 queries per second. Then,, one second in, Shard 2 crashes.

    Only queries for keys that live on Shard 2 fail; everything else keeps working. That is better than losing the whole database, but those users are completely stuck until Shard 2 is back. In production every shard is itself a replica set.

    Scene: Shard 2 goes offline. Queries for its keys fail; queries for keys on the other three shards still succeed.

    Key idea: A shard outage takes out a slice of the data, not all of it. Each shard still needs its own replicas.

  7. 7. Queries that need every shard

    Shard 2 is back. A reporting job now asks a question no single shard can answer ("total sales today"), so its service has to ask every shard and combine the results.

    This service asks the shards one after another, so its latency is the sum of four queries; asking in parallel would make it the slowest of four instead. Either way it adds load to every shard and fails if any one of them is down. Joins and transactions across shards have the same problem.

    Scene: A Reports service queries Shard 1, 2, 3 and 4 in turn for every report, so its requests take several times longer than a normal single-shard query.

    Key idea: Pick the shard key so that common queries touch one shard. Cross-shard queries are slow, costly and fragile.

  8. 8. What sharding costs

    Sharding is how databases scale writes and storage past one machine. The price: a router or smart client on every query, a shard key that is very hard to change later, hot spots when keys are skewed, cross-shard queries and transactions, and resharding as data grows.

    Try it first with vertical scaling, read replicas, caching and archiving old data. When you do shard, choose the key from your most common access pattern.

    Scene: Four shards behind a shard router, plus a Reports service that queries all of them. The router is highlighted as the piece every query depends on.

    Key idea: Shard late, choose the key carefully, and plan for hot keys and resharding from day one.