Skip to main content
14

Sharding and consistent hashing

HardDatabasesShardingScaling

What is sharding, how do you choose a shard key, and what problem does consistent hashing solve?

TL;DR

Sharding splits one dataset across several databases (shards), each holding a subset of rows, so you can scale writes and storage beyond one machine. The shard key decides where each row lives; a good one spreads load evenly and keeps most queries on a single shard. With naive hash(key) % N, adding a shard remaps almost every key. Consistent hashing places shards and keys on a hash ring, so adding or removing a shard only moves about 1/N of the keys.

Key points

  • Range sharding (by ID range or date): easy range scans, but risks hot spots (all new writes land on the last shard).
  • Hash sharding: even distribution, but range queries hit every shard.
  • Directory or lookup sharding: a mapping table decides placement; flexible but one more component.
  • Good shard keys: tenant_id for B2B SaaS, user_id for consumer apps. Bad ones: low cardinality (country), or monotonic values with range sharding.
  • Costs: cross-shard joins and transactions become hard, global unique constraints are gone, rebalancing is operational work, and hot keys (a celebrity user) can still overload one shard.
  • Consistent hashing uses virtual nodes: each server owns many points on the ring, which smooths the distribution.
  • Try first: indexes, caching, read replicas and vertical scaling. Shard only when needed.

Example

text
hash(key) % 4 → % 5      ~80% of keys move
consistent hashing, 4 → 5 nodes   ~20% of keys move (only to the new node)

Common follow-ups

  • How do you query across shards? Scatter-gather (query all shards and merge), which is slow, so design the key to avoid it. Or keep a separate search or analytics store.
  • Who uses consistent hashing? Cassandra, DynamoDB, distributed caches and load balancers.

What interviewers look for

Tip

Shard-key reasoning tied to real queries, the trade-offs (cross-shard queries, hot keys, rebalancing), and why consistent hashing beats modulo.

  • Red flag: sharding as the first answer to any scaling question.

Was this helpful?

Related questions