Chapter 9 of 12
Course Progress0 of 12 completed (0%)

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.

Database Scaling: Read Replicas, Partitioning & ShardingScale relational storage beyond single-instance bottlenecks: read replicas, replication lag, vertical/horizontal partitioning, sharding keys, and PgBouncer connection pooling.UNDERSTANDDatabase ScalingFOLLOW THE FLOWRead ReplicasAPPLY ITPartitioningDatabase Scaling: Read Replicas, Partitioning & ShardingScale relational storage beyond single-instance bottlenecks: read replicas, replication lag, vertical/horizontal partitioning, sharding keys, and PgBouncer connection pooling.UNDERSTANDDatabase ScalingFOLLOW THE FLOWRead ReplicasAPPLY ITPartitioning

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:

Single Primary (Master)

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.

Multiple Replicas (Slaves)

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:

  1. A user changes their display name from "Bob" to "Robert" and clicks Save.
  2. The browser sends an HTTP POST; the API updates the Primary database.
  3. The browser immediately redirects to /profile and sends an HTTP GET.
  4. The API routes the GET to a read replica that is 100ms behind the primary.
  5. 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.

Range-Based Sharding

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).

Hash-Based Sharding

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.

Concept Check

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

100k Writes/sec → 1 Primary + 10 Replicas → Primary CPU 100% SaturationFlaw: Every single replica must replay the exact same write stream (WAL/binlog). Replicas only scale reads!

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

Writes → Distributed across Shard 0, 1, 2, 3 | Reads → Load-balanced across Read ReplicasScalability: Both read throughput and write throughput scale linearly

Read replicas relieve 95% of database query load. When writes exceed single-node disk I/O, partition data across multiple primary shards.

Concept Check

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

Total Records
8across 4 shards
Connection Pool
2/12sockets active
Queued in PgBouncer
0waiting queries
Read-Write Split
Replicas Active
Sharding Scheme:
Read Replica Split:
Shard #0
mod 4 == 0
Primary (R/W)2 records
Alice Adams(usr_alice)
Carol Cole(usr_carol)
Read ReplicaLag: ~8ms
RO
Shard #1
mod 4 == 1
Primary (R/W)2 records
Grace Green(usr_grace)
Harry Hayes(usr_harry)
Read ReplicaLag: ~14ms
RO
Shard #2
mod 4 == 2
Primary (R/W)2 records
Mike Miller(usr_mike)
Paul Perez(usr_paul)
Read ReplicaLag: ~22ms
RO
Shard #3
mod 4 == 3
Primary (R/W)2 records
Sam Smith(usr_sam)
Tina Taylor(usr_tina)
Read ReplicaLag: ~11ms
RO
Query Router & Connection Pool Trace:
›Database cluster online: 4 Shards with 1 Primary + 1 Read Replica each.
›Connection pool router: PgBouncer active (Limit: 12 connections).

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:

Python Sharded Router Bug Hunt · Routing & Connection Pooling
Python

🎯 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 return digest % 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 calls self.pool.release(conn).

7Chapter Knowledge Challenge

Test your mastery of database sharding and replication concepts:

Concept Check 1 of 2
1

What is 'Consistent Hashing' and why is it preferred over simple modulo (hash(key) % N) when adding or removing database shards?

Concept Check 2 of 2
2

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?

Enjoying this free lesson? Your support helps us build more free animated chapters.

Support Us