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

Range-Based Sharding

Partition data by key ranges (e.g., A-M, N-Z) for ordered data access but risk uneven load.

Range-Based Sharding

What you'll learn: How to partition database data by key ranges for ordered access and the trade-offs involved.

What is Range-Based Sharding?

Range-based sharding divides your data into shards based on continuous ranges of the shard key values. Instead of using a hash function (like in hash-based sharding), you assign specific ranges to specific shards.

For example, if your shard key is last_name:

  • Shard 1: A–M
  • Shard 2: N–Z

Or with numeric user IDs:

  • Shard 1: 1–1,000,000
  • Shard 2: 1,000,001–2,000,000
  • Shard 3: 2,000,001–3,000,000

The Key Advantage: Ordered Access

Range-based sharding preserves the natural order of your data. This makes range queries extremely efficient:

  • "Find all users with last names between Jackson and Martin" → only query Shard 1
  • "Get transactions from ID 500,000 to 750,000" → single shard lookup

The routing logic is straightforward: compare the key value against your range boundaries to determine which shard to query.

The Critical Drawback: Hotspots

The biggest risk is uneven data distribution. Real-world data rarely distributes uniformly:

  • More people have last names starting with S than X
  • User IDs grow over time, making newer shards busier
  • Certain value ranges may see more write activity

This creates hotspots where one shard handles disproportionate traffic while others sit idle—exactly what sharding tries to avoid.

Analogy

Think of organizing library books by genre. Mystery novels (range) go on shelves 1–5, Romance on 6–10. Great for browsing mysteries! But if mysteries are 70% of all books, shelves 1–5 become overcrowded while 6–10 stay empty.

Key Takeaway: Range-based sharding enables efficient range queries and maintains data order but requires careful range selection to avoid hotspots from uneven data distribution.