15. Sharding
Practice: five levels
Assignments
Five levels. Do them in order. Answers are in "Solutions" at the end, so try first.
Level 1: Think (no code)
A. Good or bad shard key? Why?
countryfor a global app's users.user_id(hashed) for orders.created_at(range) for a busy events table.tenant_idfor a business app with 5,000 small customers and 3 huge ones.order_statusfor orders.
B. One shard or every shard? (Orders sharded by user_id.)
- "Show user 7's last 10 orders."
- "How many orders were placed today?"
- "Find order 9,102,334." (Order IDs don't contain the shard.)
- "Update user 7's cart."
Level 2: Calculate
- 2 billion orders at 1 KB each. Each shard should stay near 250 GB. How many shards? With a leader and 2 replicas each, how many database servers?
- At 20,000 writes a second spread evenly, how many per shard? If one shard gets 40% of the traffic instead, how many writes a second does it take?
- You grow from 4 to 5 servers. Roughly what fraction of keys move with
hash mod N? With 1,024 logical shards? - A dashboard query fans out to 16 shards. Each is slow 1% of the time. What fraction of dashboard loads are slow?
Level 3: Build
In Python, write:
RangeRouter(bounds, shards),HashRouter(shards)andDirectoryRouter(), each withshard_for(key).LogicalShardRouter(n_logical, servers)withadd_server(new)that moves whole logical shards.scatter_gather(shards_data, predicate).
Check that: range lookups land in the right shard; hashing 100,000 users over 4 shards gives roughly equal counts; growing 4 → 5 moves about 80% of keys with mod N and about 20% with 1,024 logical shards; a directory can pin a big tenant to its own shard; scatter-gather counts across all shards correctly.
Level 4: Debug
The team sharded orders by order date, in ranges, so "orders by month" reports would be fast. At the Book Fest, the database on one shard hits 100% CPU while the other three are nearly idle, and checkout slows to a crawl.
- Find the bug. Explain why one shard is hot.
- Fix it, and say what happens to the monthly reports.
Level 5: Design
The bookstore has 2 billion orders, 20,000 writes a second at sale peaks, users in India and Europe, an admin "orders by book" page, and nightly sales reports.
Deliver:
- The shard key and strategy, with reasons.
- How you handle "orders by book" and the nightly reports.
- How order IDs and the unique email rule work.
- How you add shards next year.
- The replication layout per shard.
- One transaction that crosses shards, and how you handle it.