Skip to content

Replicas: copying data for reads and safety

Working knowledgeUnder the hood

One database on one machine is one failure away from an outage, and it can only serve so many reads. Replicas fix both, but every replica is a little behind the leader, and that delay shows up in places you would not expect.

01 One leader, several copies

In leader-follower replication, one node, the leader (Postgres calls it the primary), takes every write. Before it changes its data files, it appends each change to a log: the write-ahead log (WAL) in Postgres, the binary log in MySQL. The replicas (followers, standbys) receive that log and replay it in the same order, so they end up with the same data.

A leader and two replicas, mid-stream
Leader · WAL
#10
#21
#32
#43
Replica A · WAL
#10
#21
#32
#43
Replica B · WAL
#10
#21
#32
3
  • last entry replayed
  • not received yet

The replicas hold the same log, just shorter. How much shorter is the replication lag.

  • More reads: send read-only queries to replicas, and the leader keeps its capacity for writes.
  • A spare: if the leader dies, a replica already has (almost) all the data and can take over.
  • Not more writes: every write still goes through the one leader, and every replica replays all of it. Spreading writes needs sharding.

02 A write, step by step

Ana’s balance changes from 50 to 80. The app writes to the leader and reads from whichever replica the load balancer picks. Here is the default setup in Postgres and MySQL: asynchronous replication.

Asynchronous replication and a stale read
Step 1 of 7
Replica B behind 0
Leader · WAL
bal=500
1
2
3
Replica A · WAL
bal=500
1
2
3
Replica B · WAL
bal=500
1
2
3
Client sees
Empty
  • just written
  • read from
  • stale answer
  • fresh answer
  • not received yet

All three copies have replayed the same log: Ana’s balance is 50. The client has not done anything yet.

0 replica A behind

03 Replication lag

On a healthy network the lag is typically well under a second. It grows when a replica is busy, when the network is slow, or when the leader writes in large bursts, and it can reach minutes. Two symptoms show up in apps:

  • Your own write vanishes. A user saves, the page reloads from a lagging replica, and the old value is back. Fix: read a user’s own data from the leader for a short while after they write, or record the leader’s WAL position after the write and only use a replica that has replayed past it.
  • Time runs backwards. Two reads in a row hit two replicas with different lag, so a comment appears and then disappears. Fix: pin each user’s reads to one replica.

In Postgres (10 and later), ask the primary how far each replica is behind:

SQL
SELECT application_name, state, sync_state, replay_lag
FROM pg_stat_replication;
Text
application_name | state | sync_state | replay_lag
------------------+-----------+------------+-----------------
replica_a | streaming | async | 00:00:00.000812
replica_b | streaming | async | 00:00:02.41733

For the read-your-writes check, pg_current_wal_lsn() on the primary gives the position after your write, and pg_last_wal_replay_lsn() on a replica says how far it has replayed.

04 Synchronous or asynchronous

The trace showed the leader acknowledging a write before any replica had it. That is fast, but if the leader dies at that moment, the write exists nowhere else. You can make the leader wait.

AsynchronousAck after 1 copyFastest commits. A leader crash can lose writes that were already acknowledged.
SynchronousAck after 2 copiesNo acknowledged write is lost if one node dies. Every commit waits a network round trip, and if that replica is down, commits stall.
QuorumAck after any 1 of 2Waits for whichever replica answers first, so one slow or dead replica does not stop writes.
postgresql.conf
synchronous_commit = on
synchronous_standby_names = 'ANY 1 (replica_a, replica_b)'

In Postgres, synchronous_commit = on waits until the replica has flushed the WAL to disk, not until it has replayed it. A read from that replica straight after the commit can still be stale. Only remote_apply waits for replay, and it is slower again.

05 Failover: a replica takes over

When the leader dies, something has to notice, pick a replica, promote it, and send clients to it. Postgres does not do this on its own; tools such as Patroni or a managed service’s control plane do. Here is a failover with asynchronous replication.

The leader dies; the most up-to-date replica takes over
Step 1 of 7
Node 1 · WAL
#10
#21
#32
#43
Node 2 · WAL
#10
#21
#32
3
Node 3 · WAL
#10
#21
2
3
Failover log
Empty
  • unreachable or discarded
  • furthest ahead
  • compared
  • just happened
  • no entry

Node 1 leads. It has committed entries #1 to #4 and acknowledged all four to clients. Replication is asynchronous: node 2 has replayed up to #3, node 3 up to #2.

Node 1 leader

06 When failover bites

Two leaders at onceThe old leader was only cut off, not dead, and keeps accepting writes while a replica is promoted. This is split brain: two histories that cannot be merged. Fence the old leader (cut its power or network, or reject writes with an old term number) before promoting.
Acknowledged writes are lostWith asynchronous replication, whatever the dead leader had not shipped is gone, as #4 was in the trace. If that is not acceptable for some data, use synchronous or quorum commits for it.
The timeout is wrongToo short and a brief network blip triggers a needless failover, with its own lost writes. Too long and you are down for the whole wait. Typical settings are tens of seconds; measure yours.
Clients still call the old addressApps and connection pools cache the leader’s address. Point them at a proxy, a virtual IP, or a DNS name with a short TTL, and make sure they reconnect on error.
DELETE FROM orders;Replicas copy your mistakesA bad delete on the leader reaches every replica within the lag. Replication protects against a dead machine, not against a wrong query.

A replica is not a backup. Keep real backups with point-in-time recovery. A deliberately delayed replica (recovery_min_apply_delay in Postgres) can also buy time to stop a mistake before it lands.

07 Check yourself

Question

A user renames their profile, the page reloads and shows the old name. Reads go to asynchronous replicas. What is most likely?

Question

With asynchronous replication, the leader acknowledges write #4 and dies before sending it anywhere. A replica is promoted. Where is #4?

Question

Someone runs DELETE FROM orders with no WHERE on the leader. You have two replicas. Can you promote one to get the orders back?

08 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?