Scrivio Interview library
DebuggingFoundations6 min read · updated 12 November 2026

After a user updates their address, the profile page sometimes shows the old address. The service reads from a PostgreSQL replica. How do you confirm replication lag is the cause, and what quick fixes exist?

The profile page reads from a replica that has not yet replayed the update, so we confirm it by measuring lag, write_lag, flush_lag and replay_lag in pg_stat_replication on the primary, or now() - pg_last_xact_replay_timestamp() on the replica, and matching stale reads to lag spikes. The quick fix is read-your-writes: send a user's reads to the primary for a few seconds after that user writes, or always read a user's own data from the primary. In Spring, a routing DataSource that sends every readOnly transaction to a replica must not do so blindly after a write.

Why this question is asked

This is one of the most common bugs in systems that scale reads with replicas. A user saves a new address, the page refreshes, and the old address is still there. They save again, or call support, and the trust in the product drops a little. The database is not broken; the service is reading from a copy that is a moment behind. Interviewers ask this to see whether we can prove a cause instead of guessing, and whether we know fixes that do not throw away the benefit of replicas. In this answer, we will recap why replicas lag, measure the lag, connect it to the bug, apply two quick fixes and look at the Spring routing trap.

1A Quick Recap: Why a Replica Can Be Behind

A PostgreSQL read replica, a hot standby, receives the primary's WAL, the log of changes, and replays it. With the default asynchronous replication, the primary confirms our UPDATE as soon as it is durable locally, and the replica applies it a little later, usually within milliseconds.

The gap between the two is replication lag. It grows when the replica cannot keep up: a large batch job on the primary produces WAL faster than the replica can replay it, a long query on the replica holds back replay, or the network between them is slow. During that gap, any read sent to the replica returns the old row.

Step throughHow the old address comes back
BrowserServicePrimaryReplica
PUT /profile/address
UPDATE address, COMMIT
200 OK
GET /profile
SELECT address
old address, update not replayed yet
WAL with the update arrives later

7 messages in order. Play them, or step through them one at a time.

The write succeeded; the read simply went to a copy that had not caught up.

2Measuring the Lag

Before fixing anything, we confirm the theory. On the primary, pg_stat_replication has one row per standby with three lag columns. write_lag is the time until the standby wrote the WAL, flush_lag until it flushed it to disk, and replay_lag until it applied it, which is the one that matters for reads.

SQL
-- on the primary
SELECT application_name, write_lag, flush_lag, replay_lag,
pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS bytes_behind
FROM pg_stat_replication;
-- replica1 | 00:00:00.002 | 00:00:00.003 | 00:00:04.812 | 52428800
-- on the replica
SELECT now() - pg_last_xact_replay_timestamp() AS replay_delay;
-- 00:00:04.9

Here the replica receives WAL quickly but is almost five seconds behind in replaying it, with 50 MB of WAL waiting. Notice one subtlety of the replica-side query: it measures time since the last replayed transaction, so on a quiet system with no writes it grows even though nothing is waiting. Comparing LSNs, the log positions, avoids that false alarm.

3Connecting Stale Reads to Lag Spikes

Now we graph replay lag over time next to the reports of stale reads, or better, next to a metric the service emits when it detects one. If stale reads cluster at times when lag jumps from milliseconds to seconds, we have our cause. Typical culprits show up in the same graphs: a nightly import or a large UPDATE on the primary, a reporting query on the replica that runs for minutes and delays replay, a vacuum of a big table, or network trouble between zones.

Notice that lag is not the bug by itself. Some lag is normal and unavoidable with asynchronous replicas. The bug is that the service sends a read that needs fresh data to a place that may not have it. So we fix the routing, and separately reduce the spikes.

4Quick Fix 1: Stick to the Primary After a Write

The simplest fix is to remember that a user has just written and to send that user's reads to the primary for a short window, a few seconds longer than normal lag. We can keep the timestamp in the HTTP session, in a signed cookie, or in a cache keyed by user id when several service instances serve the same user.

