DATABASES / SYSTEM CONCEPT BRIEF

Replication

Replication keeps copies of the same data on multiple machines.

IntermediatePhase 04 / Topic 12 of 16RequirementsTrade-offsFailure modes
01

Overview

Replication keeps copies of the same data on multiple machines. It provides high availability (if one node fails, another takes over), read scalability (replicas serve reads), and lower latency (replicas close to users). The central choices are the topology (single leader, multi-leader, or leaderless) and whether replication is synchronous or asynchronous.

With asynchronous replication, replicas lag behind the leader, so a read from a replica may return stale data, and a leader failure can lose the most recent writes. Synchronous replication avoids data loss but adds latency and can block writes if a replica is slow. Most systems use a mix: one synchronous replica for durability and the rest asynchronous.

A teacher and teaching assistants

The teacher (leader) updates the official gradebook. Assistants (replicas) copy the updates to their own gradebooks to answer student questions. If an assistant has not caught up yet, a student may hear an old grade (replication lag).

02

When to use it

  • Survive machine or availability zone failures.
  • Scale read-heavy workloads.
  • Serve reads close to users in other regions.
  • Offload analytics or backups from the primary.
03

Where it shows up in interviews

Read scaling

Recognize it when: reads greatly exceed writes.

  • Scale a product catalog database
  • Design Twitter's read path
High availability and failover

Recognize it when: the database must survive failures.

  • Design a payment system
  • Design multi-AZ architecture
Multi-region

Recognize it when: users on several continents.

  • Design a global social network
  • Design a multi-region key-value store
04

Where it is used in real software

PostgreSQL / MySQL replicas

Streaming replication with read replicas and automatic failover via Patroni, RDS Multi-AZ, or Orchestrator.

Cassandra and DynamoDB

Leaderless replication with tunable consistency; each write goes to N replicas.

Aurora

Replicates storage six ways across three availability zones, so replicas share storage and lag is typically tens of milliseconds.

05

Key terms

Leader / primary
Accepts writes and sends changes to followers.
Follower / replica
Applies the leader's changes; can serve reads.
Replication lag
How far a replica is behind the leader.
Synchronous / asynchronous
Whether the leader waits for replicas before confirming a write.
Read-your-writes
A user always sees their own recent writes.
06

How it works, step by step

  1. 1
    Client writes to the leader

    The leader appends the change to its log (WAL, binlog).

  2. 2
    Leader streams the log

    Followers receive and apply changes in order.

  3. 3
    Commit acknowledgment

    Asynchronous: confirm immediately. Synchronous: wait for at least one replica.

  4. 4
    Reads

    Critical reads go to the leader; others can go to replicas.

  5. 5
    Failover

    If the leader dies, promote the most up-to-date replica and redirect clients.

Asynchronous leader-follower replication
Step 1 / 4
Client
Leader
Replica A
Replica B

STEP 1UPDATE profile SET name = 'Ana' is written to the leader's log and committed.

07

Replication topologies

Trade-offs between consistency, availability, and write scaling

Step 1 / 3
TopologyWrites go toProsCons
Single leaderOne leaderSimple, no write conflictsLeader is the write bottleneck; failover needed
Multi-leaderLeader in each regionLocal writes in every regionWrite conflicts must be resolved
Leaderless (Dynamo style)Any N replicas with quorumsHigh availability, no failoverEventual consistency, read repair

NOWTopology: Single leader | Writes go to: One leader | Pros: Simple, no write conflicts | Cons: Leader is the write bottleneck; failover needed

Single leader is the default for relational databases. Multi-leader and leaderless appear in globally distributed and highly available NoSQL systems.

08

Implementation

// Route reads to replicas, but give users read-your-writes consistencyconst LAG_WINDOW_MS = 5_000; async function query(sql: string, params: unknown[], opts: { userId?: string; write?: boolean } = {}) {  if (opts.write) {    const result = await primary.query(sql, params);    if (opts.userId) await redis.set(`recent-write:${opts.userId}`, "1", { PX: LAG_WINDOW_MS });    return result;  }  const wroteRecently = opts.userId && (await redis.exists(`recent-write:${opts.userId}`));  const target = wroteRecently ? primary : pickReplica();  return target.query(sql, params);}
09

Complexity and performance

Async replication lagms to seconds

Can grow under heavy load.

Sync write latency+1 RTT to replica

Same-region replicas keep this small.

Failover timeseconds to a minute

Detection + promotion + DNS / proxy update.

10

Trade-offs

Sync vs async

Synchronous replication prevents data loss on failover but slows writes and can stall them if replicas are unhealthy; asynchronous is fast but can lose recent writes.

Read replicas vs consistency

Replicas scale reads but return stale data; route reads that must be fresh to the leader.

11

Variants and related techniques

Semi-synchronous

Wait for at least one replica, not all.

Chain replication

Writes flow through a chain; reads from the tail are strongly consistent.

Logical replication / CDC

Replicate row changes to other systems (search, analytics).

12

Common mistakes

  • Reading your own write from a lagging replica.

    Fix: Route the user's reads to the leader briefly after writes, or wait for the replica to reach the write's position.

  • Automatic failover without fencing.

    Fix: Ensure the old leader cannot keep accepting writes (split brain).

  • Treating replicas as backups.

    Fix: Replicas copy mistakes instantly (DROP TABLE); keep point-in-time backups too.

13

Interview questions

What is replication lag and how do you handle it?

The delay before a replica reflects the leader's writes. Handle it by routing freshness-critical reads to the leader, providing read-your-writes by tracking recent writers, monitoring lag, and removing lagging replicas from rotation.

Single-leader vs leaderless replication?

Single leader gives simple, consistent writes but needs failover and caps write throughput. Leaderless accepts writes on any replica with quorums, giving high availability without failover, at the cost of eventual consistency and conflict resolution.

14

Practice problems

ProblemDifficultyWhat it trains
Add read replicas to a read-heavy appEasyRead routing.
Design read-your-writes with replicasMediumSession consistency.
Design multi-region replication for a social appHardTopology and conflicts.