Full answer
Criteria:
- Query locality: if almost every request is "for tenant X", sharding by tenant keeps each request on one server.
- Even distribution: hash the key (or use many virtual buckets mapped to servers) so no shard holds a giant share. A few huge tenants may need dedicated shards.
- Growth: a timestamp key sends all inserts to the newest shard, creating a write hotspot.
- Joins: tables that are joined together should share the shard key, so their related rows sit together.
Costs:
- Queries without the shard key must fan out to every shard.
- Transactions across shards need two-phase commit or application-level compensation.
- Global unique constraints and sequences need special handling.
- Rebalancing moves data while live; mapping keys to many logical buckets makes this easier.
Before sharding, consider indexes, read replicas, partitioning, caching and a larger server, which solve most growth problems with far less complexity.
Key points
- Shard on the key most queries filter by
- Distribute evenly, often by hashing
- Avoid time-based hotspots
- Co-locate related tables
- Exhaust simpler options first
Common mistakes
- Sharding by creation date
- Sharding before simpler scaling options are tried
Follow-ups
- How would you move one tenant between shards?
- How do you generate unique ids across shards?
Tips
- Tie the choice to the main query pattern