Sharding & Partitioning

When one database cannot hold the data: shard keys, consistent hashing, hotspots, rebalancing.

Advanced8 min read
Language
Theme
user_idthe shard keyhashShard 1own DB serverShard 2own DB serverShard 3own DB serverConsistent hashingring: adding a server moves ~1/NCelebrity problemhot key melts its shard
Key idea at a glance
INTERACTIVE

Playground: the consistent hashing ring

24 keys live on the ring, each owned by the next node clockwise. Add or remove a node and count how many keys move. Then flip to naive modulo and see why nobody uses it.

When one database is not enough

Read scaling is solved by replicas; the wall that remains is writes and storage. One primary accepts every write, and one machine holds every byte. When writes exceed what one primary can absorb, or the dataset outgrows one disk (or one backup window), you split the data across machines: sharding. Each shard is a full database holding a subset; the app knows which shard owns which rows.

The shard key: the decision you cannot undo cheaply

What do you split by? A good shard key does two things: spreads load evenly and keeps common queries inside one shard. Common choices:

  • user_id: all of a user's data on one shard; user-centric queries are single-shard and fast. Risk: the celebrity problem (one user with 100M followers is one very hot shard).
  • time: recent data on the newest shard. Great for time-series retention (drop old shards instead of deleting rows), but all of today's writes hit one shard: a permanent hotspot.
  • geography: users sharded by region; low latency and data-residency compliance, uneven distribution.

Changing the shard key later means rewriting every row. Choose like you mean it.

Routing: hash mod N vs consistent hashing

hash(key) % N: perfectly even, but adding one server changes N and remaps almost every key: a full data migration. Consistent hashing: keys and servers both sit on a ring; each key belongs to the next server clockwise. Adding a server moves only ~1/N of keys. Add virtual nodes (each physical server claims many ring positions) and the spread smooths out. DynamoDB, Cassandra and CDNs all use versions of this.

What sharding costs (say this part out loud)

  • Joins die: data that joins now lives on different machines; you join in application code or denormalize.
  • Transactions die (mostly): cross-shard atomicity needs two-phase commit, which is slow and fragile; most teams design to avoid it.
  • Cross-shard queries: "top posts globally" now means querying all shards and merging (scatter-gather): slow and expensive.
  • Resharding and ops: N databases to back up, monitor, migrate and rebalance.

Hence the rule: shard last. First indexes, caching, read replicas, vertical scale, archiving old data. Most systems never need sharding; some need it for one table only.

The celebrity problem deserves its own paragraph

Even perfect hash distribution fails when load is not uniform: one key gets 30% of traffic and melts its shard. Fixes: split hot keys with a suffix (key becomes key:0..key:99, spread across shards, merge on read), cache aggressively, or special-case known hot entities. Naming this problem before the interviewer does is free points.

Worked example: sharding a social app's posts

500M users, 2 TB of posts/year. Shard by user_id with consistent hashing, 64 logical shards to start (over-shard logically so physical rebalancing is cheap). Feed reads hit one shard per author. Celebrities (>1M followers): their posts are pulled at read time instead of pushed, so no single write fans out onto one shard 100M times.

Common interview traps

  • Sharding as the first scaling step.
  • A shard key that forces every common query across all shards.
  • No plan for hotspots, resharding, or cross-shard queries.

Interview Q&A

Q: Your DB is at 80% disk and writes are climbing. Walk me through it.
A: First confirm what is growing (one table? logs?), then: archive/delete old data, add read replicas if it is read load, vertical scale as a bridge, and only then shard, choosing the key from the access patterns. Sharding is the last resort with the highest long-term cost.

Q: How do you generate unique IDs across shards?
A: Auto-increment breaks across machines. Options: UUIDs (no coordination, long and unordered), Twitter-Snowflake-style IDs (timestamp + machine id + sequence, 64-bit, roughly time-ordered, no coordination), or a dedicated ID service.

Key takeaways

Interview pointer

The moment you suggest sharding, also state its costs: joins and transactions get harder, so you would first reduce load with read replicas and caching. If sharding is truly needed, pick a shard key that keeps 95% of queries single-shard.