Vertical Scaling and Read-Replica Architectures

12 min read

Welcome to the trenches of database scaling! You’ve probably reached that classic engineering milestone: your application went viral, your database CPU usage is hovering at a terrifying 98%, and your infrastructure bill looks like an international telephone number.

Your first instinct might be to click that tempting AWS/GCP dropdown and change your database instance from db.t4g.medium to db.m6i.32xlarge (128 vCPUs, 512 GiB RAM). That is vertical scaling (scaling up). It buys you breathing room, but eventually, you collide with physical limits: socket saturation, prohibitive costs, OS lock contention, and the terrifying reality that all your eggs remain in one single, high-stakes basket.

Before jumping straight into horizontal sharding (which introduces distributed transactions, cross-shard joins, and immense architectural complexity), industry-standard systems buy orders of magnitude more runway using Vertical Optimization and Read-Replica Architectures.


🎯 Boundaries, Scope, and What This Architecture Cannot Do

Before writing a single line of config, define the boundary of what this pattern solves:

What Is Possible

  • 10x–50x Read Throughput: Distribute read-heavy traffic (analytics, profile lookups, catalog queries) across dozens of read replicas.
  • Buffer Pool Optimization: Keep working sets in memory by partitioning gigantic monolithic tables into smaller physical chunks.
  • Sub-millisecond Latency for Hot Data: Offload repetitive queries entirely using memory-first key-value stores.
  • Zero Application Code Rewrites: Route read and write queries transparently using database proxy engines.

What Is NOT Possible (The Hard Limits)

  • Scaling High-Concurrency Writes: In a traditional primary-replica topology, all writes must go through the single primary node. If your write rate exceeds the primary disk’s I/O capacity or the engine's write transaction pipeline, read replicas will not save you.
  • Instant Consistency Across Replicas Out of the Box: Physical replication is bound by the laws of networking. Asynchronous replicas will lag behind the primary. If an application demands strict serializability across every read without engineering safeguards, naive read splitting will serve stale or missing data.

1. Primary-Replica Topologies and Replication Lag Handling 🔂

Definition & The Problem

In a primary-replica (formerly master-replica) topology, one database instance acts as the single source of truth for all mutations (INSERT, UPDATE, DELETE, DDL). One or more replica nodes continuously ingest a stream of changes from the primary to maintain duplicate copies of the dataset for read-only queries.

The fundamental engineering dilemma is Replication Lag: the delay between a transaction committing on the primary and that transaction becoming visible on a replica.

text
[Client] ─── (Write: Insert User) ───► [Primary DB]
   │                                        │
   │                                        ├── WAL / Binlog Stream (Network Lag 80ms)
   │                                        ▼
   └─── (Immediate Read: Get User) ───► [Replica DB] ──► Returns: "404 Not Found" 😱

If a user signs up, hits submit, and the UI immediately redirects them to their new dashboard (which reads from a replica that is lagging by 80ms), the user gets a "User does not exist" error. This is a violation of Read-Your-Own-Writes Consistency.

Replication Modes

  1. Asynchronous Replication (Default): The primary commits transactions to its local disk and immediately acknowledges the client without waiting for replicas to confirm receipt.
    • Trade-off: Lightning-fast write latency; risk of data loss on failover; replicas can fall seconds (or minutes) behind.
  2. Semi-Synchronous Replication: The primary waits until at least one replica has written the event to its relay log before returning success to the client.
    • Trade-off: Higher write latency, zero data loss for acknowledged transactions, but does not guarantee the replica has applied (replayed) the data to its query engine yet.

Industry-Standard Lag Mitigation Strategies

Strategy A: Read-Your-Own-Writes via Session Monotonicity (The "Causal Token" Pattern)

Rather than sending all reads to the primary, route reads from the user who performed the write to the primary for a brief cooldown period (e.g., NN seconds), while sending reads from all other users to replicas.

python
# Application-level lag guard implementation
import time

REPLICATION_SAFETY_WINDOW_SECONDS = 3.0

