← System Design
Core Concepts

What is Database Replication?

Database replication means keeping copies of the same data on multiple machines (replicas). Writes go to one or more nodes and are copied to the others. It gives you more read capacity, survival when a machine dies, and data closer to users in other regions.

In simple words

Like keeping photocopies of an important register in several offices. If one office burns down the data survives, and several people can read copies at once. The copies are updated from the original, so for a moment a copy might be a little behind.

Single-leader replicationApplicationPrimaryReplica 1Replica 2writesloglogreads
Writes go to the primary; replicas copy its log and serve reads (possibly a little behind).

Why It Exists

How It Works

Single-leader (primary/replica), the most common:
        writes
   app ------> [ primary ] --replication log--> [ replica 1 ]  <- reads
                                            \-> [ replica 2 ]  <- reads

sync replication:  primary waits for replica ack -> no loss on failover, slower writes
async replication: primary acks immediately      -> fast, but replicas lag and the
                                                     last writes can be lost on failover

Types

Replication Lag and What Users See

With async replicas, a read may hit a replica that hasn't received the latest write. The classic bug: a user updates their profile, the page reloads from a replica, and the old value appears. Fixes: read-your-writes (read from the primary for a user shortly after they write, or route by a replication position), monotonic reads (keep a user on the same replica).

Key Pointers

Follow-up Questions

Replication vs sharding?
Replication = same data on many nodes (availability, read scale). Sharding = different data on different nodes (write scale, data size). Large systems do both: each shard is replicated.
A user sees their old profile right after saving. Why and how do you fix it?
Replication lag: the read went to a replica that hadn't caught up. Route that user's reads to the primary for a short window after a write, or wait until the replica has reached the write's log position.

Related