Java
@Component
class RecentWrites {
private final Cache<String, Instant> lastWrite =
Caffeine.newBuilder().expireAfterWrite(Duration.ofSeconds(10)).build();
void markWrite(String userId) { lastWrite.put(userId, Instant.now()); }
boolean mustReadPrimary(String userId) {
Instant t = lastWrite.getIfPresent(userId);
return t != null && t.isAfter(Instant.now().minusSeconds(5)); // true for 5 s after a write
}
}

A local cache like this only works if the same instance serves the user's next request; with many instances, the marker belongs in Redis or in a cookie. The window is a trade-off: if lag ever exceeds it, the stale read returns, so we pick a window above our normal lag and keep alerting on lag beyond it.

5Quick Fix 2: Read Your Own Data From the Primary

An even simpler rule fits a profile page well: reads of a user's own data, which they may just have changed, always go to the primary, while reads of other data, such as product listings or other people's public profiles, go to replicas. The user's own profile is a tiny share of total read load, so the primary hardly notices, and the bug disappears entirely rather than becoming rare.

6The Spring Routing Trap

Many Spring services route with an AbstractRoutingDataSource that picks the replica whenever the current transaction is read-only. The trap is that @Transactional(readOnly = true) describes the transaction, not the freshness the caller needs. The profile query is read-only, so it goes to the replica right after the write.

Java
class ReplicaRoutingDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
boolean readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
if (readOnly && !FreshRead.required()) return "replica"; // FreshRead set by the caller
return "primary";
}
}
// wrap it: new LazyConnectionDataSourceProxy(routing), so the key is read after the
// transaction's readOnly flag is set, not when the connection is first requested

So the routing decision needs a second input, for example a request-scoped flag set when the user wrote recently or when the code reads the user's own data. The comment in the code points at a second, quieter trap: without LazyConnectionDataSourceProxy, the transaction manager asks for a connection before the read-only flag is set, and everything routes to the primary.

7Follow-up questions

Would synchronous replication fix this?

Only with synchronous_commit = remote_apply, which makes the commit wait until the replica has replayed the change. That fixes stale reads for that replica but adds replay time to every commit and blocks writes if the replica is down. For a profile page, routing a few reads to the primary is far cheaper.

Why not just send all reads to the primary?

Because the replicas exist to carry read load. If the primary could serve everything, we would not need them. Read-your-writes rules keep the small share of reads that need freshness on the primary and leave the rest on replicas.

How do you reduce the lag spikes themselves?

Break large batch writes into smaller transactions, schedule them off peak, keep long reporting queries off the replicas that serve the application, and check that the replica's disk and CPU can keep up with replay. Lag spikes will still happen, which is why the routing fix comes first.

8Conclusion

In this answer, we saw that the old address comes from a replica that has not replayed the update yet. We confirmed it with replay_lag in pg_stat_replication or now() - pg_last_xact_replay_timestamp() on the replica, and by matching stale reads to lag spikes. The quick fixes are sticky primary reads for a few seconds after a user writes, or always reading a user's own data from the primary, and in Spring the routing DataSource needs more than the readOnly flag to decide.

What to say in the interviewAbout 80 seconds aloud

Open with

My first suspicion would be that the read goes to a replica that has not replayed the update yet, but I would prove it. On the primary I would look at pg_stat_replication, where replay_lag shows how far each replica is behind in applying WAL, and also the byte difference between pg_current_wal_lsn() and replay_lsn.

Then, if they want more

On the replica, now() - pg_last_xact_replay_timestamp() gives a quick estimate, though it grows on an idle system. Then I would graph lag next to the stale-read reports. If they line up with lag spikes, often from a big batch write, a long query on the replica or network trouble, that is the cause. The quick fix is read-your-writes.

Either remember that the user wrote and send their reads to the primary for a few seconds, stored in a cookie or Redis so any instance knows, or simply route a user's own profile reads to the primary, which is a tiny part of the load.

In Spring I would check the routing DataSource: if it sends every readOnly transaction to a replica, it will keep doing this, so it needs a freshness flag too, and it must be wrapped in LazyConnectionDataSourceProxy so it sees the readOnly flag at all. Separately I would reduce the spikes by chunking batch jobs.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "After a user updates their address, the profile page sometimes shows the old address....": https://scrivio-interview-library.netlify.app/databases/replication-and-ha/323201ce06/