How it works
Replication makes copies; sharding gives different servers different slices of data. A sharding key decides which slice holds a record. With three shards and a user ID rule of user_id % 3, user 7 lands on shard 1, and every operation must know the user ID to route to the right place.
A key should distribute both data and traffic well. Uneven growth can exhaust one shard. A celebrity or other hot key can overload one shard even if the overall dataset is balanced. Fixes may involve moving data or splitting a hot partition.
Resharding is the next cost. Going from three shards to four under a modulo rule moves about three quarters of all users, because user_id % 3 and user_id % 4 agree for only a quarter of IDs: user 7 moves from shard 1 to shard 3. Consistent hashing, and fixed logical shards mapped onto machines, exist largely to reduce that movement.
Sharding makes cross-shard joins and transactions harder, since no single database sees all the data. Keeping some related data together or denormalizing selected read paths, which means storing duplicates shaped for a query, can help, but duplicates must be maintained when source data changes. Vitess for MySQL and Citus for Postgres handle routing, yet the key choice remains yours. So treat sharding as a late step: try indexes, read replicas, caching, a larger machine, and archiving old rows first.
Orders are sharded by customer ID. Finance now wants a daily report of revenue by product across all customers.
That report touches every shard, because no single shard holds all orders for a product. Fan the query out and merge the results, or stream orders into a separate analytics store built for such scans. Changing the key to suit one report would hurt the per-customer paths that run all day.
Use this as a guide for self review; written answers are not graded.Keep in mind
- Choose a key for access patterns as well as even data distribution.
- Sharding adds routing, rebalancing, hotspot, and query complexity.