Replication keeps copies of the same data on several machines. It is how databases survive machine failures, serve more reads than one server could, and put data close to users around the world. Copying static data is easy; the hard part is keeping copies in sync while the data changes, and every replication design is a trade-off between consistency, write latency and availability.
Think of it like
A head chef calling out recipe changes
Only the head chef (the leader) may change a recipe, and they call each change out to the line cooks (followers), who update their own copies in the same order. A cook who missed the last call serves yesterday's version (replication lag). If the head chef walks out, the kitchen must agree on a new one quickly, and must make sure the old chef doesn't come back still shouting orders (split brain).
Why replicate
- High availability: if one node dies, another copy keeps serving. See Availability & Reliability.
- Read scaling: spread read traffic across many replicas.
- Lower latency: place replicas near users in other regions.
- Durability and disaster recovery: a copy in another zone or region survives the loss of a data center.
- Isolation of heavy work: run analytics, reports and backups against a replica instead of the primary.
Leader-follower replication
The most common design: one node is the leader (primary) and accepts all writes. It records each change in its replication log and streams it to followers (replicas, secondaries), which apply the changes in the same order. Reads can go to the leader or any follower. PostgreSQL streaming replication, MySQL replication, MongoDB replica sets, Redis replicas and Kafka partitions all work this way.
The simulation above lets you adjust replication delay and watch followers fall behind. Press play below to compare a safe semi-synchronous write with a stale read from a lagging replica.
Synchronous, asynchronous and semi-synchronous
Synchronous
- The leader waits for followers to confirm before acknowledging
- No acknowledged write is lost if the leader dies
- Write latency is set by the slowest follower
- One slow or dead follower can stall all writes
Asynchronous
- The leader acknowledges immediately and replicates in the background
- Fastest writes; followers can be far away
- A failover can lose the most recent acknowledged writes
- The default for MySQL and PostgreSQL replicas
Semi-synchronous
- Wait for at least one follower (or any one of a set), not all of them
- Every acknowledged write exists on two nodes
- Tolerates a slow follower as long as another one answers
- MySQL semi-sync; Postgres
synchronous_standby_names = 'ANY 1 (...)'
wal_level = replica
max_wal_senders = 10
synchronous_commit = on # remote_apply also waits until the standby has applied it
synchronous_standby_names = 'ANY 1 (replica_a, replica_b)'How changes are shipped: replication logs
| Method | What is sent | Pros | Cons | Used by |
|---|---|---|---|---|
| Statement-based | The SQL statements themselves | Compact | Nondeterminism (NOW(), RAND(), auto-increment, triggers) makes replicas diverge | Early MySQL (binlog_format=STATEMENT) |
| Physical / WAL shipping | Low-level storage changes: which bytes changed in which disk page | Exact copy; simple and fast | Tied to the storage format and version; whole cluster only; can't feed other systems | PostgreSQL streaming replication, Oracle Data Guard (physical) |
| Logical / row-based | Per-row changes: inserted row, old and new values of updated rows, deleted keys | Independent of storage format; allows cross-version upgrades, per-table replication and CDC | Larger volume for bulk updates | MySQL binlog_format=ROW (default since 5.7.7), Postgres logical replication, Debezium |
| Trigger-based | Changes captured by triggers into a side table | Flexible filtering and transformation | Overhead on every write; fragile | Legacy tools such as Slony-I |
Replication lag and its anomalies
Asynchronous followers are always slightly behind: usually milliseconds, but seconds or minutes during load spikes, network trouble or long-running queries on the replica. Reading from them produces three classic anomalies. See Consistency Models for the formal definitions.
| Anomaly | What the user sees | Fixes |
|---|---|---|
| Read-your-writes (read-after-write) | Posts a comment, refreshes, and it's gone | Read the user's own recently changed data from the leader (e.g. for a minute after a write); or record the write's log position and only read from replicas that have replayed past it |
| Monotonic reads | Refreshes and sees a new comment, refreshes again and it vanishes (the second read hit a more lagged replica) | Pin each user to one replica (hash the user ID); or track the highest log position seen and require replicas at least that far along |
| Consistent prefix reads | Sees an answer before the question it replies to (causally related writes arrived out of order, often from different partitions) | Write causally related data to the same partition; track causal dependencies (version vectors) |
Failover and split brain
- 1
Detect the failure
Followers or an orchestrator notice missing heartbeats. Timeouts are a trade-off: too short causes needless failovers during load spikes, too long means minutes of downtime. See Heartbeats & Gossip Protocols.
- 2
Choose a new leader
Prefer the most up-to-date follower. The choice should be made by a consensus system (Patroni with etcd, MongoDB's Raft-based elections) so only one candidate can win.
- 3
Reconfigure clients
Writes must reach the new leader: update service discovery, a proxy or a virtual IP. Other followers start replicating from it.
- 4
Fence the old leader
If the old leader comes back it must not accept writes. Epoch (term) numbers, leases and STONITH ("shoot the other node in the head") stop it.
Split brain happens when two nodes both believe they are the leader and both accept writes, so the data diverges. It is caused by network partitions or long pauses (a GC pause or VM freeze longer than the timeout). The defenses are majority-based elections (only one side of a partition can hold a majority), fencing tokens (a monotonically increasing epoch sent with every write, so storage rejects writes from a stale leader) and leases with bounded clocks. See Consensus: Raft & Paxos.
Multi-leader replication
With multi-leader (active-active) replication, several nodes accept writes, typically one leader per region, and replicate to each other asynchronously. Each region gets local write latency and keeps working if another region goes down. Offline-first apps are an extreme case: every device is a leader that syncs later (calendars, note apps, CouchDB). The unavoidable cost is write conflicts.
Conflict resolution strategies
| Strategy | How it works | Trade-off |
|---|---|---|
| Avoid conflicts | Route all writes for a record to its "home" leader (e.g. the user's region) | Conflicts only during failover or home changes; the simplest option when it fits |
| Last-writer-wins (LWW) | Highest timestamp wins, ties broken by node ID | Simple and convergent, but silently drops concurrent writes, and clock skew can pick the wrong winner (Cassandra uses LWW per cell) |
| Version vectors + siblings | Detect true concurrency and keep both versions for the app or user to merge | No silent loss; the application must handle merges (Riak, Dynamo's shopping cart) |
| CRDTs | Data types whose merge is commutative, associative and idempotent: counters, sets, maps, text sequences | Automatic, mathematically correct merges; limited to supported types, with metadata overhead (Riak data types, Redis Enterprise Active-Active, Automerge, Yjs) |
| Custom merge logic | Application handlers run on write or on read | Flexible but easy to get wrong (CouchDB) |
The simplest CRDT is a grow-only counter (G-Counter): each replica increments only its own slot, and merging takes the maximum of each slot. Replicas can count independently during a partition and always agree after syncing, in any order, any number of times. The implementation appears at the end of this page.
Leaderless replication
Dynamo-style systems (Amazon's Dynamo paper, Cassandra, ScyllaDB, Riak) have no leader. A client or coordinator sends each write to all N replicas of a key and waits for W acknowledgements; reads ask R replicas and keep the newest version. If the read and write sets must overlap, every read sees at least one copy of the latest write. See Quorums & Leaderless Replication for the details.
Choosing a replication model
| Model | Writes go to | Consistency | During a partition | Examples |
|---|---|---|---|---|
| Single leader, sync or semi-sync | One leader | Strong when reading from the leader | Writes stop if the leader is unreachable | PostgreSQL, MySQL, MongoDB with majority writes |
| Single leader, async | One leader | Replicas are eventually consistent | Writes stop; recent writes may be lost on failover | Typical read-replica setups, Redis |
| Multi-leader | A leader per region or device | Eventual, with conflicts to resolve | Every region keeps accepting writes | Active-active multi-region, CouchDB, offline-first apps |
| Leaderless (quorum) | Any W of N replicas | Tunable via R and W | Stays available while a quorum (or sloppy quorum) is reachable | Cassandra, ScyllaDB, Riak, DynamoDB's ancestor Dynamo |
| Consensus (Raft, Paxos) | A leader, committed by a majority | Linearizable | Only the majority side makes progress | etcd, CockroachDB, Spanner, TiKV |
Implementation
After a write, remember the leader's WAL position. Later reads use a replica only if it has replayed at least that far; otherwise they fall back to the leader. Users without recent writes stick to one replica for monotonic reads.
import psycopg
leader = psycopg.connect(LEADER_DSN, autocommit=True)
replicas = [psycopg.connect(dsn, autocommit=True) for dsn in REPLICA_DSNS]
def rename_user(session: dict, name: str) -> None:
leader.execute("UPDATE users SET name = %s WHERE id = %s", (name, session["user_id"]))
# The UPDATE has committed, so the current WAL position is past its commit record
lsn = leader.execute("SELECT pg_current_wal_lsn()::text").fetchone()[0]
session["min_lsn"] = lsn
def get_user(session: dict):
sql = "SELECT id, name FROM users WHERE id = %s"
min_lsn = session.get("min_lsn")
if min_lsn is None:
replica = replicas[session["user_id"] % len(replicas)] # sticky => monotonic reads
return replica.execute(sql, (session["user_id"],)).fetchone()
for replica in replicas:
caught_up = replica.execute(
"SELECT pg_last_wal_replay_lsn() >= %s::pg_lsn", (min_lsn,)
).fetchone()[0]
if caught_up:
return replica.execute(sql, (session["user_id"],)).fetchone()
return leader.execute(sql, (session["user_id"],)).fetchone() # fall back to the leaderKey takeaways
- Replication provides availability, read scaling, lower latency and disaster recovery, but it is not a backup.
- Leader-follower is the default: synchronous replication avoids data loss at the cost of latency, asynchronous is fast but can lose writes on failover, and semi-sync balances the two.
- Logical (row-based) logs beat statement-based ones and double as a CDC stream; physical WAL shipping makes exact copies.
- Replica lag causes read-your-writes, monotonic-read and consistent-prefix anomalies; fix them with leader reads, sticky replicas or log-position tracking.
- Failover needs consensus-based leader election and fencing to prevent split brain.
- Multi-leader and leaderless designs stay writable during failures but must resolve conflicts (LWW, version vectors, CRDTs) or rely on quorums (W + R > N).
Common pitfalls
- Reading from async replicas right after a write and showing users stale data.
- Promoting an out-of-date follower and silently losing (or reusing IDs from) acknowledged writes.
- Failover without fencing, letting a returning old leader accept writes alongside the new one.
- Using last-writer-wins without realizing it discards concurrent writes and depends on clock accuracy.
- Treating replicas as backups and having no point-in-time recovery.
Interview tips
- Always say whether replication is sync, async or semi-sync, and what that means for data loss on failover.
- When you add read replicas, immediately address read-your-writes for the user who just wrote.
- For multi-region writes, say how conflicts are avoided or resolved; "LWW" should come with its caveats.
Real-world applications
- Read replicas to scale read-heavy web applications.
- Hot standbys in another availability zone for high availability.
- Cross-region replicas for disaster recovery and local reads.
- Active-active multi-region databases for global write availability.
- CDC from the replication log into caches, search and analytics.
Test yourself
With asynchronous leader-follower replication, what can happen when the leader crashes and a follower is promoted?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.