Video in progress
You want to shard the orders table. Which do you pick as the shard key: `user_id`, `order_id` or `created_at`?
Pick the key that most queries use — usually user_id: one user's orders sit on one shard, and queries go to one shard. created_at piles all new records onto one shard, and order_id spreads "a user's orders" across all shards.
📖 Answer
Before choosing the shard key, I write out the main queries:
- "my orders" —
WHERE user_id = ?(the most frequent); - "open an order" —
WHERE order_id = ?; - admin reports — by date.
created_at (range). All new orders land on the last shard — it overheats, while the others sit there for reads only. Splitting by time is good for archiving, but not for spreading load. This is often a fit for PostgreSQL partitioning (within a single server), not for shards.
order_id (hash). Writes spread evenly, but "my orders" now goes to every shard (scatter-gather). With 32 shards, you wait for the slowest one.
With user_id (hash), everything for a user is in one place, and transactions stay inside one shard. For lookup by order_id there's a trick: embed the shard number or part of the user_id into the order_id (Instagram did this) — the shard is determined from the ID itself.
The risk is a very large user (a B2B customer with millions of orders). Their shard gets heavier than the others. If you know about it in advance, such customers can be given a shard of their own.
Don't run admin reports across shards: bring the data into an analytical database (ClickHouse, BigQuery) through CDC and query it there.
And split into more logical pieces from the start (for example, 1024 virtual shards on 8 physical servers) — then expanding means moving pieces, not rehashing the data.
Sign up to mark studied questions and save your progress.