Topic B14
Sharding
Splitting one table across several databases, and why the shard key decides everything.
Watch: looking up by user number asks just one database. Looking up by country has to ask all three.
- moving now
- being checked
- finished / the result
- no longer used
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
A table is sharded by user_id. Which query is most expensive?
A bad shard key for a SaaS app?
What should you try before sharding?
0 of 3 answered.
Built on
Used in
No follow-up topics yet.