Sharding

Topic 8 of 10 in Week 3: Databases12 min readIntermediateFree course

Overview

Replication copies the same data to more machines, which helps with reads and availability. But if the data is too big for one machine, or there are too many writes for one leader, copying doesn’t help. You have to split the data. That’s sharding (also called horizontal partitioning): each shard holds a subset of the rows, and together they hold everything.

Sharding is powerful and expensive in complexity, so it usually comes after you’ve exhausted bigger machines, caching and read replicas.

How it works

Sharding: splitting data across databases. The app looks up user_id 1873. A shard router computes hash of user_id mod 4 equals 1 and sends the query to Shard 1 of four shards, each a database with replicas. Range sharding splits keys into ranges such as A to F or by date: it supports range scans but creates hot spots for new dates or popular letters. Hash sharding spreads keys evenly with a hash: load is even but range scans across shards are lost. Choose a shard key used by most queries and with many distinct values, such as user_id rather than country. Queries without the shard key must ask every shard, which is slow and expensive.

Each row has a shard key. A router maps the key to a shard. The router can be:

  • a library in the application,
  • a proxy layer (Vitess for MySQL, Citus for PostgreSQL, mongos for MongoDB),
  • built into the database (Cassandra, DynamoDB, CockroachDB, Spanner).

Each shard is usually itself replicated: a leader and followers.

Choosing the shard key

This is the most important decision, and the hardest to change later. A good shard key:

  • Appears in most queries, so most requests go to one shard.
  • Has many distinct values (high cardinality): user_id, not country.
  • Spreads load evenly, in both data size and traffic.
  • Keeps data that changes together on the same shard, so transactions stay local (all of a user’s orders with the user).

Examples: user_id for a social app, tenant_id for a B2B SaaS app, conversation_id for messages.

Range vs hash sharding

Range sharding assigns contiguous key ranges to shards: A–F, G–M, or January, February.

  • Range queries stay on one or a few shards.
  • Hot spots: if keys are timestamps, all new writes hit the newest shard; some ranges are simply more popular.

Hash sharding hashes the key and assigns by hash value.

  • Spreads data and load evenly, even for sequential keys.
  • Range queries over the key must visit every shard.

Some systems combine them: hash on one part of the key, range on another (Cassandra’s partition key plus clustering key).

Directory-based sharding keeps a lookup table from key (or tenant) to shard. It’s flexible, since you can move a big tenant to its own shard, but the directory must be fast and highly available.

The costs of sharding

  • Cross-shard queries: “top 10 products by sales across all users” must ask every shard and merge (scatter-gather). It’s slow and gets worse as shards are added. Answer such questions from a separate analytics store instead.
  • Cross-shard transactions: moving money between users on different shards needs distributed transactions or sagas.
  • No global constraints: a unique email across all shards needs a separate lookup table.
  • Joins across shards must be done in the application.
  • Operations: backups, schema changes and monitoring multiply by the number of shards.

Hot spots

Even with hashing, one key can be very hot: a celebrity user, a giant tenant, a viral post. Options:

  • cache that key’s data,
  • give big tenants dedicated shards (directory-based),
  • split the hot key with a suffix (user_id#1..#10) and combine on read,
  • rate-limit abusive traffic.

Resharding

Data grows, so you’ll need more shards. With hash(key) % N, changing N moves almost every key, which means a huge migration. Better approaches:

  • Many logical shards from day one: for example 1,024 logical shards mapped onto 8 physical servers; later you move whole logical shards to new servers without rehashing.
  • Consistent hashing: adding a node moves only a small fraction of keys (next lesson).
  • Online migration: copy data to new shards while writing to both, verify, then switch reads and writes.

In an interview

Shard only when your estimates demand it, and show the arithmetic: “50 TB and 80,000 writes per second exceed one database, so I’ll shard messages by conversation_id into 16 shards, each with replicas. Listing a user’s conversations uses a separate table sharded by user_id.” Then mention the hot-conversation risk and your resharding plan.

Recap

Sharding splits data across databases so storage and writes can grow beyond one machine. The shard key decides everything: it should match your main queries, have many values and spread load. Range sharding helps range scans but risks hot spots; hash sharding spreads load but scatters ranges. Expect cross-shard queries, transactions and resharding to be the hard parts, and plan for them from the start.

Exercise

Shard a messaging app

A messaging app stores 50 TB of messages and handles 80,000 message writes per second at peak; one database server can handle about 10 TB and 10,000 writes per second comfortably. Main queries: load the latest messages in a conversation; list a user's conversations. (a) Roughly how many shards do you need? (b) What shard key would you choose for messages, and why not user_id or message_id? (c) How would you serve 'list a user's conversations'? (d) What happens with a group chat that has 100,000 members and is very active?

Text
(a)
(b)
(c)
(d)

Summary

  • Sharding (horizontal partitioning) splits rows across several databases, each holding a subset of the data.
  • The shard key decides placement: it should appear in most queries, have many distinct values and spread load evenly.
  • Range sharding keeps ranges together but risks hot spots; hash sharding spreads load but loses range scans across shards.
  • Queries without the shard key must ask every shard (scatter-gather); cross-shard transactions are hard.
  • Plan for resharding from the start, for example with many logical shards or consistent hashing.