def save_user_profile(user_id: str, profile_data: dict, db_primary, cache):
    # 1. Mutate primary
    db_primary.update("users", profile_data, where={"id": user_id})
    
    # 2. Record a timestamp cookie or cache marker for this specific user
    cache.set(f"user:last_write:{user_id}", time.time(), ex=int(REPLICATION_SAFETY_WINDOW_SECONDS) + 1)

def get_user_profile(user_id: str, db_primary, db_replica, cache):
    last_write = cache.get(f"user:last_write:{user_id}")
    
    # If the user performed a write within the safety window, bypass replicas
    if last_write and (time.time() - float(last_write) < REPLICATION_SAFETY_WINDOW_SECONDS):
        return db_primary.select("users", where={"id": user_id})
    
    # Safe to read from potentially lagging replica
    return db_replica.select("users", where={"id": user_id})

Strategy B: LSN / GTID Tracking (Precise State Check)

Modern databases assign monotonic log numbers to transactions:

  • PostgreSQL: Log Sequence Numbers (LSN).
  • MySQL: Global Transaction Identifiers (GTID).

When a client executes a write, the primary returns the commit LSN/GTID. The client sends this value with its subsequent read query. The replica verifies whether its replayed state has reached that LSN/GTID:

sql
-- MySQL: Wait until the replica has applied the transaction with GTID X
-- Will block until caught up or until timeout (e.g., 2.0 seconds)
SELECT WAIT_FOR_EXECUTED_GTID_SET('3E11FA47-71CA-11E1-9E33-C80AA9E29538:1-50', 2.0);

-- PostgreSQL check: Inspect replication delay in bytes
SELECT pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS replication_delay_bytes
FROM pg_stat_replication;

2. Read/Write Splitting via Database Proxies and Connection Pooling 🔀

Definition & The Problem

Hardcoding database connection switching inside application code (e.g., if is_write: master_db.query() else: replica_db.query()) leads to fragile codebases, poor reuse of connection pools, and cascading failure during failovers.

Furthermore, relational databases like PostgreSQL fork a separate backend process for each client connection (costing ~5–10MB RAM per connection plus context switching). When 2,000 stateless web containers spin up, they quickly trigger FATAL: remaining connection slots are reserved for non-replication superuser connections.

A Database Proxy acts as an intermediary layer that terminates incoming application connections, maintains a pool of persistent connections to the database instances, parses SQL statements on the fly, and routes traffic automatically.

text
                  ┌──────────────┐      Writes       ┌─────────────┐
 [Web Pod 1] ───► │              │ ────────────────► │ Primary DB  │
 [Web Pod 2] ───► │  DB Proxy    │                   └─────────────┘
 [Web Pod 3] ───► │ (e.g.,PgCat/ │      Reads        ┌─────────────┐
 [Web Pod N] ───► │   ProxySQL)  │ ────────────────► │ Replica 1   │
                  └──────────────┘         │         └─────────────┘
                                           │         ┌─────────────┐
                                           └───────► │ Replica 2   │
                                                     └─────────────┘

Connection Pooling Mechanics

  • Session Pooling: A client connection is bound to a single backend database connection from login until disconnect. (Safer for prepared statements and session-level variables, but limits scalability).
  • Transaction Pooling: The proxy assigns a backend connection to the client only for the duration of a transaction. Once a COMMIT or ROLLBACK executes, the backend connection returns to the pool.
  • Statement Pooling: The connection is returned after every query (does not support multi-statement transactions).

Practical Proxy Configuration: ProxySQL (MySQL)

ProxySQL sits between your application and your MySQL clusters, analyzing SQL queries via regex and routing them according to hostgroups.

sql
-- 1. Define Hostgroups: 10 = Writers (Primary), 20 = Readers (Replicas)
INSERT INTO mysql_servers (hostgroup_id, hostname, port, max_connections) 
VALUES 
  (10, 'primary-db.internal', 3306, 200),
  (20, 'replica-db-1.internal', 3306, 500),
  (20, 'replica-db-2.internal', 3306, 500);

-- 2. Configure Query Routing Rules
-- Direct SELECT ... FOR UPDATE or explicit transaction locks to the primary
INSERT INTO mysql_query_rules (rule_id, active, match_pattern, destination_hostgroup, apply_pattern)
VALUES (1, 1, '^SELECT.*FOR UPDATE', 10, 1);

