Video in progress

Strong Junior 🏗️ System design

A user saved their profile and the page reloaded, but the old name is shown. A few seconds later everything is fine. What's happening?

This is replication lag: the write went to the primary, but the read was served by a replica that hasn't caught up yet. The fix is a read-your-writes guarantee: for a short time after a change, send that user's reads to the primary.

📖 Answer

With asynchronous replication, the primary first saves the change itself and then sends it to the replicas. Usually this takes milliseconds, but if a replica is busy or a heavy query is running, it can be seconds, sometimes even minutes.

Nobody minds a stranger's profile looking 2 seconds stale. But losing something you just saved feels like "the site is broken", and the user keeps clicking "Save" over and over.

Practical solutions:

  • when users read their own profile, orders and settings — always use the primary;
  • after a write, put a timestamp in the session and send that user's reads to the primary for, say, the next 10 seconds;
  • return the updated object in the save response — the client doesn't have to ask again.

You need to monitor the lag as well. In PostgreSQL, on the replica:

SELECT now() - pg_last_xact_replay_timestamp() AS lag;

If the lag keeps growing, that's a reason to alert.