← Back to SQL, page 18

sql-0353 · Hard senior

How would you choose a shard key when splitting a large database across several servers?

Pick a key that most queries filter on, so each request touches one shard, and that spreads data and load evenly, such as tenant_id or user_id. Avoid keys with hot values or time-based keys that send all new writes to one shard. Cross-shard queries, transactions and re-sharding become harder, so shard only when simpler options are exhausted.

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