Foundations of Database Sharding
13 min read
Database Sharding and Optimisation Concepts
Chapter 3: Foundations of Database Sharding 🧩
Welcome to Chapter 3! If you are here, congratulations: your application is either wildly successful, or someone on your team designed a schema that inserts 40,000 telemetry events per second into an unindexed table. Either way, your single database instance is sweating, your CPU graphs look like a flat line at 100%, and the cloud provider's biggest instance tier is beginning to look terrifyingly expensive.
Before you split your database into a dozen pieces, let's understand the foundations of sharding, the architectural tradeoffs you will make, and the non-negotiable boundaries you must respect.
0. The Boundary: What Sharding Can and CANNOT Do 🛑
Engineers often view sharding as a magic wand: "We will just shard by user ID and scale to infinity!"
Before touching any code, you need to understand the physical and theoretical boundaries of sharding.
+------------------------------------------+------------------------------------------+
| WHAT SHARDING CAN DO | WHAT SHARDING CANNOT DO |
+------------------------------------------+------------------------------------------+
| Scale write throughput horizontally | Fix unindexed, slow, or poorly-written |
| across multiple distinct disks/CPUs | SQL queries |
+------------------------------------------+------------------------------------------+
| Bypass physical storage limits of a | Provide cheap, millisecond-latency joins |
| single physical server / cloud volume | across multiple shards |
+------------------------------------------+------------------------------------------+
| Limit the blast radius of hardware | Eliminate operational complexity; you |
| failure to a subset of your users | now manage N databases instead of 1 |
+------------------------------------------+------------------------------------------+
| Provide geographic locality for data | Guarantee trivial, zero-overhead ACID |
| (data residency / compliance) | distributed transactions |
+------------------------------------------+------------------------------------------+Why do these boundaries exist?
- The Speed of Light and Network Latency: In a monolithic database, an index lookup and a join happen in local memory (RAM) or local NVMe storage with nanosecond or microsecond access times. In a sharded system, an un-sharded cross-node join requires network round-trips ( minimum within the same datacenter). If you do 50 nested lookups over the wire, your query goes from 2 milliseconds to 100+ milliseconds.
- The Cost of Distributed Consensus (CAP & PACELC): Multi-shard transactions require Two-Phase Commit (2PC) or distributed consensus protocols (like Paxos or Raft). 2PC requires nodes to hold row locks while waiting for coordinator confirmation across the network. If a shard fails or lags, locks stay open, queues back up, and your throughput plummets.
Rule #1 of Sharding: The first rule of sharding is to exhaust every other scaling method first. Add indexes, optimize queries, introduce Redis caching, implement read replicas, upgrade your instance size (vertical scaling), and prune dead data. Shard only when you hit write-throughput or physical storage walls.
Subtopic 1: Horizontal vs Vertical Sharding: Tradeoffs and Triggers ⚖️
1.1 The Definition & The Problem
When your database grows too large for one machine, you have two choices for breaking apart your schema: Vertical Partitioning/Sharding or Horizontal Sharding.
Original Monolith Table:
[ User ID | Name | Email | PasswordHash | ProfileBio | OrderHistory | BillingInfo ]
VERTICAL SHARDING (Split by Column/Domain):
Node A (Auth DB): [ User ID | Email | PasswordHash ]
Node B (Profile DB): [ User ID | Name | ProfileBio ]
Node C (Billing DB): [ User ID | BillingInfo | OrderHistory ]
HORIZONTAL SHARDING (Split by Rows):
Shard 1 (Users 1-1,000,000): [ User ID | Name | Email | ... ]
Shard 2 (Users 1,000,001-2,000,000): [ User ID | Name | Email | ... ]Vertical Sharding (Functional Decomposition)
- What it is: Separating tables or column clusters by business domain or access frequency onto separate database instances. For example, moving
ordersto Database A,usersto Database B, andanalytics_eventsto Database C. - When to use it: When your domain models naturally decouple (often aligning with a transition toward service-oriented or microservice architectures).
- The Tradeoff: You completely lose foreign key constraints and
JOINcapabilities between decoupled tables at the database level. These must now be orchestrated at the application layer.
Horizontal Sharding (Data Partitioning)
- What it is: Splitting rows of the same schema across multiple database nodes. Each node (a "shard") has the exact same tables, columns, and indexes, but holds a completely distinct subset of the rows.
- When to use it: When a single table or entity group (e.g.,
orders,messages,telemetry) exceeds the storage, IOPS, or write capacity of the largest hardware available.
1.2 Comparison Matrix
| Factor | Vertical Sharding | Horizontal Sharding |
|---|---|---|
| Schema Similarity | Different schemas per node | Identical schemas across all nodes |
| Query Complexity | Moderate (queries within a domain stay untouched) | High (queries must include the shard key to avoid broadcasting) |
| Scaling Limit | Finite: You eventually run out of tables to separate | Near-linear: You can continue adding shards as rows increase |
| Operational Toll | Lower initial impact | High (requires resharding logic, rebalancing, split backups) |
1.3 The Real-World Triggers: When Do You Pull the Trigger?
Do not shard because you have 50 million rows. Modern relational databases (PostgreSQL, MySQL) handle hundreds of millions of rows easily if indexed properly.
Pull the trigger only when you encounter these specific constraints:
- Sustained Write IOPS Saturation: Your primary writer database instance is hitting sustained 85-90% disk IOPS or CPU write bottlenecks, and read-replicas cannot help (because replicas also must execute all writes).
- Replication Lag Cascades: Replicas fall behind because replaying the write stream on a single thread/process cannot keep up with traffic.
- Backup and Restore (RTO/RPO) Violations: A physical backup (
pg_dumpor snapshot) takes 18 hours, and a test restore takes 36 hours. If your disaster recovery SLA is 4 hours, your database is physically too large to operate safely as a single unit. - Hardware Ceilings: You are on an AWS
r6i.32xlarge(128 vCPUs, 1 TiB RAM) or bare-metal equivalent, and writes still exceed capacity.
Subtopic 2: Selecting Shard Keys: Avoiding Hotspots and Data Skew 🔑
2.1 The Definition & The Problem
A Shard Key is one or more columns in your table that determine which physical shard a given row will live on.
Choosing a shard key is a one-way door decision. Changing a shard key on a multi-terabyte production database requires creating a new cluster, backfilling data, synchronizing live writes, and cutting over with minimal downtime—a project that can take months.
Choose the wrong key, and you encounter two database killers:
- Data Skew: Shard 1 holds 85% of your data while Shards 2, 3, and 4 sit completely idle.
- Hotspots (Traffic Skew): All writes or reads pound a single shard simultaneously, causing that node to crash while the remaining cluster is at 2% CPU.
2.2 Sharding Strategies: Range, Hash, and Entity
Strategy 1: Range-Based (e.g., Shard Key: created_at or id)
[0000 - 1000] ---> Shard 1
[1001 - 2000] ---> Shard 2
[2001 - 3000] ---> Shard 3 <--- 🔥 ALL CURRENT WRITES LAND HERE (HOTSPOT!)
Strategy 2: Hash-Based (e.g., Shard Key: hash(user_id) % num_shards)
user_101 (Hash: 0x4F) ---> Shard 1
user_102 (Hash: 0x1A) ---> Shard 3
user_103 (Hash: 0x8C) ---> Shard 2 <--- ⚖️ EVENLY DISTRIBUTED WRITES1. Range-Based Sharding
- How it works: Data is divided into ranges (e.g., IDs 1 to 100,000 go to Shard 1; 100,001 to 200,000 go to Shard 2; or by date ranges).
- The Trap: If you shard by an auto-incrementing ID or timestamp, 100% of all current inserts hit the newest shard. You defeat the entire purpose of sharding by creating a moving write hotspot.
- When it works: Read-heavy historical datasets where range queries are frequent (e.g., fetching all events from
2024-01-01to2024-01-31from an archive partition).
2. Hash-Based Sharding
- How it works: Pass the shard key into a deterministic hash function (e.g., Murmur3, MD5) and calculate modulo or locate on a consistent hash ring:
- Pros: Phenomenal write distribution. Two consecutive inserts (
id: 1001,id: 1002) land on completely different physical servers. - Cons: Range queries become impossible without a scatter-gather query. Running
SELECT * FROM orders WHERE created_at BETWEEN X AND Yrequires querying every single shard and merging the results in memory.
3. Entity-Group / Tenant-Based Sharding (The SaaS Standard)
- How it works: Sharding on
tenant_idoraccount_id. All data for a specific customer (orders,line_items,customers) resides on the same shard. - Pros: Queries within a tenant remain fast, isolated, and can utilize local joins.
- The Trap (The "Celebrity / Justin Bieber" Problem): If you run an e-commerce platform and Shard 1 houses a standard mom-and-pop store while Shard 2 houses Nike, Shard 2 will collapse under holiday traffic while Shard 1 sleeps.
2.3 Real-World Scenario: Designing a Composite Shard Key
To avoid both the Justin Bieber problem and range-query scatter-gather penalties, enterprise architectures frequently use Composite Shard Keys.
Suppose you are designing an enterprise ticketing system:
-- Anti-Pattern Key:
-- Shard Key: tenant_id
-- If Tenant 42 (Enterprise Client) sends 10,000,000 tickets, Shard X explodes.
-- Better Pattern: Composite Routing Key
-- Shard Key: hash(tenant_id, ticket_category)
-- Or Directory-based assignment for whale tenants:+-------------------------------------------------------------+
| Directory Service (Lookup Table in fast Redis / Metadata DB)|
+-------------------------------------------------------------+
| tenant_id: 1 - 500 --> Assigned to Shard Cluster A |
| tenant_id: 501 - 1000 --> Assigned to Shard Cluster B |
| tenant_id: 9999 (Nike) --> Dedicated Shard Cluster C |
+-------------------------------------------------------------+By isolating ultra-large tenants onto dedicated shards via a routing directory, you preserve predictable performance for the rest of your shared clusters.
Subtopic 3: Architectural Patterns: Application-Level vs Middleware-Based Sharding 🏗️
How does a query find its way to the correct shard? There are two primary architectural patterns used across the industry.
PATTERN 1: APPLICATION-LEVEL SHARDING
+-------------------------------------------------+
| Application Server |
| +-------------------------------------------+ |
| | Routing Logic: TargetShard(user_id) | |
| | Connection Pools: [Pool-1] [Pool-2] | |
| +-------------------------------------------+ |
+---------+-----------------------------+---------+
| |
v v
[ Shard 1 ] [ Shard 2 ]
----------------------------------------------------
PATTERN 2: MIDDLEWARE / PROXY-BASED SHARDING
+-------------------------------------------------+
| Application Server |
| (Treats DB like a single monolith) |
+------------------------+------------------------+
| Standard SQL
v
+-------------------------------------------------+
| Middleware / Sharding Proxy |
| (e.g., Vitess VTGate, Citus Coordinator) |
| - Parses SQL Abstract Syntax Tree (AST) |
| - Manages Global Connection Pooling |
| - Rewrites Query & Aggregates Results |
+---------+-----------------------------+---------+
| |
v v
[ Shard 1 ] [ Shard 2 ]3.1 Pattern 1: Application-Level Sharding
In this model, your backend code contains the routing logic and maintains separate database connection pools for each physical shard.
Practical Example (TypeScript / Node.js concept):
import { Pool } from 'pg';
import crypto from 'crypto';
class ShardedClient {
private shards: Pool[];
constructor(shardConnectionStrings: string[]) {
this.shards = shardConnectionStrings.map(conn => new Pool({ connectionString: conn }));
}
// Deterministic Shard Selector
private getShardIndex(shardKey: string): number {
const hash = crypto.createHash('md5').update(shardKey).digest();
// Read the first 4 bytes as an integer
return hash.readUInt32BE(0) % this.shards.length;
}
public async getOrder(tenantId: string, orderId: string) {
const shardIndex = this.getShardIndex(tenantId);
const targetPool = this.shards[shardIndex];
// Direct execution on the selected shard
const result = await targetPool.query(
'SELECT * FROM orders WHERE tenant_id = $1 AND id = $2',
[tenantId, orderId]
);
return result.rows[0];
}
}- Pros:
- Zero intermediary network hops: the application connects directly to the database.
- No external middleware components to deploy, monitor, or debug.
- Cons:
- Connection Storms: If you have 50 application pods and 20 database shards, and each pod maintains a pool of 20 connections per shard, you have active open database connections!
- Code Pollution: Developers must pass shard keys explicitly through service and repository layers.
- Resharding requires complex application logic or migration scripts.
3.2 Pattern 2: Middleware-Based / Proxy Sharding
In this pattern, an intelligent proxy layer sits between the application and the shards. The application speaks standard SQL to the proxy, completely unaware that multiple databases exist.
Industry Standard Implementations:
- Vitess (YouTube/Slack stack for MySQL): Applications talk to stateless
VTGateproxies, which inspect the SQL AST, consult aVSchema(Vitess schema mapping), and route toVTTabletprocesses controlling underlying MySQL instances. - Citus (PostgreSQL Extension): Transforms PostgreSQL into a distributed database using a coordinator node (or distributed coordinator topology) to distribute tables along shard keys.
Example: How Citus Handles Sharding at the DB Engine Layer
Instead of application-side routing code, the engine handles the distribution declaratively:
-- Connect to Postgres coordinator
CREATE EXTENSION citus;
-- Create standard relational table
CREATE TABLE users_table (
user_id UUID NOT NULL,
account_id INT NOT NULL,
payload JSONB,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
PRIMARY KEY (account_id, user_id)
);
-- Turn standard table into a horizontally sharded distributed table
-- Shard key: account_id (Hash distributed)
SELECT create_distributed_table('users_table', 'account_id');When you run:
SELECT * FROM users_table WHERE account_id = 42;The coordinator inspects the query, calculates hash(42), and pushes the query strictly to the single worker holding that partition.
- Pros:
- Application codebase stays clean; standard ORMs (Prisma, TypeORM, Hibernate) work out of the box.
- Centralized connection pooling and query optimization.
- Transparent rebalancing: middleware can move shards between physical boxes while holding requests in a queue for seconds, avoiding hard downtime.
- Cons:
- Added latency: every query must transit through the proxy/coordinator layer.
- You now maintain an orchestration layer that represents an additional infrastructure dependency.
3.3 Tradeoff Summary: Application vs. Middleware
+--------------------------+-----------------------------+-------------------------------+
| Feature | Application-Level | Middleware-Based (e.g. Vitess)|
+--------------------------+-----------------------------+-------------------------------+
| Extra Latency Hop | None (Direct connection) | Yes (~0.5 - 2 ms proxy cost) |
| Connection Management | Difficult (High footprint) | Centralized (Very efficient) |
| Application Complexity | High (Code routes queries) | Zero to Minimal |
| Cross-Shard Query Agg. | Manual (Write code to merge)| Handled automatically |
| Migration/Maintenance | Developer-driven | Operator-driven |
+--------------------------+-----------------------------+-------------------------------+Summary & Key Takeaways 📝
- Sharding is an architectural last resort: Always maximize indexes, read replicas, caching layers, and vertical scaling before sharding.
- Choose your split axis carefully: Vertical sharding groups tables by business domain (auth vs billing); Horizontal sharding cuts identical rows across machines.
- Guard your shard keys: Hash-based sharding provides the best write distribution; Range-based sharding creates moving write hotspots. Entity/Tenant-based sharding is ideal for B2B SaaS, provided you isolate outlier customers.
- Choose your operational model: Application-level routing is simpler to start with but hard to scale connection-wise. Middleware (like Vitess or Citus) adds operational infrastructure but keeps application code clean and coordinates complex rebalancing.
References and Documentation 📚
- Vitess Architecture & VSchema: Vitess Documentation (vitess.io)
- Distributed PostgreSQL with Citus: Citus Engine Docs (citusdata.com)
- MongoDB Sharding Concepts & Chunk Splitting: MongoDB Sharding Guide
- Designing Data-Intensive Applications (Martin Kleppmann): Chapter 6: Partitioning (Essential foundational reading for replication vs. partitioning dynamics).
Challenge
Sharding Readiness Review
You are the on-call engineer reviewing a service that is about to be sharded. Before anyone touches the schema, you must prove the team understands when sharding is the right tool, which axis to split on, and what it costs.
Your task
Fill in every blank line below. The editor is plain text — nothing runs, nothing is validated by a compiler. Your answers will be reviewed for accuracy, correct terminology, and practical trade-off awareness.
Rules of engagement
- Answer in 1–3 sentences per blank; short bullet fragments are fine.
- Use the precise vocabulary of the domain (e.g. the correct name for a failure mode, not a vague paraphrase).
- Where a question asks for a cost or advantage, give a concrete operational one, not "it is harder".
- Where a question asks for a number or formula, show the arithmetic.
- Do not answer a question by naming a technology alone; state the reason.
Context you may assume
A single-node PostgreSQL/MySQL primary with read replicas, a connection pooler, and an ORM. The team has proposed sharding because the largest table is very large. Your review must test whether that reasoning holds up and whether the proposed design survives real traffic.
Work top to bottom. Sections 1–2 are about whether to shard; sections 3–6 are about how to split and route; sections 7–9 are about the costs you are signing up for.
Expected result
What a complete submission looks like
Every blank line under sections 1–9 is filled in. There are no ____ placeholders left and no answer is left as "TBD" or "N/A".
Each answer is judged against these criteria:
| Criterion | Requirement |
|---|---|
| Completeness | All 9 sections answered; sub-parts a–e and both mitigations in section 5 are each addressed separately. |
| Terminology | Uses the standard name for each concept or failure mode rather than a paraphrase or a single product name. |
| Specificity | Advantages and costs are operational and concrete (what breaks, what gets slower, what the operator must now do). |
| Arithmetic | Section 6 shows the connection formula with all three variables and the computed total. |
| Trade-off framing | Sections 7 and 8 explicitly state both sides of the trade-off, not just one. |
| Justification | Section 9 explains the mechanism of irreversibility (what work a wrong choice forces), not merely "it is hard to change". |
Marked incorrect if:
- A blank is answered with a tool name and no reasoning.
- The row-count argument is accepted as sufficient justification for sharding (section 1).
- A cost is described only as "more complex" without naming the source of the complexity.
- The two routing patterns in section 6 are described as if one is strictly better than the other.
No answer key is provided; the reviewer verifies each blank against the reference material.