-- Direct general SELECT statements to the read-replica hostgroup
INSERT INTO mysql_query_rules (rule_id, active, match_pattern, destination_hostgroup, apply_pattern)
VALUES (2, 1, '^SELECT', 20, 1);

-- Load configuration into runtime and persist to disk
LOAD MYSQL SERVERS TO RUNTIME; SAVE MYSQL SERVERS TO DISK;
LOAD MYSQL QUERY RULES TO RUNTIME; SAVE MYSQL QUERY RULES TO DISK;

Modern PostgreSQL Alternative: PgCat / PgBouncer

While PgBouncer is the gold standard for lightweight connection pooling in PostgreSQL, modern deployments use PgCat (developed by PostgresML) because it natively supports read/write splitting, replica load balancing, and failover detection without requiring separate read and write ports in your application code.


3. Distributed Caching Layers for Query Offloading ⚡

Definition & The Problem

Even with 10 read replicas, relational databases are disk-bound and CPU-bound when processing complex relational lookups, multiple JOINs, and JSON aggregations. Fetching an item page that requires 8 relational joins 5,000 times per second will saturate replica CPUs.

A Distributed In-Memory Cache (Redis, KeyDB, Memcached) keeps pre-computed structures in RAM, operating at sub-millisecond latency and delivering hundreds of thousands of operations per second per node.

Cache Invalidation Patterns

1. Cache-Aside (Lazy Loading) — The Industry Standard

The application layer controls cache lookups and fallbacks.

python
import json
import redis

cache = redis.Redis(host='cache.internal', port=6379, decode_responses=True)

def get_product(product_id: int, db_replica) -> dict:
    cache_key = f"product:{product_id}"
    
    # 1. Attempt read from cache
    cached_data = cache.get(cache_key)
    if cached_data:
        return json.loads(cached_data)
    
    # 2. On miss, read from database replica
    product = db_replica.query("SELECT * FROM products WHERE id = %s", (product_id,))
    
    if product:
        # 3. Populate cache with TTL (Time-To-Live)
        cache.setex(cache_key, 3600, json.dumps(product))
        
    return product

Critical Cache Failures & How to Stop Them

A. Cache Stampede (Thundering Herd)

  • The Scenario: A high-traffic key (e.g., flash_sale_items) expires at 12:00:00. At 12:00:01, 20,000 requests arrive concurrently. All 20,000 see a cache miss. All 20,000 fire identical heavyweight SQL queries to the database simultaneously.
  • The Solution: Mutex locking or Probabilistic Early Expiration (the XFetch algorithm).
python
# Mitigating Thundering Herd using a Redis Distributed Lock
def get_product_safe(product_id: int, db_replica):
    cache_key = f"product:{product_id}"
    data = cache.get(cache_key)
    
    if data:
        return json.loads(data)
        
    lock_key = f"lock:{cache_key}"
    # Acquire a temporary mutex lock (expires in 5s to avoid deadlocks)
    if cache.set(lock_key, "1", nx=True, ex=5):
        try:
            # Single thread refreshes the cache
            product = db_replica.query("SELECT * FROM products WHERE id = %s", (product_id,))
            cache.setex(cache_key, 3600, json.dumps(product))
            return product
        finally:
            cache.delete(lock_key)
    else:
        # Other threads sleep briefly and retry reading cache
        time.sleep(0.05)
        return get_product_safe(product_id, db_replica)

B. Cache Penetration

  • The Scenario: Attackers repeatedly request IDs that do not exist in the database (GET /product/-99999). The cache always misses, forcing the DB to perform pointless disk reads.
  • The Solution: Cache empty/null results with a short TTL (e.g., 60 seconds) or configure a Bloom Filter upstream in Redis to reject non-existent IDs with zero DB queries.

4. Table Partitioning: Range, List, and Hash Partitioning 📦

Definition & The Problem

