FullStack AI Hub
Studio
System Design · 03. Data & Storage
11 min
10 steps
Beginner

Replication

Scale reads with leader-follower streams, tame replication lag, and survive leader failovers without split-brain.

System Design03. Data & StorageLesson 4 of 11
11 minBeginner10 steps

Replication

Scale reads with leader-follower streams, tame replication lag, and survive leader failovers without split-brain.

TOTAL QPS
3,200/s
READ / WRITE
88% / 12%
P95 LATENCY
520 ms
PRIMARY LOAD
95%
reads + writes3,200 qpsBackend API48%Primary DB95%SPOF · 95%88% reads starving write transactions
read query
write / WAL stream
heartbeat / election
stale read / outage
In This LessonStep 1 of 10
What You Will Master
  • ✓Offload read-heavy queries from a saturated Primary Leader onto Follower Read Replicas
  • ✓Navigate the speed-vs-durability trade-off between Async, Sync, and Semi-Sync WAL replication
  • ✓Fix replication-lag stale reads with Read-Your-Writes routing and LSN watermarks
  • ✓Promote a standby leader cleanly while preventing split-brain data corruption with fencing tokens

Architectural Trade-Off Comparison Matrix

PatternBest ForKey Trade-Off
Async ReplicationRead scaling across regions with low write latencyRecent committed writes can be lost if Leader dies suddenly (RPO > 0)
Semi-Sync (1 Sync + N Async)Production OLTP databases balancing RPO=0 and speedOne extra network RTT on commits; stalls briefly if sync standby drops
Read-Your-Writes (LSN)User profiles, comments, and post-checkout order pagesRouting logic must track recent writer timestamps or LSN watermarks
Fencing Tokens / EpochsAutomated leader failover under network partitionsStorage layer must reject writes carrying stale epoch numbers

Step-by-Step Architectural Breakdown (10 Steps)

Full architectural walkthrough transcript and state transitions for Replication.

STEP 01 · PROBLEMJump to step →

One Primary DB drowning in mixed reads and writes

Your application sends **2,800 read queries/sec** and **400 writes/sec** into a single **Primary DB**. Because 88% of traffic is read-only analytics and profile lookups, the database is pegged at **95% CPU**.

Worse, that single machine is a **Single Point of Failure (SPOF)**: one bad disk controller or AZ power dip takes the entire product offline.

watch:Even if you buy a bigger server vertically, a single database node still leaves you with zero high availability during hardware failure.

Single Point of FailureRead/Write ContentionVertical Ceiling
STEP 02 · SOLUTIONJump to step →

Leader-Follower read scaling

We introduce **Leader-Follower Replication**. All **writes** still go to the single **Primary Leader** (preserving a single source of truth), while **two Read Replicas** continuously mirror its changes.

A **DB Router** directs `INSERT/UPDATE` traffic to the Leader and load-balances `SELECT` queries across the Follower pool—cutting Primary CPU from **95% down to 24%**.

good:Leader-Follower scales read throughput horizontally just by adding more replicas—without changing your SQL schema.

Leader-FollowerRead/Write SplittingRead Replica Pool
STEP 03 · TECHNIQUEJump to step →

How replicas stay in sync: Write-Ahead Log (WAL)

Replicas do not copy entire database tables on every change. Every mutation on the Leader is first appended sequentially to an immutable **Write-Ahead Log (WAL / Binlog)** marked with a monotonic **LSN (Log Sequence Number)**.

Followers open persistent TCP streams to the **WAL Shipper**, pull each byte-level or row-level log record in order, and replay it locally to reconstruct the exact same state.

idea:Row-based WAL replication is deterministic—unlike statement-based replication, functions like NOW() or RAND() never diverge across followers.

Write-Ahead Log (WAL)Log Sequence Number (LSN)Row-Based Replication
STEP 04 · TRADE-OFFJump to step →

Async vs Synchronous replication trade-off

In **Asynchronous replication**, the Leader commits and ACKs the client immediately without waiting for followers. Writes are fast (**15 ms**), but if the Leader catches fire 100 ms later, un-shipped commits vanish (**RPO > 0**).

In **Synchronous replication**, the Leader waits for followers to persist the WAL before ACKing. Durability is airtight (**RPO = 0**), yet a single slow or dead follower halts **every write** across the entire system!

