SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
  • Indexing
  • Partitioning
  • Replication
  • Sharding
  • Query Optimization
  • Denormalization
  • Materialized Views
  • Connection Pooling
  • Replication Models
  • Replication Lag
  • Quorum (R + W > N)
  • Shard Keys, Hot Shards and Resharding
  • Cross-Shard Joins
  • Backups, RPO, RTO and Disaster Recovery
  • Point-in-Time Recovery
  • Data Archiving and TTL
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Data and Storage/Database Scaling

Replication

Keep copies of your data on several machines for safety and read speed.

⏱ 15 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Replication means keeping copies of the same data on several machines. If one machine dies, another still has the data. And many machines can answer reads at the same time.

  • One node is usually the leader (it takes the writes). The others are followers (they copy the leader and serve reads).
  • Copying can be synchronous (wait for the copy) or asynchronous (do not wait). Async is faster but copies can be behind.
  • Replication is not the same as sharding. Replication copies the same data. Sharding splits different data.

02Concept: What is it?

One database on one machine is a risk. The disk can fail. The machine can crash. And one machine can only answer so many reads per second. So we run several copies of the database. Each copy is called a replica. Every write must reach every replica, and that copying work is what we call replication.

Leader and followers
✍️Writesapp
→↓write
👑Leaderprimary
→↓change log
📋Follower 1replica
📋Follower 2replica
📋Follower 3replica
→↓reads
👀Readersapp
Writes go to the leader. The leader sends every change to the followers. Reads can go to any of them.

The leader writes each change to a log (a list of changes in order). Followers read that log and apply the same changes in the same order. This is why they end up equal.

🧠Two big reasons
Availability (a copy survives a crash) and read scale (more machines can answer reads). Replication does not make writes faster, because every write still has to be applied on every copy.

03Real-Life Example

🍵The Class Notebook
A teacher writes the day's notes on the board. Three students copy them into their notebooks. If the teacher's board is wiped, the notes still live in the notebooks. And a new student can ask any of the three for the notes, so the teacher is not asked all day. But a slow student may not have finished copying the last line yet. If you ask that student, you get old notes.
Class notebook
Replication
The teacher and the board
The leader
Students copying the notes
Followers applying the change log
A wiped board
The leader crashes (failover)
Students asked for notes instead of the teacher
Reads served by followers
A slow student who is a line behind
Replication lag, a stale read
Teacher waits until every student is done
Synchronous replication
Teacher moves on without waiting
Asynchronous replication
Sync vs async, in one picture
Async
✍️1. Leader writes
↓2. say OK
📨3. copy later
Sync
✍️1. Leader writes
↓2. copy and wait
📨3. follower confirms
↓4. say OK
Async confirms early. Sync confirms only after the copy is safe.

04Why Do We Need It?

🛡️Survive failures
If a disk or machine dies, another copy takes over. No data is lost (if the copy was up to date).
📈Scale reads
Most apps read far more than they write. Followers share that read load.
🌍Be close to users
Put a replica in each region. Reads become local and fast.
🔧Maintenance without downtime
Upgrade or back up one replica while the others serve users.
📊Protect the main database
Run heavy reports on a follower, so users on the leader are not slowed.
♻️Disaster recovery
A replica in another region survives a whole data centre failure.
Replication buys you survival and read speed. It costs you freshness, because a copy can be a little behind.

05Where Do We Use It?

🗄️SQL databases
PostgreSQL, MySQL and SQL Server all have leader-follower replication built in.
📄Document stores
MongoDB uses replica sets: one primary and several secondaries.
🧱Wide-column stores
Cassandra keeps several copies of each row on different nodes (leaderless).
⚡Caches
Redis can run replicas for read scale and for failover.
📨Message brokers
Kafka copies each partition to other brokers so messages survive a crash.
☁️Cloud databases
Managed services offer read replicas and multi-zone copies with a few clicks.

06Types / Parts / How It Works

Three ways to organise the copies

