Sharding
Splitting the data.
Replicas help with reads, but every write still goes to one leader. When Shoply has a billion orders, one machine can't hold them all, or keep up with the writes. Sharding splits the data across many databases.

- Replicas don't help writes
- A billion orders
- Split the data
Hash-based sharding
Each piece is called a shard. To decide which shard holds a row, we hash its key, and take the remainder after dividing by the number of shards. Here we place ten thousand users across four shards. Run it. Each shard gets about a quarter of the users. And every time we need Sam's data, the same formula sends us straight to the right shard.
import hashlib
def shard_for(key, shards=4):
h = int(hashlib.md5(key.encode()).hexdigest(), 16)
return h % shards
counts = [0, 0, 0, 0]
for i in range(10_000):
counts[shard_for(f"user{i}")] += 1
print("users per shard:", counts)
print("sam lives on shard", shard_for("sam"))users per shard: [2486, 2495, 2558, 2461] sam lives on shard 0
What sharding costs
Sharding gives huge scale. Each shard holds a fraction of the data, and handles a fraction of the writes. But it adds real complexity. Queries that need data from many shards are slow. Joins across shards are hard. And adding shards later means moving data around.
Benefits
- Unlimited data sizeWrites spread outSmaller, faster shards
Costs
- Cross-shard queriesHard joinsRe-sharding is painful
Summary
Sharding splits data across many databases, using a key to decide where each row lives. It scales writes, but adds complexity. Next, choosing that key well.
Key takeaways- Split by a key
- Each shard holds a part
- Complex, so delay it