Sharding Algorithms and Routing Strategies
13 min read
Prerequisites: Understanding of single-node database indexing, horizontal scaling fundamentals, and the concept of a shard key.
The Routing Dilemma: Where Did I Put That Row?
Imagine you run an e-commerce platform. When your database outgrows a single machine, you split your 100-million-row orders table across 16 database servers (shards).
Now a customer attempts to fetch order #984123.
Your application server freezes. Which of the 16 databases actually holds that row?
Without a deterministic routing strategy, you have only one agonizing option: broadcast (or scatter-gather). You query all 16 shards in parallel, wait for 15 to say "Not here!", grab the row from the 16th, and assemble the result.
+--> [Shard 0] -> "Not here"
|
Client ---> [Scatter-Gather] ----+--> [Shard 1] -> "Not here"
(Queries all 16) |
+--> [Shard 8] -> "Found it!" (Row #984123)At 50,000 requests per second, broadcasting will incinerate your network throughput, exhaust connection pools, and drive tail latency () into the stratosphere.
Sharding algorithms and routing layers exist to turn this distributed hunt into an instantaneous direct lookup.
1. Hash-Based and Modulo Sharding Implementations
The Definition and Problem
Hash-based sharding applies a deterministic hashing algorithm to a record’s shard key and maps the output to a specific shard. It was invented to solve the nemesis of distributed systems: data skew and hot-spotting.
If your customers are creating accounts sequentially, you do not want all new writes pounding the same server. Hash functions introduce pseudo-randomness, spreading keys uniformly across storage partitions.
The Mechanism: Modulo Arithmetic
The simplest implementation computes a hash of the partition key and takes the modulo of the total number of shards ():
Key: "user_49102"
│
▼
[MurmurHash3 / xxHash64] ──> 0x8F2D19B4 (2,402,081,204)
│
▼
2,402,081,204 % 4 (shards)
│
▼
Shard 0Choosing the Right Hash Function
Do not use cryptographic hash functions like SHA-256 or bcrypt for routing. Cryptographic hashes prioritize collision resistance against malicious adversaries at the cost of high CPU cycle consumption.
For sharding routers, prioritize speed and uniform distribution:
- xxHash (XXH3): Ridiculously fast (runs at RAM speeds, ~30 GB/s per core).
- MurmurHash3: The historical standard used in systems like Apache Cassandra.
Hands-On Implementation: Python Modulo Router
Here is an industry-grade, stateless modulo router using mmh3 (MurmurHash3):
import mmh3
class ModuloShardRouter:
def __init__(self, shard_count: int):
if shard_count <= 0:
raise ValueError("Shard count must be greater than 0")
self.shard_count = shard_count
def get_shard(self, shard_key: str) -> int:
# mmh3.hash returns a signed 32-bit int (-2^31 to 2^31 - 1)
# Convert to an unsigned 32-bit integer before applying modulo
unsigned_hash = mmh3.hash(shard_key) & 0xFFFFFFFF
return unsigned_hash % self.shard_count
# Setup a cluster of 4 shards
router = ModuloShardRouter(shard_count=4)
sample_keys = ["usr_alpha", "usr_beta", "usr_gamma", "usr_delta", "usr_epsilon"]
for key in sample_keys:
print(f"Key: {key:<12} -> Assigned Shard: {router.get_shard(key)}")Output:
Key: usr_alpha -> Assigned Shard: 1
Key: usr_beta -> Assigned Shard: 3
Key: usr_gamma -> Assigned Shard: 0
Key: usr_delta -> Assigned Shard: 2
Key: usr_epsilon -> Assigned Shard: 1Boundaries and Limitations: The Re-sharding Cliff
What is possible:
- Stateless routing: The router requires zero shared state. It can be embedded as a library directly inside your application process.
- Uniform distribution: Random distributions eradicate write hot-spots.
What is NOT possible:
Dynamic scaling without massive data reshuffling:
If you scale from to shards, the divisor in your modulo operation changes.When changing from to , roughly (often 80% to 90%) of all your existing database records must be physically moved between disks.
Efficient range scans: If you run
SELECT * FROM orders WHERE created_at BETWEEN '2026-01-01' AND '2026-01-31', rows matching this query are scattered across every single shard. Range scans always degrade to scatter-gather.
2. Range-Based and Directory-Based Lookup Routing
When modulo sharding fails to meet requirements (e.g., you need fast range scans or tenant isolation), engineers rely on Range-Based or Directory-Based routing.
+-------------------------------------------------------------------------+
| ROUTING STRATEGIES |
+------------------------------------+------------------------------------+
| RANGE-BASED | DIRECTORY-BASED |
+------------------------------------+------------------------------------+
| Shard 0: [00000 - 25000] | Shard 0: Tenant "AcmeCorp" |
| Shard 1: [25001 - 50000] | Shard 1: Tenant "Hooli", "Initech" |
| Shard 2: [50001 - 75000] | Shard 2: Tenant "StarkIndustries" |
| Shard 3: [75001 - 99999] | Lookup Table: ID -> Shard Map |
+------------------------------------+------------------------------------+Strategy A: Range-Based Routing
Definition
Data is partitioned into contiguous, ordered intervals based on the shard key (e.g., timestamps, alphabetical names, or auto-incrementing integers).
Where it Shines
- Range queries stay local: Running
WHERE id >= 1000 AND id <= 1500routes directly to a single shard. No scatter-gather required. - Data lifecycle management: Dropping old data (e.g., delete data older than 2 years) is as simple as dropping an entire shard/table partition.
The Catastrophic Hotspot Failure
If you choose an auto-incrementing ID or a timestamp (created_at) as your range key:
- Shard 1 holds Day 1.
- Shard 2 holds Day 2.
- Shard 3 holds Day 3 (Today).
Result: 100% of your application's write traffic hits Shard 3. Shards 1 and 2 sit idle at 0.1% CPU utilization, while Shard 3 catches fire.
Rule of Thumb: Never shard by range on monotonically increasing keys unless you specifically implement write buffers or synthetic prefix salts.
Strategy B: Directory-Based Lookup Routing
Definition
Instead of calculating where data goes using a formula, the system queries a central Lookup Service (or state catalog) containing a dynamic mapping table:
+-------------------------+
| Lookup Service / DB |
| (e.g., Redis / Spanner) |
+-------------------------+
▲ │
1. Query Shard Location │ │ 2. Return Shard 3
│ ▼
Client ────────────────────────> [Router] ───────────────────────> [Shard 3]
3. Send Query DirectlyReal-World Implementation Pattern
Directory-based routing is common in B2B Multi-Tenant SaaS systems:
-- Central Routing Table (Stored in a fast replicated store like Redis/etcd/Postgres)
CREATE TABLE tenant_directory (
tenant_id VARCHAR(64) PRIMARY KEY,
shard_id INT NOT NULL,
status VARCHAR(16) DEFAULT 'ACTIVE',
migrating_to_shard INT NULL
);Boundaries and Scope:
- The Good: Complete operational control. If tenant
"Enterprise-Client-X"starts using 10,000x more storage than everyone else, you can update one row in your directory, migrate their data, and assign them to their own dedicated physical shard without disturbing other tenants. - The Bad: The directory introduces an extra network round-trip ( query problem) on every read and write. If your directory crashes, your entire database infrastructure goes dark.
- The Mitigation: Cache the directory heavily inside your application servers using TTLs or cache invalidation via Redis Pub/Sub / Kafka events.
3. Consistent Hashing and Virtual Nodes
The Problem
Modulo sharding breaks when shard counts change because the divisor shifts. What if we could add or remove database nodes while requiring only items to be moved (where is total keys and is total shards)?
Enter Consistent Hashing, introduced in 1997 by David Karger et al. at MIT.
The Mechanism: The Hash Ring
Instead of mapping keys to indices , consistent hashing maps both nodes and data keys to the same continuous circular space: the Hash Ring.
- Imagine a ring bounded from to (or ).
- Hash your shard connection strings (e.g.,
Shard-A,Shard-B,Shard-C) to place them onto points along the ring perimeter. - When writing a record with key , hash to get an address on the ring.
- Walk clockwise along the ring until you encounter the first database node. That node owns the key.
0 / 2^32
. - - - .
' '
' '
* [Shard A] * [Key 1]
' '
' '
' '
[Key 3] * * [Shard B]
' '
' '
' '
* [Shard C] * [Key 2]
' '
' '
' - - - 'Key 1walks clockwise owned by Shard B.Key 2walks clockwise owned by Shard C.Key 3walks clockwise owned by Shard A.
If Shard B fails, only the keys between Shard A and Shard B move to Shard C. The keys owned by Shard A are untouched!
The Virtual Node (VNode) Solution
The Flaw of the Naive Ring
With only 3 physical shards, random hashing will not distribute nodes evenly around the circle. One node might end up owning 70% of the ring circumference, resulting in an extreme data imbalance.
The Fix: VNodes
Instead of placing each physical server on the ring once, assign each physical server 100 to 256 virtual locations (VNodes) using labeled hashes:
Shard-A#0,Shard-A#1,Shard-A#2, ...,Shard-A#199Shard-B#0,Shard-B#1,Shard-B#2, ...,Shard-B#199
VNodes interleave the physical nodes across the ring, evening out variance and delivering near-perfect uniform distribution across all storage servers.
Hands-On Implementation: Consistent Hash Ring with VNodes
import bisect
import mmh3
class ConsistentHashRing:
def __init__(self, replicas: int = 100):
self.replicas = replicas # Virtual nodes per physical shard
self.ring = [] # Sorted list of hash values
self.vnode_map = {} # Hash -> Physical Shard Name
def _hash(self, key: str) -> int:
return mmh3.hash(key) & 0xFFFFFFFF
def add_shard(self, shard: str):
"""Add a physical shard with multiple virtual nodes."""
for i in range(self.replicas):
vnode_key = f"{shard}#vnode_{i}"
vnode_hash = self._hash(vnode_key)
bisect.insort(self.ring, vnode_hash)
self.vnode_map[vnode_hash] = shard
def remove_shard(self, shard: str):
"""Remove a physical shard and clean up its virtual nodes."""
for i in range(self.replicas):
vnode_key = f"{shard}#vnode_{i}"
vnode_hash = self._hash(vnode_key)
index = bisect.bisect_left(self.ring, vnode_hash)
if index < len(self.ring) and self.ring[index] == vnode_hash:
del self.ring[index]
del self.vnode_map[vnode_hash]
def get_shard(self, shard_key: str) -> str:
"""Find the corresponding shard for a key in O(log N) time."""
if not self.ring:
raise RuntimeError("Ring is empty. Add shards first.")
key_hash = self._hash(shard_key)
# Binary search for the first node clockwise (>= key_hash)
idx = bisect.bisect_right(self.ring, key_hash)
# If we reached the end of the ring, wrap around to the first node (index 0)
if idx == len(self.ring):
idx = 0
return self.vnode_map[self.ring[idx]]
# Simulation
ring = ConsistentHashRing(replicas=150)
ring.add_shard("db-prod-shard-01")
ring.add_shard("db-prod-shard-02")
ring.add_shard("db-prod-shard-03")
test_user = "user_account_9012"
print(f"Target: {ring.get_shard(test_user)}")
# Scale up cluster dynamically
ring.add_shard("db-prod-shard-04")
print(f"Target after scaling: {ring.get_shard(test_user)}")4. Routing Layer Architectures: Vitess, Citus, ProxySQL
Routing logic must live somewhere in your architecture. You have three primary architectural choices:
WHERE DOES ROUTING LIVE?
1. Middleware Proxy 2. Engine Extension / Coordinator
(e.g., Vitess VTGate) (e.g., Citus Coordinator)
[ App Server ] [ App Server ]
│ │
▼ ▼
[ VTGate Proxy ] [ Citus Coordinator ]
│ │ │ (Postgres Core) │
▼ ▼ ▼ ▼
[VTTablet] [VTTablet] [Shard Worker] [Shard Worker]
[MySQL Shard] [MySQL Shard]Architectural Comparison Matrix
| Technology | Architecture Type | Native DB Engine | Best Suited For | Query Planning Mechanism |
|---|---|---|---|---|
| Vitess | Distributed Proxy / Sidecar | MySQL | Massive OLTP (Hyperscale, YouTube scale) | Abstracted via VSchema & VTGate routers |
| Citus | DB Engine Extension | PostgreSQL | Mixed OLTP & Analytical HTAP | Plugs into Postgres Planner Hooks |
| ProxySQL | Layer-7 Reverse Proxy | MySQL / MariaDB | Read/Write splitting, query caching, rule-based routing | Regex match + MySQL user/schema rules |
Deep-Dive A: Vitess (VTGate & VTTablet)
Created by YouTube to scale MySQL horizontally, Vitess completely decouples application code from physical database topology.
- VTGate: A stateless proxy cluster. Your applications connect to VTGate via standard MySQL protocol drivers. VTGate inspects incoming SQL, resolves shard keys using a declarative JSON mapping file called VSchema, queries the target shards, and stitches the results back together.
- VTTablet: A sidecar process running on every MySQL shard host that acts as a gatekeeper, monitoring memory, pooling connections, and killing rogue queries before they crash the MySQL daemon.
Example VSchema Definition:
{
"sharded": true,
"vindexes": {
"hash_index": {
"type": "hash"
}
},
"tables": {
"users": {
"column_vindexes": [
{
"column": "user_id",
"name": "hash_index"
}
]
}
}
}Vitess reads this VSchema, runs internal consistent hashing on user_id, and routes mutations without requiring application code to know about the underlying database topology.
Deep-Dive B: Citus (Native PostgreSQL Distributed Extension)
Citus transforms standard PostgreSQL into a distributed database engine. Unlike Vitess (which lives as an external proxy cluster), Citus embeds directly into PostgreSQL via its open C-extension APIs.
- You connect to a Coordinator Node (or across any node using Citus MX).
- Citus intercepts query plans at the Postgres parser level and rewrites them into distributed execution fragments dispatched to remote Worker Nodes.
Initializing a Distributed Table in Citus:
-- Connect to Postgres with Citus extension loaded
CREATE EXTENSION citus;
-- Create standard relational table
CREATE TABLE orders (
order_id BIGINT,
tenant_id INT,
total_amount NUMERIC(12, 2),
ordered_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
PRIMARY KEY (tenant_id, order_id)
);
-- Distribute table across workers using tenant_id as the hash shard key
SELECT create_distributed_table('orders', 'tenant_id');Deep-Dive C: ProxySQL (Rule-Based L7 Proxy)
ProxySQL doesn't break tables into fragments like Citus or Vitess. Instead, it inspects queries on the wire using regular expressions and directs traffic across hostgroups (e.g., routing writes to primaries and reads to replicas, or routing by database schema).
Setting Up Query Rules in ProxySQL:
-- Send write operations (INSERT, UPDATE, DELETE, FOR UPDATE) to Hostgroup 0 (Primaries)
INSERT INTO mysql_query_rules (rule_id, active, match_pattern, destination_hostgroup, apply)
VALUES (1, 1, '^SELECT .* FOR UPDATE', 0, 1);
-- Route standard SELECT queries to Hostgroup 1 (Read Replica Cluster)
INSERT INTO mysql_query_rules (rule_id, active, match_pattern, destination_hostgroup, apply)
VALUES (2, 1, '^SELECT .*', 1, 1);
-- Load the rules to runtime memory and persist to disk
LOAD MYSQL QUERY RULES TO RUNTIME;
SAVE MYSQL QUERY RULES TO DISK;Hard Architectural Boundaries: What Sharding Can and Cannot Solve
When implementing sharding algorithms and routing strategies, you hit concrete engineering boundaries imposed by the laws of distributed systems:
+---------------------------------------------------------------------------------------+
| THE BOUNDARY WALL |
+---------------------------------------------------+-----------------------------------+
| WHAT IS POSSIBLE | WHAT IS IMPOSSIBLE / HARD |
+---------------------------------------------------+-----------------------------------+
| Linear horizontal write throughput scaling | Cross-shard ACID transactions |
| Sub-millisecond single-shard lookups ($O(1)$) | Cross-shard distributed joins |
| Zero application code changes (via smart proxies) | Global unique foreign key checks |
+---------------------------------------------------+-----------------------------------+Why Do These Boundaries Exist?
Cross-Shard Foreign Keys Are Impossible:
If tableorderssits on Shard 1 and references tableuserson Shard 2, the storage engine cannot enforce referential integrity locally. Enforcing it across shards requires cross-node distributed locking, which degrades write latencies exponentially.- The Reality: Foreign keys across shards must be removed from the database schema and enforced inside your application service layer.
Cross-Shard Transactions Require Two-Phase Commit (2PC):
If a single transaction writes to Shard A and Shard B, you must coordinate them using protocols like Two-Phase Commit (2PC). If the coordinator node crashes during the commit phase, database locks are held open indefinitely, stalling downstream writes.- The Reality: Most high-throughput sharded deployments prohibit cross-shard transactions outright, requiring operations to be idempotent and asynchronously unified using transactional outbox patterns and event queues.
Global Secondary Indexes Require Dedicated Infrastructure:
If you shardusersbyuser_id, searching byemailwill trigger an all-shard scatter-gather scan.- The Reality: You must either maintain a secondary lookup directory, duplicate the data across shards (fan-out writes), or sync data to a distributed search engine like Elasticsearch/OpenSearch.
Further Reading and Official Documentation
- Vitess Documentation: VSchema Concepts & VTGate Architecture
- Citus Data: Distributed Data Modeling Reference
- ProxySQL Official Docs: Query Routing and Hostgroups
- Karger et al. (MIT): Consistent Hashing and Random Trees (1997 Paper)
- xxHash Specification: Extreme High-Speed Non-Cryptographic Hashing Algorithm
Challenge
Sharding & Routing Layers — Recall Check
You've just reviewed how different sharding algorithms and routing layers trade off uniformity, locality, and operational flexibility. This challenge asks you to recall the specific mechanisms, parameters, and failure modes from that material.
Instructions
- Fill in every blank line in the editor. Each blank should be a short, precise answer — a named technique, a parameter, a direction, or a one-line justification.
- Do not write essays. One or two lines per blank is enough.
- You may add a short note under any blank if you want to justify the choice.
- Do not delete the question text; write your answer directly under each prompt on the blank line provided.
Focus areas
- Hashing choice and routing complexity
- Resharding behaviour of modulo routing
- Write hotspots in range routing
- Operational cost of directory routing
- Key movement and virtual nodes in consistent hashing
- Picking a proxy/extension for a real deployment
- Designing around cross-shard constraints
Answer checking is done by an LLM against the summary — be specific and use the correct terminology.
Expected result
Answers are evaluated holistically by an LLM. A complete response must:
- Fill every blank with a specific, technically accurate term, parameter, or mechanism — not vague phrases like "it is faster" or "use a good hash".
- Use correct sharding/routing vocabulary (e.g. scatter-gather, shard key, hash ring, virtual node, coordinator, hostgroup, 2PC, idempotent workflow).
- State a trade-off or reason wherever the question asks "why" — one clause is sufficient.
- Where a number, range, or default is requested, give a concrete value rather than "many" or "a few".
- Where a tool is requested, name a specific product and connect it to the routing style it actually implements.
- Where a scenario is given, name the routing strategy that best fits and justify it in a single line.
Deductions apply for: blanks left empty, answers that describe a different routing strategy than the one asked about, and answers that omit the operational consequence (latency, migration cost, coordination cost, hotspot risk).