AI Hints
System Design · Lesson 43 of 120

Sharding

Splitting the data.

⏱ 2 min read▶ Video at 50:33🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

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.

Sharding
From the video: Sharding
  • 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.

shards.pypython
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"))
Output
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
Next up: Choosing a Shard Key — even and useful