Skip to main content

Sharding

One-line summary: Sharding splits one large dataset across many machines so a database can scale writes and storage beyond a single server's limits.


๐Ÿงฉ Core Conceptsโ€‹

Sharding (horizontal partitioning) divides a dataset into smaller pieces called shards, each stored on a separate database node. Every shard holds a subset of the rows, and together they form the whole dataset.

flowchart TD
App[Application] --> Router[Shard Router]
Router --> S1[(Shard 1<br/>users Aโ€“H)]
Router --> S2[(Shard 2<br/>users Iโ€“P)]
Router --> S3[(Shard 3<br/>users Qโ€“Z)]

Why Shard?โ€‹

  • Scale writes โ€” a single primary can only handle so many writes; sharding spreads them.
  • Scale storage โ€” data exceeds one machine's disk.
  • Reduce contention โ€” smaller working set per node, better cache locality.
  • Complements replication (which scales reads and availability) โ€” sharding scales writes.

โš ๏ธ Sharding adds real operational complexity. Exhaust vertical scaling, caching, and read replicas first.


๐Ÿงญ Sharding Strategiesโ€‹

1. Range-Based Shardingโ€‹

Assign contiguous key ranges to shards (e.g., users Aโ€“H, Iโ€“P, Qโ€“Z).

  • โœ… Simple; efficient range queries.
  • โŒ Prone to hotspots if data/traffic is skewed (e.g., everyone signs up with names starting A, or sequential timestamps hit the newest shard).

2. Hash-Based Shardingโ€‹

Compute hash(shard_key) % N to pick a shard.

  • โœ… Even distribution, avoids most hotspots.
  • โŒ Range queries become scatter-gather; % N breaks badly when N changes (mass reshuffle) โ€” solved by consistent hashing.

3. Directory-Based Shardingโ€‹

A lookup service maps each key (or key-range) to its shard.

  • โœ… Maximum flexibility; can rebalance by editing the directory.
  • โŒ The directory becomes a single point of failure and an extra hop โ€” must be replicated & cached.

4. Geo-Based Shardingโ€‹

Partition by location (e.g., EU users โ†’ EU shard).

  • โœ… Low latency for local users; helps data-residency/compliance.
  • โŒ Uneven load across regions; cross-region queries are costly.
StrategyDistributionRange QueriesRebalancingBest For
RangeCan be unevenโœ… EfficientSplit/merge rangesTime-series, ordered scans
Hashโœ… EvenโŒ Scatter-gatherHard (use consistent hashing)Uniform key access
DirectoryFlexibleDependsโœ… Easy (edit map)Dynamic / heterogeneous data
GeoBy regionLocal โœ…By regionGlobal, latency/compliance

๐Ÿ—๏ธ Shard Key Selectionโ€‹

The shard key determines which shard a row lives on โ€” the most important decision in sharding.

A good shard key has:

  • High cardinality โ€” many distinct values to spread data.
  • Even distribution โ€” no single value dominates.
  • Query alignment โ€” most queries filter by it (avoids scatter-gather).
  • Low mutability โ€” changing a row's key means moving it between shards.

โŒ Bad key: country (few values, skewed). โœ… Good key: user_id (high cardinality, evenly hashed).


๐Ÿ”ฅ Hotspotsโ€‹

A hotspot is a shard receiving disproportionate load โ€” it becomes the bottleneck while others sit idle.

flowchart LR
T[Traffic] --> H[(Hot Shard 90%)]
T --> C1[(Shard 4%)]
T --> C2[(Shard 3%)]
T --> C3[(Shard 3%)]

Causes & fixes:

  • Sequential keys (auto-increment IDs, timestamps) โ†’ use hashing or key salting.
  • Celebrity/popular records โ†’ add a cache (caching) or split the hot key.
  • Poor shard key โ†’ pick a higher-cardinality key.

โš–๏ธ Rebalancingโ€‹

As data grows or nodes are added/removed, shards must be rebalanced to keep load even.

  • Fixed number of partitions: create many more logical partitions than nodes upfront; move whole partitions between nodes (no re-hashing of keys).
  • Consistent hashing: only a fraction of keys move when a node joins/leaves.
  • Avoid hash % N for a variable N โ€” changing N remaps most keys.

๐ŸŒ€ Consistent Hashingโ€‹

Consistent hashing maps both keys and nodes onto a hash ring. A key belongs to the first node clockwise from it. Adding/removing a node only reassigns the keys in its arc โ€” roughly K/N keys move instead of nearly all.

flowchart TD
subgraph Ring [Hash Ring]
N1((Node A)) --> N2((Node B))
N2 --> N3((Node C))
N3 --> N1
end
K1[key1] -.-> N2
K2[key2] -.-> N3
K3[key3] -.-> N1
  • Virtual nodes (multiple ring positions per physical node) smooth out uneven distribution.
  • The standard technique for dynamic sharding & distributed caches. See also Hashing.

๐Ÿ”— Cross-Shard Queries & Joinsโ€‹

Once data is split, operations spanning multiple shards get hard:

  • Cross-shard joins โ€” no single node has all the data; you must scatter-gather (query every shard, merge in the app) or denormalize to keep related data co-located.
  • Cross-shard transactions โ€” require distributed transactions (2PC/Sagas), which are slow and complex.
  • Aggregations (COUNT, SUM) โ€” run per-shard then combine.
  • Unique constraints across shards can't be enforced natively.

๐Ÿ’ก Design your shard key so that the most common queries hit a single shard.


๐Ÿง  Trade-offs / When to Useโ€‹

BenefitCost
Scales writes & storage horizontallyOperational & code complexity
Smaller working set per nodeCross-shard joins/transactions are hard
Fault isolation per shardRebalancing & hotspot management overhead

Use sharding when a single node truly can't hold the data or handle the write throughput โ€” and only after simpler options are exhausted.


Interview Questionsโ€‹

  • How would you pick a shard key for a user-facing service with both read and write hotspots?
  • Explain a safe rebalancing strategy when adding new nodes to a sharded cluster.
  • How would you design to avoid cross-shard joins for the most common queries?

Production Checklistโ€‹

  • Monitor per-shard QPS, storage, and latency to detect hotspots early
  • Maintain a partition map and version it for safe rollouts
  • Automate rebalancing with low-impact migration windows and throttling
  • Ensure backups and consistent snapshots per shard
  • Test failure scenarios: node loss, network partitions, and partial rebalances

Testing & Monitoringโ€‹

  • Load test with skewed key distributions to reveal hotspots
  • Verify that rebalancing moves data without violating consistency guarantees
  • Monitor shard-level metrics and set alerts on skew, queue buildup, and retry rates
  • Run chaos tests that remove/add nodes and validate client behavior
  • Replication โ€” copies data for read-scaling & availability (pairs with sharding)
  • Databases โ€” SQL vs NoSQL and data modeling
  • Caching โ€” relieve hotspots and reduce shard load
  • CAP Theorem โ€” consistency/availability under partitions
  • Consistency Models โ€” consistency across shards
  • Scalability โ€” horizontal scaling fundamentals
  • Hashing โ€” consistent hashing internals

โ† Back to System Design ยท ยฉ sparshjaswal