Today I’ll take a systematic look at another core topic in distributed systems: sharding.
In distributed systems, replication solves availability and read scaling. Once data volume or write throughput exceeds what a single machine can handle, sharding becomes practically unavoidable.
1. Why Do We Need Sharding?
The main reason we shard is scalability.
Sharding lets us:
- Spread data across multiple machines
- Split read and write load so it can be processed in parallel
- Support larger data volumes and higher throughput through horizontal scaling (scale out)
But sharding is no free lunch; it also introduces a new set of complexities.
Problems That Come with Sharding
- You need a partition key: you must use some key to quickly locate which shard holds a given piece of data
- Sharding schemes are hard to change: once live, adjustments are usually very costly
- They don’t play well with secondary indexes or relational data
- Cross-shard operations are complex and may even require distributed transactions
As a result, sharding is better suited to key-value workloads or scenarios where access is mainly by primary key.
2. Sharding in the Broad Sense: Multi-Tenant Sharding
In broad terms, sharding isn’t only for “technical horizontal scaling”; it’s also very important in multi-tenant systems.
Typical scenarios include:
- SaaS products
- Cloud services
- Enterprise platforms
In these systems, the tenant itself is a natural sharding unit.
Common Benefits of Multi-Tenant Sharding
- Resource isolation: one tenant’s heavy load won’t take down other tenants
- Permission isolation: reduces the risk of unauthorized access
- Cell-based architecture: improves fault isolation
- Per-tenant backup and restore: makes operations and incident response simpler
- Legal compliance (e.g., GDPR): supports data export and deletion
- Data residency: supports storing data in specific regions
But this approach also comes with prerequisites:
- Each tenant’s data can’t be so large that a single machine can’t handle it
- Otherwise you’re back to the problem of “sharding within a single tenant”
3. Sharding in the Narrow Sense: How to Shard Key-Value Data
The more common discussion is sharding in the narrow sense—sharding key-value data.
1️⃣ Sharding by Key Range (Range Sharding)
Define ranges directly on the original key:
- Each shard is responsible for a contiguous range
- It’s like splitting a dictionary into volumes by letter range
Pros
- Supports efficient range queries
- Data is naturally ordered within each shard
Cons
- Hotspot issues
- Keys are sequential (e.g., timestamps)
- New writes concentrate on the same shard
- Rebalancing is expensive
- When the number of shards changes, shards must be split or merged
- This triggers a large amount of data migration
2️⃣ Sharding by Key Hash (Hash Sharding)
To solve the hotspot problem with range sharding, you can hash the key first and then shard based on the hash value.
Hash sharding can distribute keys more evenly, but there’s more than one way to implement it.
Common Approaches
(1) Hash Modulo the Number of Nodes
node = hash(key) % N
- Simple to implement
- But changing the number of nodes causes almost all data to be redistributed
- Rebalancing is extremely expensive, so it’s not recommended in practice
(2) A Fixed Number of Shards
- Pre-create a large number of shards (e.g., 1000)
hash(key) % shard_count- Then map the shards to nodes
Pros
- When nodes are added or removed, only shards move; keys aren’t rehashed
- Rebalancing cost is manageable
Cons
- Once the shard count is fixed, it’s hard to adjust
- Shards that are too large or too small both cause problems
(3) Sharding by Hash Range
- Each shard covers a contiguous range of hash values
- Shards can be split or merged dynamically
- This adapts better when data volume changes
(4) Consistent Hashing
- Abstract the hash space as a ring
- A key maps to the first node encountered clockwise
- When nodes change, only a small number of keys are affected
Consistent hashing is very common in caching systems and KV stores; in essence, it’s a kind of “implicit sharding.”
4. Hotspots and Skew: Hashing Doesn’t Solve Everything
Even with hash sharding, you can’t avoid hotspots at the business level.
Typical Scenarios
- Viral posts on social media
- Celebrity accounts
- Products that go viral
In these cases:
- A single key gets an extremely high volume of access
- That key is called a hot key
Common Ways to Handle It
- Spread requests at the application layer
- Add random numbers before or after the key
- Distribute writes across multiple logical keys
- Give hot keys their own shard
- Put a single hot key in its own shard
- Even assign it a dedicated machine
These approaches are usually engineering compromises that require extra read merging and operational overhead.
5. Rebalancing: Automatic or Manual?
Any sharded system has to deal with rebalancing.
- Rebalancing is an expensive operation
- It involves moving a large amount of data
- It can significantly affect system performance
Automatic vs. Manual
- Fully automatic
- Low operational overhead
- But behavior is unpredictable
- Can easily trigger cascading failures
- Manual intervention
- Slower to operate
- But safer and more controllable
In many production systems:
Having human control during rebalancing can actually be an advantage
6. Request Routing: How Do You Find the Right Shard?
Going from “request a piece of data” to “find the node that hosts the corresponding shard” still requires solving request routing.
Three Common Approaches
- Client connects to any node
- The node forwards the request itself
- Introduce a separate routing layer
- Dedicated to shard awareness and forwarding
- Client is aware of the shard topology
- Accesses the target node directly
Challenges
- Who decides which node a shard lives on?
- Is the routing layer a single point of failure?
- How do you ensure requests are routed correctly while shards are migrating?
Common Solutions
- Coordination services
- ZooKeeper, etcd
- Based on consensus protocols to prevent split brain
- Gossip protocols
- Used in leaderless systems
- Provide weak consistency guarantees (e.g., Cassandra)
7. Sharding and Secondary Indexes
Sharding usually relies on a primary key / partition key, but many business scenarios require querying by non-primary-key fields.
For example:
Find all “red” cars
This involves secondary indexes, and secondary indexes are a hard problem in sharded systems.
1️⃣ Local Secondary Indexes
- Each shard maintains an index over its own data
- Writes are simple
- Queries require scatter/gather
Problems
- You have to query every shard
- This easily amplifies tail latency
2️⃣ Global Secondary Indexes
- The index itself is also sharded
- Each index shard maintains a list of IDs for a certain class of values
Trade-offs
- Reads are more efficient
- Writes are more complex
- You may need distributed transactions or have to accept eventual consistency
Summary
Sharding is a core technique for achieving scalability in distributed systems, but the complexity it introduces goes far beyond simply “splitting up the data.”
- Choose the wrong sharding scheme, and the long-term cost can be extremely high
- There’s no silver bullet—only trade-offs
- Sharding design is fundamentally modeling how the business accesses its data
Understanding sharding isn’t just about understanding an algorithm. It’s about understanding:
the long-term interplay among data, load, evolution, and operations