Partitioning and Sharding

Split big tables and datasets by key so no single table or server has to hold everything.

Advanced · about 4 hours · difficulty 4/5

Learn first: Replication, Read Replicas and Failover, Indexes and Query Performance

When one table holds billions of rows, or one server cannot handle the write load, you split the data.

Partitioning within one database

Table partitioning divides a large table into smaller physical pieces by a key, while queries still see one table. PostgreSQL supports range (by month), list (by region) and hash partitioning. Benefits: queries that filter by the key touch fewer partitions, and dropping an old month is instant instead of a giant DELETE. This is often enough and much simpler than sharding.

Sharding across servers

Sharding puts different subsets of rows on different database servers. Each shard is a full database holding, say, a range of tenant ids.

  • Shard key choice is everything. A good key spreads load evenly and keeps data queried together on the same shard (tenant id for a B2B SaaS, user id for a social app).
  • Hash-based sharding spreads evenly; range-based keeps ranges together but risks hot spots; a lookup directory gives flexibility at the cost of another component.

What sharding costs you

  • Cross-shard joins and transactions become hard or impossible.
  • Resharding when a shard gets too big is a major project.
  • Every query must know which shard to hit.

Tools like Vitess (MySQL) and Citus (Postgres) hide much of this, and distributed SQL databases (CockroachDB, YugabyteDB, Spanner) shard automatically.

Before you shard

Exhaust the cheaper options first: better queries and indexes, caching, read replicas, a bigger machine, table partitioning and archiving cold data.

You are ready to move on when you can partition a large events table by month and argue for a shard key in a multi-tenant app.

Key concepts

  • Range, list and hash partitioning
  • Choosing a shard key
  • Hot spots and skew
  • Cross-shard queries
  • Resharding
  • Vitess, Citus and distributed SQL

Mini project

Convert an events table to monthly range partitions in Postgres, measure query plans before and after, and write a script that detaches partitions older than a year.

Check yourself

Why is created_at usually a poor shard key for a write-heavy table?

Free resources