Even if your primary node only accepts writes, what happens when a single table hits 500 million rows (e.g., audit logs, orders, tracking events)?

  1. B-Tree Index Bloat: Indexes grow larger than available RAM. Index scans must read from disk rather than the buffer pool.
  2. Maintenance Nightmare: Running VACUUM (Postgres) or OPTIMIZE TABLE (MySQL) locks tables or monopolizes I/O for hours.
  3. Data Eviction Penalties: Running DELETE FROM logs WHERE created_at < '2023-01-01' causes massive transaction write-ahead log (WAL) churn and triggers vacuum bloat.

Table Partitioning splits a large physical table into smaller, independent underlying tables (partitions) while maintaining a single logical table interface for queries.

text
               Logical Table: transactions
                     [Routing Engine]
              ┌──────────────┼──────────────┐
              ▼              ▼              ▼
       Part_2024_Q1    Part_2024_Q2   Part_2024_Q3
       (10M rows)      (10M rows)     (10M rows)

Partitioning Types

Partitioning Type Best Used When... Practical Example
Range Partitioning Data maps naturally to continuous intervals (timestamps, sequential IDs). Time-series metrics, financial ledger tables by month/year.
List Partitioning Rows correspond to discrete, categorical values. Segregating data by country/region (US, EU, APAC) for regulatory compliance.
Hash Partitioning There is no logical range/category, but data must be evenly spread to avoid hot partitions. Splitting user accounts evenly across NN physical storage segments.

Hands-on: PostgreSQL Declarative Range Partitioning

Here is an enterprise-standard declarative range partitioning implementation for audit logs:

sql
-- 1. Create the parent partitioned table (cannot store rows directly)
CREATE TABLE system_events (
    id BIGINT GENERATED ALWAYS AS IDENTITY,
    event_type VARCHAR(50) NOT NULL,
    payload JSONB,
    created_at TIMESTAMPTZ NOT NULL,
    PRIMARY KEY (id, created_at) -- Partition key MUST be part of primary key!
) PARTITION BY RANGE (created_at);

-- 2. Create physical partition tables for specific ranges
CREATE TABLE system_events_2026_q1 PARTITION OF system_events
    FOR VALUES FROM ('2026-01-01 00:00:00+00') TO ('2026-04-01 00:00:00+00');

CREATE TABLE system_events_2026_q2 PARTITION OF system_events
    FOR VALUES FROM ('2026-04-01 00:00:00+00') TO ('2026-07-01 00:00:00+00');

-- 3. Create indexes on the parent table; PG automatically cascades them to partitions
CREATE INDEX idx_system_events_type ON system_events (event_type);

The Magic of Partition Pruning

When you run a query filtering on the partition key, the database query planner uses Partition Pruning to scan only the relevant physical files and completely ignore the rest:

sql
EXPLAIN SELECT * FROM system_events 
WHERE created_at BETWEEN '2026-02-01' AND '2026-02-15';

-- QUERY PLAN Output:
-- Append  (cost=0.00..24.50 rows=10 width=48)
--   ->  Seq Scan on system_events_2026_q1  (cost=0.00..24.45 rows=10 width=48)
-- Notice system_events_2026_q2 is NOT even touched!

Instant Retention Drops (Zero-Downtime Data Purging)

Instead of executing a destructive, slow DELETE FROM system_events WHERE created_at < '2026-04-01';, you can detach and drop the physical partition instantly:

sql
-- Instant metadata-only operation: Detach the old partition
ALTER TABLE system_events DETACH PARTITION system_events_2026_q1;

-- Drop the partition table without locking the active table
DROP TABLE system_events_2026_q1;

🛠️ Summary & Architectural Decision Flow

When your database begins to sweat under load, follow this decision tree before embarking on horizontal sharding:

text
Is CPU/Disk I/O maxed out?
  │
  ├── Are the queries primarily reads?
  │     ├── YES: Add Read Replicas + Implement a Proxy (ProxySQL/PgCat).
  │     └── Are identical reads repeated frequently?
  │           └── YES: Implement Cache-Aside with Redis + Lock protection.
  │
  ├── Is write performance dropping due to massive table sizes/index bloat?
  │     └── YES: Implement Range or Hash Table Partitioning.
  │
  └── Are raw write transactions exceeding single-node hardware limits?
        └── YES: Re-evaluate your indexes and schema. If saturated, you are now
                 ready for Horizontal Database Sharding (Topic 3).