watch:Making ALL followers synchronous reduces write availability dramatically: if just 1 of 3 replicas stalls, every checkout write hangs.

Async ReplicationSync ReplicationRPO (Recovery Point Objective)
STEP 05 · PROBLEMJump to step →

Replication lag: the vanishing post bug

A user updates their bio and clicks **Save**. The write succeeds on **Primary Leader**, and the browser immediately refreshes the profile page—which your router sends to **Read Replica 2**.

Because Replica 2 is lagging **450 ms behind** the WAL stream, it serves the **old bio**! The user thinks their edit was lost and keeps mashing Save.

watch:Under async replication, followers are only eventually consistent—lag can spike from 10 ms to several seconds during heavy batch migrations.

Replication LagEventual ConsistencyStale Read Anomaly
STEP 06 · SOLUTIONJump to step →

Fix stale reads with Read-Your-Writes routing

To guarantee **Read-Your-Writes consistency** without routing every read to Primary, the API returns the commit’s **LSN watermark** (or sets a 10-second `recent-write` cookie) right after a user saves.

The **LSN-Aware Router** sends that user’s own immediate reloads to **Primary** (or only to a follower whose applied LSN ≥ watermark), while everyone else keeps reading fast from the replica pool.

good:Only the editing author needs immediate read-after-write consistency; millions of other viewers happily tolerate 200 ms of async lag.

Read-Your-WritesLSN WatermarkSticky Session Routing
STEP 07 · TECHNIQUEJump to step →

Semi-Synchronous replication: best of both worlds

In practice, almost nobody runs every follower synchronously. **Semi-Synchronous replication** configures **exactly one follower** as a **Sync Standby** and keeps the remaining read replicas **Asynchronous**.

Every write is guaranteed to exist on **at least two machines** before the client gets a 200 OK (**RPO = 0**), and if the Sync Standby dies, one of the Async Replicas is automatically promoted to Sync Standby so writes keep flowing.

good:Semi-Sync (used by MySQL Semi-Sync and Postgres synchronous_standby_names) is the industry sweet spot for durable, low-latency OLTP databases.

Semi-Sync ReplicationHot StandbyRPO = 0 Durability
STEP 08 · PROBLEMJump to step →

Leader crashes: automated failover & promotion

At 3:14 AM, **Primary Leader** loses power. Health probes from the **Failover Orchestrator** miss 3 consecutive heartbeats (15 seconds) and declare the Leader dead.

The orchestrator picks the follower with the **highest LSN** (the Sync Standby), promotes it to the new **Primary Leader**, and flips the DB Router’s write endpoint—recovering writes in **< 30 seconds**.

watch:Never set heartbeat timeouts too aggressive (e.g., 1 second): a brief GC pause could trigger an unnecessary failover storm!

Heartbeat TimeoutStandby PromotionRTO (Recovery Time Objective)
STEP 09 · TRADE-OFFJump to step →

Preventing Split-Brain with Fencing Tokens

What if **Old Primary** never actually died—it was only isolated by a 20-second network partition? When the cable heals, **two nodes both believe they are Leader** and accept conflicting writes (**Split-Brain**), permanently corrupting balances.

Production clusters stamp every leader election with a strictly increasing **Epoch / Fencing Token** (`Epoch 7 > Epoch 6`). The storage layer and proxy immediately reject any write from the zombie `Epoch 6` leader (**STONITH / Fencing**).

watch:Split-brain is the #1 cause of catastrophic database corruption during automated failover—always require quorum consensus + epoch fencing.

Split-BrainFencing Token (Epoch)STONITH
STEP 10 · RECAPJump to step →

Production HA replication topology

A battle-tested replicated database pairs **1 Primary Leader** with **1 Semi-Sync Standby** (zero data loss) and **2+ Async Read Replicas** (horizontal read scaling), fronted by an **LSN-aware DB Router** and guarded by **Epoch Fencing**.

Run the combined chaos experiment below to kill a replica during a traffic spike and watch the architecture hold steady.

good:Use Semi-Sync for durability, Async Replicas for read scale, LSN watermarks for Read-Your-Writes, and Epoch Fencing for safe failovers.

HA Replication BlueprintSemi-Sync + Async PoolFenced Failover

Related Production Deep-Dives & Simulators

Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.