Modern System Design & API Architecture · Chapter 9 · ~30 min · Advanced
Database Scaling: Read Replicas, Partitioning & Sharding
When a single SQL instance can no longer keep up with user growth, you must scale data horizontally. Explore the mechanics of read-write splitting, replication lag mitigation, hash vs range sharding, and connection pool management.
- Implement Read-Write Splitting with Primary-Replica database replication
- Diagnose and mitigate replication lag (read-after-write consistency)
- Compare Hash-based vs Range-based horizontal database sharding architectures
- Prevent connection pool exhaustion and configure proxy connection routers
Database Scaling: Read Replicas, Partitioning & Sharding: learn it visually
Scale relational storage beyond single-instance bottlenecks: read replicas, replication lag, vertical/horizontal partitioning, sharding keys, and PgBouncer connection pooling.
1Vertical Hardware Ceilings & The Read-Write Split
Virtually all real-world web applications (social media, blogs, e-commerce, news) exhibit a heavily asymmetric traffic profile: 90% to 98% of queries are reads (SELECT), while only 2% to 10% are writes (INSERT, UPDATE, DELETE).
Before touching complex sharding, the first scaling step is Primary-Replica Replication:
Write Authority
Handles all mutating SQL statements. Every write is committed to the Write-Ahead Log (WAL) or binlog, which is streamed asynchronously across the private network to replica nodes.
Read Horizontal Pool
Read-only clones that replay the primary's log stream. Web servers distribute read queries across this pool, scaling read throughput from 2,000 queries/sec to 100,000+ queries/sec.
// Application-level Read-Write Routing
async function queryDatabase(sql: string, params: any[], isMutation = false) {
// Direct all mutating operations to the single primary database
if (isMutation || isWriteQuery(sql)) {
return primaryPool.query(sql, params);
}
// Load-balance read SELECT queries across the pool of read replicas
const replica = replicaPool.pickNextRoundRobin();
return replica.query(sql, params);
}2The Peril of Replication Lag: Read-After-Write Consistency
In asynchronous replication, there is a small physical propagation delay (typically 5ms to 500ms, or several seconds during network congestion) between when a write commits on the primary and when it replays on replicas.
This causes the classic Stale Read Anomaly:
- A user changes their display name from "Bob" to "Robert" and clicks Save.
- The browser sends an HTTP POST; the API updates the Primary database.
- The browser immediately redirects to
/profileand sends an HTTP GET. - The API routes the GET to a read replica that is 100ms behind the primary.
- The replica returns the old name "Bob"! The user thinks the site is broken and submits again.
3Horizontal Sharding: Hash vs Range Partitioning
When your dataset exceeds single-machine storage (e.g. 10TB of tweets) or write I/O saturates the Primary, you must horizontally shard: splitting rows across independent database servers.
Key Intervals
Partitions data by ranges (e.g. Users A-F → Shard 0, G-L → Shard 1). Easy to query ranges, but prone to hotspotting (e.g., if a celebrity with last name 'Smith' attracts 80% of traffic).
Uniform Modulo
Computes hash(user_id) % N. Evenly distributes records across all shards, eliminating hotspots. However, cross-shard joins and re-sharding require consistent hashing algorithms.
What is the primary drawback of horizontal database sharding compared to a single monolithic database?
4Mental Models: Read Replicas, Sharding & Pools
Contrast common misconceptions about database scaling with production realities:
Wrong idea: Adding read replicas to scale write-intensive mutations
Assuming that adding 10 read replicas will speed up high-frequency INSERT and UPDATE operations during a flash sale.
Real system: Route SELECTs to replicas and scale writes via horizontal sharding
Read replicas relieve 95% of database query load. When writes exceed single-node disk I/O, partition data across multiple primary shards.
Why does a PostgreSQL database crash or crawl when 5,000 serverless functions attempt to open direct TCP database connections?
5Hands-On: Database Sharding & Connection Pool Simulator
Test your intuition with the live simulator below. Switch between Hash Modulo and Range-Based sharding, execute writes and reads, and trigger a query surge to see connection pool queuing in real time:
Database Sharding & Connection Pool Architecture Simulator
6Bug Hunt: Fix the Database Router & Pool Leak
Below is a Python database routing layer. It contains three critical defects: it routes all traffic to Shard 0 (defeating sharding entirely), routes write queries to read replicas (causing read-only transaction crashes), and leaks checked-out database connections by failing to release them in a finally: block.
Fix the implementation below, then click Run & verify:
🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.
Need a hint?
- Calculate hash: uncomment
digest = ...and returndigest % len(self.shards)instead of 0. - Fix routing: use
target_db = shard.primary if is_write else shard.replica. - Release connection: add a
finally:block that callsself.pool.release(conn).
7Chapter Knowledge Challenge
Test your mastery of database sharding and replication concepts:
What is 'Consistent Hashing' and why is it preferred over simple modulo (hash(key) % N) when adding or removing database shards?
In a read-write split setup, when should a SELECT query be explicitly directed to the Primary database instead of a Read Replica?
8Recap & Architectural Review
- Read-Write Split: Direct writes to a single Primary and scale read queries across horizontal Read Replicas.
- Replication Lag: Mitigate stale reads using Read-After-Write pin windows or LSN verification.
- Horizontal Sharding: Partition data across shards using deterministic hashing to prevent hotspots.
- Connection Pooling: Always multiplex database connections through tools like PgBouncer to prevent connection exhaustion.
Ready to dive into distributed systems theory: CAP Theorem & PACELC?