Video in progress

When do you decide to shard PostgreSQL, and how do you choose the shard key?

Sharding is the last resort: only after vertical scaling, replicas, partitioning, archiving and query optimization are exhausted. The key should keep the most queries within a single shard and spread the load evenly, usually tenant_id or user_id.

📖 Answer

The moment you shard, you lose a number of things: JOINs across shards, global unique constraints, a single transaction, simple backup/restore, simple migrations. Every team now has to think "which shard does this query go to". That's why I first ask: what is the real limit, my write IOPS, the data volume, or connections?

Today a single PostgreSQL with 64-128 vCPUs and several TB of NVMe carries a great deal. In most projects the problem is in the schema or the queries.

If a shard is needed anyway, this is how I pick the key:

  • 95%+ of the main queries should stay on one shard. In SaaS that's almost always tenant_id.
  • The distribution should be even. One giant customer (a hot tenant) kills one shard, so there has to be a way to move such customers to their own shard.
  • The key should be immutable. If a user moves to another tenant, the data has to be moved.

The architecture options: routing inside the application (a tenant_id → shard table, AbstractRoutingDataSource), an extension like Citus (distributed tables, reference tables), or another database (CockroachDB, YugabyteDB), where you have to test full PostgreSQL compatibility and latency.

I always prefer the "directory" approach (a key → shard map) over a hash: when rebalancing, you can move customers one at a time. For global reports I collect data from the shards through CDC into a separate analytics store.