📚 References & Further Reading

Challenge

Scaling a Read-Heavy Postgres/MySQL Stack Before Sharding

You're the on-call engineer for a growing SaaS app. Writes are fine for now, but p99 reads are climbing, the primary is at 80% CPU on read traffic, and the product team wants a "your comment appears instantly" guarantee.

Before anyone says the word sharding, fill in the blanks below to prove you know the practical runway: replicas → proxy → cache → partitions.

Your task

Answer each prompt in the Monaco editor by replacing each ___ with the correct term, mode, mechanism, or short explanation. Keep answers to one line each. Use precise industry terminology — vague answers like "make it faster" will not be accepted.

Guidelines

  • Do not write code. This is a design-reasoning exercise.
  • Where a prompt asks for two things (e.g., a problem and its mitigation), give both on the same line, separated by →.
  • Where a prompt asks for a name, the exact industry term is expected (product names count).
  • Reason from limits first: state the constraint, then the fix.

Hint: every answer in this challenge maps to a decision you would actually make in a design review doc.

Expected result

Grading criteria

Each blank is scored independently. Full credit requires the exact industry term or a semantically identical phrase; partial credit for a correct concept expressed imprecisely.

Q1 — three distinct limits

  • Must list three different categories of constraint. Acceptable categories include cost/economics, connection/socket ceilings, single-node OS limits, memory, and CPU.
  • Reject three variations of the same idea (e.g., "cost, price, budget" counts as one).

Q2 — read-your-own-writes

  • Must name the read-your-own-writes pattern (synonyms such as "read-after-write consistency" accepted).
  • The window must be described as derived from measured replication lag / observed replica delay, not a hardcoded guess.
  • Reject answers that only say "route reads to primary" without naming the pattern and the window-sizing basis.

Q3 — replication position tracking

  • PostgreSQL answer must reference LSN (log sequence number) based waiting.
  • MySQL answer must reference GTID based waiting.
  • Swapping the two scores zero for that item.

Q4 — proxy layer

  • "Why not in app code" must mention the lack of central control/visibility, operational coupling, or the need to rewrite logic per service.
  • Component must be named as a database proxy / SQL-aware router / connection pooler front end.
  • Must supply two real products (e.g., ProxySQL, PgCat, PgBouncer, HAProxy, Vitess, MaxScale, Amazon RDS Proxy — any two valid ones).

Q5 — pooling modes

  • All three modes required in session → transaction → statement order.
  • Scalability pick must be transaction pooling.
  • Caveat must reference session state not being preserved across transactions (prepared statements, temp tables, SET variables, advisory locks).
  • Order errors or a single missing mode lose that item's credit.

Q6 — cache failure modes

  • Mode A must be cache stampede (accept "thundering herd") with a mitigation of mutex/lock or probabilistic early expiration.
  • Mode B must be cache penetration (accept "cache miss storm for nonexistent keys") with a mitigation of caching nulls briefly or Bloom filter.
  • Mitigations must be paired with the correct mode; a swapped pairing scores zero.

Q7 — partitioning strategies

  • Time-series → range partitioning.
  • Categorical/regulatory → list partitioning.
  • Even spread → hash partitioning.
  • Any swap scores zero for the affected item.

Q8 — retention and pruning

  • Retention technique must name detaching / dropping a partition (accept "partition drop", "detach partition then drop").
  • Optimizer behavior must name partition pruning.
  • Generic answers like "add an index" or "archive to another table" score zero.

Q9 — decision flow

  • a) → add replicas + proxy.
  • b) → add distributed cache with lock protection.
  • c) → partition the table.
  • d) → revisit indexes and schema first, then consider sharding.
  • Each letter is worth one point; the four-way mapping must be exact.

Q10 — write scalability ceiling

  • Must explain that all writes still funnel to a single primary, so adding replicas does nothing for write throughput, and that asynchronous replicas introduce lag/stale reads rather than adding write capacity.
  • Answers that only mention "replication lag" without naming the single-writer bottleneck receive partial credit.

Overall

  • No code is expected; a solution that writes SQL or application code instead of answering is marked incorrect.
  • Blank or placeholder (___) lines are unscored.
plain text

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.