Lesson 8 of 9 · 24m
Partitioning and Sharding
Partitioning divides data inside one database; sharding divides ownership across databases. The hard part is choosing a key that keeps common work local.
You shard when one node cannot carry the write volume, storage, or blast radius anymore — not because a conference talk made it sound mature. Partitioning inside one database is often enough for years. True sharding multiplies operational complexity, so the key design decision is not the tool. It is the partition key.
Partitioning is often the first and best step
Declarative partitioning keeps one logical table but divides it into physical children:
CREATE TABLE events (
tenant_id bigint NOT NULL,
created_at timestamptz NOT NULL,
payload jsonb NOT NULL
) PARTITION BY RANGE (created_at);
CREATE TABLE events_2026_11 PARTITION OF events
FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');This is excellent for time-series workloads because dropping a month is metadata work rather than a billion row deletes. Indexes can stay local to partitions, vacuum works on smaller physical objects, and partition pruning can eliminate irrelevant scans.
Sharding is distributed ownership
With sharding, tenant_id or user_id often determines which database owns the row:
hash(tenant_id) mod 16 -> shard 0..15A good shard key makes common queries local. If 95% of requests touch one tenant, tenant sharding works well. If the hot query is global search across all tenants, tenant sharding just scatters everything and makes you build federation.
Cross-shard operations are the tax
The things that become hard immediately:
- joins across shards
- global uniqueness
- distributed transactions
- rebalancing hot shards
- consistent backups
- schema migrations
A system that can answer WHERE tenant_id = 42 locally may be fast forever. A system that constantly does scatter-gather across 32 shards is often slower and less reliable than the monolith it replaced.
Hot partitions defeat elegant math
Uniform hashing spreads keys evenly, but workload is not uniform. One celebrity tenant can turn shard 7 into a bonfire while the rest idle. Common mitigations are splitting hot tenants manually, directory-based placement instead of pure modulo hashing, or isolating whales onto dedicated shards.
tenant -> shard map
small tenants: hash directory ranges
tenant 88213: dedicated shard 19This is less elegant and more operable. Prefer operable.
Field notes
- Choose partition keys based on query patterns, not schema convenience.
- Time partitions should match retention and access patterns: daily, weekly, or monthly is a business question too.
- Sharding too early creates permanent complexity; exhaust vertical scaling, indexing, batching, and partitioning first.
- Resharding is a migration, not a toggle. Plan dual reads, backfills, verification, and rollback.
Was this lesson helpful?