StoicBuilder

HandbookXIII the AqueductSharding

XIIIthe Aqueduct, Scale it

Sharding

1 min readUpdated 28 November

In plain words

Sharding splits your data across several databases by a shard key, such as account ID, so each holds only part of the rows and the writes are spread out, at the cost of harder queries across shards.

Where you see it

Harbor's deploy logs pass 3 billion rows, and one Postgres primary can't keep up with the writes even after indexing and a bigger machine. The team shards the table by account ID across 8 nodes with Citus, and every query for one account still goes to exactly one shard.

lib/shards.tsserver
const SHARDS = 8;function shardFor(accountId: string) { return hash(accountId) % SHARDS; // same account, same shard, every time} const db = shardPools[shardFor(accountId)];await db.query("insert into deploy_logs (account_id, line) values ($1, $2)", [accountId, line]);
Modulo is the simplest router and the hardest to change: going from 8 to 9 shards moves most rows. A lookup table or consistent hashing moves far fewer.

What goes wrong

  1. Sharding before you need to

    Indexes, a read replica, partitioning or archiving old rows, and a bigger machine take a single Postgres a long way. Sharding makes every query, migration and backup more complex, so it belongs at the end of the list.

  2. A shard key that piles onto one shard

    Sharding by date sends all of today's writes to one shard, and your largest customer can overload theirs. Pick a key that spreads the load and that most queries include.

  3. Queries that need every shard

    A report across all accounts now asks every shard and combines the answers, and a transaction spanning two shards loses its usual guarantees. Choose the key around the queries you run most.

What to tell your agent

Copy this into Lovable, Bolt, Cursor or any agent
Before proposing sharding, show me what one database could still do: query and index fixes, partitioning old rows, a read replica and a larger instance, with rough numbers. If we still need it, compare two shard keys by how evenly they spread writes and which of our ten busiest queries would have to touch every shard.

Quick check

Sign in to earn +10 XP for it

Harbor shards its deploy logs by account ID. Which query becomes expensive?

Got a prompt that touches sharding?

Paste it. You get a better prompt first, then the cards that explain it.

Check your own prompt

Free, no sign-up.