Building block

Sharding

Splits data across several independent databases by a key to scale writes and volume. The last resort when replicas, a cache and a bigger server are no longer enough.

Sharding: a router picks the shard by the hash of user_iduser_idhash 0hash 1hash 2ApplicationShard mapRouterShard 1Shard 2Shard 3
Sharding: a router picks the shard by the hash of user_id

When you cannot avoid sharding

Replication scales reads, but all writes go to one primary. When one server cannot keep up with writes or data no longer fits on disk (tens of terabytes), data is spread across several databases, each holding its part.

Before sharding, exhaust simpler steps: a bigger server (a modern machine with 64+ cores and a terabyte of RAM handles a lot), indexes, a cache, replicas, archiving old data. Sharding adds complexity for good.

Choosing a shard key

The key decides which shard a row lands on. For ShortLesson a logical key is user_id or school_id: all data of one user or one school sits together, and most queries hit one shard.

Hash sharding (hash(user_id) % N) spreads data evenly, but range queries become expensive. Range sharding (by date or alphabet) is handy for ranges but creates hot shards: all new writes land in the last one.

A bad key creates a «hot» shard: shard by course_id, have one course with a million students, and that one shard becomes the bottleneck.

The price: cross-shard queries and resharding

Joins and transactions across shards are either impossible or very expensive. Global reports have to be gathered from every shard or from a separate analytics store.

To add servers without moving data en masse, you create many logical shards (hundreds or thousands) and place them on fewer physical databases. In 2021 Notion split PostgreSQL into 480 logical shards on 32 physical databases. Ready made options: Citus for PostgreSQL, Vitess for MySQL, or distributed databases like CockroachDB that shard on their own.

Pros

  • Scales both writes and data volume.
  • One shard failing affects only some users.
  • Each shard is smaller, so indexes and backups are faster.

Cons

  • Joins and transactions across shards are expensive or impossible.
  • A wrong key creates hot shards.
  • Resharding is complex and risky.
  • Complicates migrations, backups and operations.

When to choose it

  • One server cannot keep up with writes even after optimization.
  • Data volume exceeds the reasonable size of one database.
  • There is a natural key that isolates most queries (user, school, tenant).

Where it is used

  • Instagram: thousands of logical PostgreSQL shards and IDs with an embedded shard number (2012).
  • Notion: 480 logical shards on 32 physical PostgreSQL databases (2021).

Tools

Sources

Logos belong to their owners and are used for identification only. Icons: Simple Icons (CC0), Devicon (MIT).