Your application runs on one database server. Traffic grows, most of it reads: product pages, dashboards, search. The server's CPU climbs, and one day the disk fails and the whole product is down until someone restores a backup. Two problems, one common answer: keep more than one copy of the data. That is replication.
What replication is
Replication means keeping the same data on several database servers and keeping those copies in sync. The most common layout is primary and replicas (older docs say master and slaves):
- The primary accepts all writes:
INSERT,UPDATE,DELETE, schema changes. - The replicas receive a copy of every change from the primary and apply it in the same order. Applications can read from them, but not write to them.
This gives you two things. First, read scaling: reads can be spread over several replicas, so the primary has more room for writes. Second, availability: if the primary dies, a replica already holds almost all the data and can be promoted to become the new primary.
What it does not give you is write scaling. Every write still goes through one primary. If writes are your bottleneck, you need a different tool, such as sharding.
How changes travel from primary to replica
Databases already keep a log of changes for crash recovery. Replication reuses it.
- A client sends
UPDATE accounts SET balance = 90 WHERE id = 7to the primary. - The primary writes the change to its log before touching the data files. In PostgreSQL this is the write-ahead log (WAL). In MySQL, replication uses the binary log (binlog).
- The primary commits and answers the client.
- Each replica has a connection to the primary and receives new log records as they are written (streaming).
- The replica writes the records to its own disk and replays them, so its data files end up in the same state as the primary's.
There are two broad styles of log. Physical replication ships low-level changes ("these bytes on this page changed"), so the replica is a byte-for-byte copy of the whole server. PostgreSQL streaming replication works this way. Logical replication ships row-level changes ("row 7 in accounts now has balance 90"), which lets you replicate only some tables, or replicate between different major versions. MySQL's row-based binlog and PostgreSQL's logical replication are examples.
Synchronous or asynchronous
The key question is step 3: does the primary wait for the replica before telling the client the commit succeeded?
Asynchronous replication (the usual default): the primary commits locally and answers right away. Replicas catch up a moment later. Writes stay fast, and a slow or dead replica never blocks the primary. The cost: if the primary crashes, the last few transactions may not have reached any replica. Promote a replica, and those transactions are gone.
Synchronous replication: the primary waits until at least one replica confirms it has the change before answering. A committed transaction then exists on two machines, so failover loses nothing. The cost is latency on every write (one network round trip, at least), and if the synchronous replica goes down, writes can stall unless another replica takes its place.
Many setups mix the two: one synchronous replica in the same region for safety, and several asynchronous replicas for reads.
In PostgreSQL, this is controlled by settings such as synchronous_standby_names and synchronous_commit:
-- on the primary: wait for one of these standbys to confirm each commit
ALTER SYSTEM SET synchronous_standby_names = 'FIRST 1 (replica_a, replica_b)';
SELECT pg_reload_conf();
Replication lag
With asynchronous replicas, there is always some delay between a commit on the primary and the moment the replica shows it. That delay is replication lag. On a healthy system it is usually small, but it grows when:
- the primary has a burst of writes (a bulk import, a big migration);
- the replica's disk or CPU is slower than the primary's;
- a long query on the replica holds back replay (PostgreSQL may delay applying changes that conflict with a running query);
- the network between them is slow or saturated.
You can measure it. On a PostgreSQL primary:
SELECT client_addr, state, replay_lag
FROM pg_stat_replication;
On a PostgreSQL replica, now() - pg_last_xact_replay_timestamp() gives a rough age of the data. MySQL exposes a similar figure in SHOW REPLICA STATUS (Seconds_Behind_Source; older versions use SHOW SLAVE STATUS). Put lag on a dashboard and alert on it.
Why lag surprises users
Lag is harmless until your application reads from a replica right after writing to the primary. A concrete example:
- A user changes their display name. The request goes to the primary and commits.
- The app redirects to the profile page. That read is routed to a replica.
- The replica is 300 ms behind. The page shows the old name.
The user thinks the save failed and tries again. This breaks read-your-writes consistency. Other symptoms of the same cause: a comment that appears and then disappears when two reads hit two replicas with different lag, or a newly created order that returns "not found".
Common fixes:
- Read your own recent writes from the primary. After a user writes, route that user's reads to the primary for a few seconds (store a timestamp in the session or a cookie).
- Route by importance. Reads that must be fresh (checkout, account settings, anything followed by a decision) go to the primary. Reads that can be a little old (feeds, reports, search pages) go to replicas.
- Wait for the replica to catch up. Record the primary's log position after the write, and only read from a replica that has replayed past it. Some drivers and proxies support this.
- Stick a user to one replica, so they at least never go backwards in time.
Failover
When the primary fails, a replica is promoted. That sounds simple, but a few things need care:
- Pick the most up-to-date replica, so you lose as little as possible.
- Avoid split brain. If the old primary is not dead, only unreachable, and comes back thinking it is still primary, you now have two primaries accepting different writes. Failover tools use fencing and consensus to stop this. For PostgreSQL, tools like Patroni handle this; managed services do it for you.
- Repoint the application, through a virtual IP, DNS, or a proxy, so clients find the new primary.
- Rebuild the old primary as a replica once it returns.
Practice failover before you need it. A failover that has never been tested is a guess.
Common mistakes
-
Treating replicas as backups. A replica copies a
DROP TABLEas faithfully as anINSERT. You still need real backups, ideally with point-in-time recovery. - Reading from replicas without thinking about lag. Decide per query which reads may be stale.
-
Writing to a replica by accident. Replicas should be read-only (PostgreSQL standbys are; on MySQL set
read_onlyandsuper_read_only). - Ignoring long queries on replicas. Analytics queries on a replica can increase lag or get cancelled. Consider a separate replica for them.
- Assuming replicas make writes faster. They do not. They add a little work to the primary.
In short
- Replication keeps copies of your data on several servers: one primary takes writes, replicas follow its change log.
- It helps with read scaling and availability, not write scaling.
- Asynchronous replication is fast but can lose the last transactions on failover; synchronous replication is safer but adds write latency.
- Replication lag is normal. Measure it, and route reads that must be fresh to the primary.
- Failover needs fencing to avoid split brain, and regular practice.
- A replica is not a backup.
Watch the animated version: https://youtu.be/XaetUe-Laz8
Originally published at abdeldjalilchougui.biz.
Top comments (0)