ModelWho takes writes?Good and bad
Single leader (leader-follower)Only one leader. Followers are read-only.Simple. No write conflicts. The leader is one write bottleneck, and failover needs care.
Multi-leaderSeveral leaders, often one per region. They copy each other.Fast local writes in each region. Two leaders can change the same row, so you need conflict resolution.
LeaderlessAny node can take a write. The client writes to several nodes and reads from several.No single point of failure. You tune quorums (W + R > N) and accept fuzzy consistency (Dynamo, Cassandra style).
The three shapes
Single leader
👑Leader
↓
📋F
📋F
Multi-leader
👑Leader EU
↔
👑Leader US
⚠️conflicts possible
Leaderless
🟢N1
🟢N2
🟢N3
🧮write to W, read from R
Arrows show which node sends changes to which.

When does the leader say OK?

ModeLeader waits forSpeedSafety
AsynchronousNothing. It confirms at once.FastestA leader crash can lose the newest confirmed writes.
Semi-synchronousOne follower.MediumA second copy of every confirmed write exists.
SynchronousAll followers.SlowestStrongest. But one slow or dead follower stalls all writes.
📝How the change is shipped
Systems copy either statements (the SQL text), row changes (before and after values), or the physical write-ahead log (WAL, the raw disk changes). Row-based and WAL shipping avoid surprises like non-deterministic functions (NOW(), RAND()) giving a different answer on each copy.
VisualizerLeader, followers, lag and failoverClick Write a few times, then read from a follower. Switch to Sync and watch the wait grow. Kill the leader in Async mode right after a write.
When does the leader say 'done'?

The leader says 'done' at once and copies in the background. Fast writes, but a crash can lose the newest ones.

Read from
👑Leaderwrites: v0
⇢⇣30 ms
📋Follower 1copy: v0 (0 on the way)
⇢⇣60 ms
📋Follower 2copy: v0 (0 on the way)
Clock: 0 ms. A glowing node is the one you read from. Amber means behind the leader.
Write waits for
0 ms
network round trip
Replication lag
0 writes
behind, right now
Stale read?
no
reading follower 2
Writes lost
-
kill the leader to see
Press Write a few times. Watch how the followers catch up after the delay. Then read from a follower.

A simplified model with a simulated clock (no random numbers). Failover promotes the follower that is furthest ahead. Real databases add leader election, fencing and catching the old leader up when it returns.

07How to Use It / Steps / Implementation

Using replication well

  1. 1
    Start with a leader and two followers
    Three copies in different zones survive one failure and still have a majority for an election.
  2. 2
    Send reads to followers, writes to the leader
    Use a router or a driver setting. Remember that followers can be slightly behind.
  3. 3
    Pick sync or async on purpose
    A common choice is semi-sync: one nearby follower is synchronous, the rest are async.
  4. 4
    Give users read-your-writes
    After a user writes, read their data from the leader for a short time (or track the version they wrote).
  5. 5
    Monitor lag
    Alert when a follower is more than a few seconds behind. Remove very slow followers from the read pool.
  6. 6
    Plan failover
    Detect the dead leader with timeouts, elect the most up-to-date follower, point clients to it, and fence the old leader.
  7. 7
    Practise it
    Kill a leader in a test environment. Failover that has never been tried usually fails when you need it.
⚠️Split brain
If the old leader is only slow (not dead), it may come back and still think it is the leader. Now two nodes accept writes and the data forks. Use fencing (a token or epoch number) so the old leader is refused.
Typical goal: replica lagwell under one second

08Key Terms to Know

TermMeaning in easy words
ReplicaOne copy of the data on one machine
Leader / primary / masterThe node that accepts writes
Follower / secondary / standbyA node that copies the leader
Replication log (WAL)The ordered list of changes that followers apply
SynchronousThe leader waits for the copy before confirming
AsynchronousThe leader confirms first and copies later
Replication lagHow far a follower is behind the leader
FailoverPromoting a follower to leader when the leader fails
Split brainTwo nodes both think they are the leader
QuorumThe minimum number of nodes that must agree (W + R > N)
Read-your-writesYou always see your own recent changes

09Pros, Cons and Trade-offs

