Course contentsShow
← System Design
Lesson 245 of 1,9197. Database Scaling: ShardingFree lesson

Composite Shard Keys

Combine multiple attributes in the shard key to achieve better distribution or locality for complex workloads.

Composite Shard Keys

What you'll learn: How to combine multiple attributes into a single shard key for smarter data distribution across database shards.


What Is a Composite Shard Key?

A composite shard key uses multiple columns or attributes together to determine which shard holds your data, rather than relying on just one field. For example, instead of sharding solely by user_id, you might shard by (country, user_id) or (tenant_id, timestamp).

This gives you finer-grained control over data distribution and lets you optimize for both even load balancing and data locality.


Why Use Multiple Attributes?

Sometimes a single attribute creates problems:

  • Better distribution: A simple user_id hash might still produce hotspots if some users generate far more data than others. Adding timestamp or category can spread that load.
  • Query locality: Queries often filter by multiple dimensions. Sharding by (tenant_id, date) keeps all data for "Tenant A on March 15th" on one shard, making range queries fast.
  • Avoiding hotspots: If sharding by timestamp alone, recent data gets hammered. Combining with user_id spreads recent writes across shards.

Example Scenarios

  • Multi-tenant app: Shard key = (tenant_id, user_id) → keeps tenant data together while balancing users within.
  • Time-series logs: Shard key = (device_id, timestamp) → groups device logs together, spreads load across devices.
  • E-commerce orders: Shard key = (region, order_id) → enables regional queries, avoids global scans.

Trade-Offs

The more attributes you combine, the more complex your routing logic becomes. You must hash or encode the composite key carefully, and some query patterns may still require hitting multiple shards if they don't include all key components.

Key Takeaway: Composite shard keys combine multiple attributes to achieve better load distribution and query locality, especially in complex workloads with multiple access patterns.