PostgreSQL and MySQL inside · mid
Replication and read-after-write problems
A replica applies changes a little after the primary commits them. A read right after a write can hit the replica too early and show old data. You must know how to measure the lag and how to route reads.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Replication is asynchronous by default: the primary commits and returns, and the replica applies the change later.
- PostgreSQL ships its write-ahead log (WAL) to replicas. MySQL ships its binary log. Both can fall behind during heavy writes.
- Measure lag: pg_stat_replication.replay_lag on the primary, or now() - pg_last_xact_replay_timestamp() on a replica. In MySQL use SHOW REPLICA STATUS.
- The classic bug: a user saves an address, the next page reads from a replica, and shows the old value. It fixes itself a few seconds later.
- Quick fix: read the user's own recent data from the primary for a few seconds after a write, or return the saved data in the write response.
- Better: route by need in one data-access layer. Balances and payments always read from the primary. Pages that can be a little old read from replicas.
- Synchronous replication (synchronous_commit = remote_apply in PostgreSQL) makes the write visible on the replica before the commit returns. The cost: every commit waits for the replica, and a slow replica slows or stops writes.
- A common cause of lag at night: one huge DELETE in a single transaction. Delete in small batches with pauses. MySQL parallel replication workers help a replica keep up.
The red pen
Common traps: mistake → fix
Mistake: Read replicas always show the latest data
Fix: they can be seconds behind, or more.
Mistake: Send every read to the primary to be safe
Fix: you lose the reason for having replicas.
Mistake: Add a sleep after the write
Fix: lag is not constant; fix the routing instead.
Easy to hard
Questions interviewers ask, easy to hard
- What is replication lag and how do you measure it?
- A user updates a profile but sees the old value. Reads go to a replica. What do you do?
- Which reads must never use a replica?
- What does synchronous replication cost?
Practise
Practise with these questions
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.