Video in progress
What is the difference between synchronous and asynchronous mode in streaming replication, and what problem does replica lag cause in the application?
In asynchronous mode the primary confirms a commit immediately and the WAL reaches the replica later: it's fast, but on failover the last transactions may be lost. In synchronous mode the commit waits for the replica's confirmation. Because of lag, a user who reads data they just wrote from a replica may not see it.
📖 Answer
The primary writes every change to the WAL, and the replica receives the WAL as a stream and replays it. synchronous_commit and synchronous_standby_names set the mode:
| Value | What the commit waits for |
|---|---|
off |
doesn't even wait for the local disk flush |
local |
only the primary's disk |
remote_write |
the replica wrote it to the OS |
on |
the replica flushed it to disk |
remote_apply |
the replica replayed it, so reading from it is safe |
If a synchronous replica goes down, commits on the primary hang. That's why a quorum like ANY 1 (r1, r2) is usually configured.
A typical application bug is read-after-write:
POST /profile -> written to the primary
redirect GET -> read from the replica, lag 300ms -> the old name shows up
The solutions:
- for a few seconds after a write, route that user's requests to the primary;
- always read critical data from the primary;
- remember
pg_current_wal_lsn()on the primary and check thatpg_last_wal_replay_lsn()on the replica has reached it.
To watch the lag: pg_stat_replication (replay_lag) on the primary, and now() - pg_last_xact_replay_timestamp() on the replica. Lag usually grows because of a big batch update, a slow disk, or a long query on the replica.
Sign up to mark studied questions and save your progress.