Backend Case Studies

Topic B14

Sharding

Splitting one table across several databases, and why the shard key decides everything.

10 min · advanced

Watch: looking up by user number asks just one database. Looking up by country has to ask all three.

id % 3 = 0id % 3 = 1id % 3 = 2shard 03·ID27·ID30·JPshard 119·ID22·US34·USshard 28·US11·ID14·JPapp
  • moving now
  • being checked
  • finished / the result
  • no longer used
Step 1 of 3

The users table is too big for one server, so it's split across 3 databases (shards) by user_id % 3. Each block: a user's id and country.

Queries using the shard key go to one shard. Any other query has to ask all of them.

When you need sharding

Almost never at the start. Before sharding, try this order: the right indexes, better queries, caching, read replicas, and a bigger database server. One modern PostgreSQL server can handle terabytes of data and tens of thousands of queries a second. Sharding only makes sense when writes or data size outgrow one machine, because replicas only help with reads.

Choosing a shard key

  • Used in almost every query: for a SaaS app, usually tenant_id (the customer company's id). All of one company's data sits on one shard, so JOINs and transactions still work within it.
  • Spreads evenly: a key with few values (country, status) makes shards lopsided. One giant customer can also make one shard "hot".
  • Doesn't change: if a row's shard key changes, the row has to move to another shard.
Code, for programmersPicking a shard in the app
const shards = [db0, db1, db2];

function shardFor(tenantId) {
  return shards[hash(tenantId) % shards.length];   // or a consistent-hashing ring
}

// one shard: fast, and transactions work as usual
const orders = await shardFor(tenantId).order.findMany({ where: { tenantId } });

// every shard: scatter, then gather, merge and sort in the app
const results = await Promise.all(shards.map((s) =>
  s.order.findMany({ where: { status: "late" }, orderBy: { createdAt: "desc" }, take: 20 })));
const latest = results.flat().sort((a, b) => b.createdAt - a.createdAt).slice(0, 20);

What you give up

  • JOINs and transactions across shards are no longer available for free.
  • Per-database auto-increment ids collide; use UUIDs or a global id generator (like Snowflake).
  • Adding a shard means moving data. With % N, nearly all of it moves; consistent hashing or a tenant-to-shard lookup table reduces that.
  • Backups, schema migrations and monitoring happen N times.

Quiz

  1. A table is sharded by user_id. Which query is most expensive?

  2. A bad shard key for a SaaS app?

  3. What should you try before sharding?

0 of 3 answered.