Video in progress

A user saved their profile, but after the page reloaded the old data showed up. Why does this happen with a read replica, and how do you fix it?

Streaming replication is usually asynchronous: after the master commits, the WAL reaches the replica a little later. If the write goes to the master and the next read lands on a replica that is still behind, the user doesn't see their own change. Reads that need read-your-writes must go to the master.

📖 Answer

Replication lag is usually milliseconds, but during a heavy migration, a big batch, or a long query on the replica, it reaches seconds and minutes.

Measuring the lag:

-- on the master
SELECT client_addr, state,
       write_lag, flush_lag, replay_lag
FROM pg_stat_replication;

-- on the replica
SELECT now() - pg_last_xact_replay_timestamp() AS lag;

Note that the last query shows a large lag even when there are no writes.

Practical solutions, from simple to complex:

  1. The writing user's reads go to the master. For example, for 5 seconds after a write, that user's session reads from the master (using a cookie or a session flag).
  2. Routing by transaction type. In Spring, AbstractRoutingDataSource + @Transactional(readOnly = true) goes only to the replica. But "save and immediately show it back" should happen in a single writing transaction.
  3. Waiting by LSN. After a write, remember pg_current_wal_lsn(), and read from the replica only once its pg_last_wal_replay_lsn() is ahead of that. Precise, but complicated.
  4. Synchronous replication (synchronous_commit = remote_apply): a commit doesn't return until the replica has applied it. It gives a guarantee, but every write gets slower, and if the replica goes down, writes stop.

I don't send important reads like money, balance or order status to a replica at all. A replica is for catalogs, search and reports.