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

Shard Mapping and Routing

How applications or middleware determine which shard to query for a given request based on shard key.

Shard Mapping and Routing

What you'll learn: How your application or middleware knows which database shard to query when a request comes in.


The Core Challenge

Once you've split your database across multiple shards using a shard key, you face a new problem: when a user requests data, how does your system know which shard holds that data? This is where shard mapping and routing comes in.


What Is Shard Mapping?

A shard map is essentially a directory or lookup table that tracks which shard key values live on which physical shard. Think of it like a restaurant host with a seating chart—when customers (queries) arrive, the host checks the chart to route them to the correct table (shard).

The system consults the shard map before executing any query to determine the destination shard based on the shard key in the request.


How Routing Works

When a query arrives with a shard key value (like user_id=12345), the routing logic:

  1. Extracts the shard key from the request
  2. Consults the shard map to determine which shard contains that key range
  3. Routes the query to the appropriate database shard
  4. Returns the results to the application

This can happen in your application code, a proxy layer, or specialized middleware like database routers.


Simple Example

If you're using range-based sharding where:

  • Shard A: user_id 1-10000
  • Shard B: user_id 10001-20000

A request for user_id=7500 gets routed to Shard A, while user_id=15000 goes to Shard B.


Key Takeaway: Shard mapping is the directory that tells your system where to find data, and routing is the process of directing queries to the correct shard—without this, sharding wouldn't work.