✅ Pros
  • Survives machine and disk failures
  • Scales reads by adding followers
  • Local reads in each region
  • Backups and reports without hurting users
  • Upgrades without downtime
⚠️ Cons
  • Followers can be stale (lag)
  • Does not scale writes
  • Failover is tricky (split brain, lost writes)
  • More machines and more cost
  • Multi-leader and leaderless need conflict handling

Trade-offs

ChoiceWe gainWe lose
Async replicationFast writes, tolerant of slow followersPossible data loss on a crash, stale reads
Sync replicationNo loss of confirmed writesSlower writes, lower availability
More followersMore read capacity, more safetyMore copying work for the leader, more cost
Read from followersOffloads the leaderStale reads
Multi-region replicasLocal reads, disaster recoveryLarger lag, harder conflicts
Multi-leaderFast writes everywhereConflict resolution complexity

10Common Problems and Mistakes

Common mistakes

  1. Reading your own write from a follower. A user posts a comment, refreshes, and it is missing. Route their reads to the leader for a while.
  2. Treating replication as a backup. A bad DELETE is copied to all followers in milliseconds. You still need point-in-time backups.
  3. Trusting async failover. A promoted follower may lack the last few writes. Know how much loss you accept.
  4. No lag monitoring. A follower can drift minutes behind and nobody notices.
  5. Expecting more write speed. Replicas do not fix a write bottleneck. Sharding does.
  6. Automatic failover with no fencing. This is how split brain happens.

Odd things users can see

🔙Time going backwards
Read 1 hits a fresh follower, read 2 hits a slower one, and data disappears. Fix with monotonic reads (stick to one replica).
🔀Out-of-order effects
An answer appears before the question it replies to. Fix with consistent prefix reads.
⏳Long lag after a burst
A big write or heavy query on a follower makes it fall behind.
🧯Lost writes on failover
Writes that only the dead leader had are gone. Some systems discard them quietly.

11Real-World Examples

🐘PostgreSQL
Streaming replication ships the WAL to standbys. Synchronous mode is optional per standby.
🐬MySQL
Binary-log replication with read replicas. Group Replication adds a consensus-based option.
🍃MongoDB
A replica set elects a new primary automatically if the primary stops responding.
🪐Cassandra and DynamoDB
Leaderless style: each item is stored on several nodes and read or written with a quorum.
☁️Amazon Aurora and RDS
Read replicas, and storage copied across several availability zones (general idea).
📨Kafka
Each partition has a leader and followers called in-sync replicas (ISR).
📝Note
These are general ideas. Defaults, names and guarantees change between products and versions.
Mini case: a read-heavy shop
👥Shoppers
→↓reads
📋F1zone A
📋F2zone B
📋F3zone C
←copy
👑Leaderorders
⇢⇣async, far away
🌍DR replicaother region
Leader Read followers Disaster recovery
One leader for orders, three followers for product pages, one in another region for disaster recovery.

12Related Topics to Read Next

CAP Theorem→

Replication is where the consistency vs availability choice shows up.

Sharding→

Splits data for write scale. Each shard is usually replicated too.

Partitioning→

Another way of dividing data. Compare it with copying data.

Availability→

Replicas are the main tool for staying up.

Single Point of Failure (SPOF)→

A lone database is one. Replicas remove it.

ACID Transactions→

Replication has to keep committed transactions safe.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: copies of the same data on several machines.
  • ✔Why: survive failures, scale reads, serve users nearby.
  • ✔Models: single leader (simple), multi-leader (local writes, conflicts), leaderless (quorums).
  • ✔Sync vs async: sync is safe but slow, async is fast but can lose and lag. Semi-sync is the middle.
  • ✔Lag: followers can be stale. Use read-your-writes, monotonic reads, and monitor lag.
  • ✔Failover: detect, elect the freshest follower, redirect, fence the old leader. Beware split brain.
  • ✔Not a backup: a bad delete is replicated too.
  • ✔One line: “Replication copies data for safety and read speed, and the price is that copies can be a little behind.”
← Previous
Partitioning
Next →
Sharding