29 / 32 · 5 min
More than one copy
One database server is a single point of failure and a ceiling on read capacity. Replication addresses both, and introduces a new problem.
How it works
The primary accepts writes. Each change is streamed to one or more replicas as log records, and each replica applies them in order. A replica is a full copy, continuously catching up.
writes -> PRIMARY -> log stream -> REPLICA 1 -> reads
-> REPLICA 2 -> readsWhat it buys
Read capacity. Most applications read far more than they write, so sending reads to replicas moves the majority of the load off the primary.
Failover. If the primary fails, a replica is promoted. This is a real benefit and not automatic: something must detect the failure and decide, and deciding wrongly gives you two primaries accepting conflicting writes, which is worse than an outage.
Backups and reporting can run on a replica without slowing the primary.
Replication lag
A replica is always slightly behind. Usually milliseconds, sometimes much more under load or a long transaction.
That produces the bug everyone hits:
user submits a change -> written to primary
page redirects and reloads -> read from replica
replica has not caught up -> the user sees their old dataThe user did everything right and the system appears to have lost their work.
Fixes, in order of preference: read from the primary for a short window after a write by that user; or read their own data from the primary always; or wait for the replica to reach the write position before reading.
Synchronous, and what it costs
A synchronous replica must confirm before the primary commits, so no committed write can be lost. The cost is that every write now waits for a network round trip, and if the replica is slow or unreachable, writes stall.
| Asynchronous | Synchronous | |
|---|---|---|
| Write latency | unaffected | includes the replica |
| Data loss on failover | possible | none |
| Replica down | writes continue | writes may stop |
One thing it does not fix
Replication copies everything faithfully, including a DELETE with no WHERE. It is not a backup, and treating it as one is a recurring and expensive mistake.