Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

Users sometimes update their profile and then see the old value on refresh. The service writes to a primary and reads from replicas. Name the consistency guarantee that is missing and three ways to provide it.

The missing guarantee is read-your-writes, also called session consistency: after a user writes, their own later reads should see that write. The service writes to the primary but reads from asynchronous replicas that lag behind, so a refresh can hit a replica that has not applied the update yet. Three ways to provide it are routing that user's reads to the primary for a short time after a write, tracking the write's position in the log and reading from a replica only once it has caught up, and returning the updated data in the write response so the client does not re-read at once; and we monitor replica lag, because every workaround degrades when lag grows.

Why this question is asked

Read replicas are the standard way to scale reads in PostgreSQL and MySQL, and Spring makes routing reads to them easy. The cost is a subtle bug that users notice immediately: they save their profile, the page reloads, and their old name is still there. Interviewers ask this to see whether we can name the consistency guarantee involved and fix it without giving up the replicas. In this answer, we will reproduce the problem, name the guarantee, and then go through three fixes in detail, with their costs, before finishing with replica lag monitoring.

1Reproducing the Problem

The service uses a routing data source: methods marked @Transactional(readOnly = true) go to a replica, others go to the primary. Replication is asynchronous: the primary commits, then streams its write-ahead log to the replicas, which apply it a little later, usually milliseconds, sometimes seconds under load.

Java
@Transactional
public void updateName(long userId, String name) {
users.updateName(userId, name); // primary: 'Ana Silva', committed at t = 0 ms
}
@Transactional(readOnly = true)
public User profile(long userId) {
return users.findById(userId).orElseThrow(); // replica
}
// Browser: POST /profile -> 204 t = 0 ms
// GET /profile -> 'Ana S.' t = 40 ms, replica lag 300 ms: old value
// GET /profile -> 'Ana Silva' t = 900 ms: replica caught up
Step throughA refresh that reads before the replica catches up
BrowserServicePrimaryReplica
POST /profile name = Ana Silva
UPDATE ... COMMIT
204 saved
GET /profile (refresh)
SELECT user 42
Ana S. (old: WAL not applied yet)
WAL streamed and applied, 300 ms later

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

Notice that nothing is lost; the replica simply had not applied the write yet when the refresh arrived. The bug is about which copy the read was sent to, and when.

2Naming the Missing Guarantee

The guarantee is called read-your-writes: a client that has written a value will always see that write, or a newer one, in its own later reads. It is one of the session guarantees, together with monotonic reads, which means a client never sees data go back in time, for example by reading a fresh replica and then a staler one. Session consistency means providing these within one user's session. It is much weaker and cheaper than making every read see every write, because other users may still see the old name for a moment, which nobody notices.

So we do not need to stop using replicas. We only need to make sure that this user, right after this write, reads from a copy that has it.

3Fix 1: Stick to the Primary for a While After a Write

The simplest fix is time based. When a user writes, we record the time, for example in their session or in a short-lived cookie, and for the next few seconds every read for that user goes to the primary. The window must be longer than normal replica lag, say 5 seconds when lag is usually under 1 second.

Java
public class ReadRoutingDataSource extends AbstractRoutingDataSource {
@Override protected Object determineCurrentLookupKey() {
boolean readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
Instant lastWrite = RequestContext.lastWriteAt(); // from session or cookie
boolean recent = lastWrite != null
&& lastWrite.isAfter(Instant.now().minusSeconds(5));
return (readOnly && !recent) ? "replica" : "primary";
}
}
// Wrap it in LazyConnectionDataSourceProxy, so the read-only flag is known
// before the connection is chosen.

Notice the two parts: the routing decision reads the transaction's read-only flag, and LazyConnectionDataSourceProxy delays fetching a connection until the first statement, by which time Spring has set that flag. The weakness is that the window is a guess: if lag spikes to 10 seconds, users see stale data again. It also adds load to the primary in proportion to how often users write.

4Fix 2: Track the Write Position and Wait for the Replica

A more precise fix uses the replication log position. In PostgreSQL every change has a log sequence number, LSN. After the write commits, we read the primary's current position and store it with the session. Before a read, we check whether the chosen replica has replayed at least that position; if so we read there, if not we wait briefly or fall back to the primary.

SQL
-- On the primary, right after the write commits
SELECT pg_current_wal_lsn(); -- 3/1A2B3C40 store in the session
-- On the replica, before the read
SELECT pg_last_wal_replay_lsn() >= '3/1A2B3C40'::pg_lsn; -- false: not yet
-- wait up to 200 ms and check again, or read from the primary
SELECT pg_last_wal_replay_lsn() >= '3/1A2B3C40'::pg_lsn; -- true: safe to read here

Notice that this never waits longer than needed and works however large the lag gets, falling back to the primary only when it must. MySQL offers the same idea with global transaction identifiers: the session remembers the GTID of its write, and WAIT_FOR_EXECUTED_GTID_SET on the replica waits until it has applied it. Some databases and proxies provide this as a built-in causal or session consistency option, so check what yours supports before writing it yourself. The cost is extra work on every read and a slightly more complex library, which is why platforms usually provide it once for all teams.

5Fix 3: Return the Updated Data in the Write Response

Often the simplest fix is to avoid the immediate re-read. The write endpoint returns the updated profile as the primary committed it, and the client updates its state from that response instead of reloading. For single-page applications this is natural: the form submits, the response contains the new user object, and the page shows it. A later full reload may still hit a replica, so this fix is usually combined with a short primary window or position tracking for full page loads.

Java
@PutMapping("/profile")
public UserDto update(@RequestBody NameChange change) {
User saved = service.updateName(currentUserId(), change.name()); // primary
return UserDto.from(saved); // {"id":42,"name":"Ana Silva"} -> client renders this
}
Three ways to read your own writes
FixHow it worksCostWeak spot
Primary after writeReads go to primary for N secondsSimple, more primary loadLag longer than N
Track log positionRead replica once it reaches the LSNPrecise, more codeNeeds session state
Return data on writeClient uses the responseNo extra readsFull reloads still re-read

6Monitoring Replica Lag

All three fixes assume the lag is usually small. When it grows, the primary window expires before replicas catch up, position checks fall back to the primary more often and overload it, and other users see older data for longer. So replica lag is a first-class metric. In PostgreSQL we can measure it on the primary from pg_stat_replication, which shows each replica's replay_lag, or on a replica by comparing now() with pg_last_xact_replay_timestamp(). We alert when lag stays above a threshold, for example 2 seconds for 5 minutes, and investigate the usual causes: long queries on the replica that conflict with replay, an overloaded replica, network limits or large batch writes on the primary.

7Follow-up questions

What is monotonic reads, and how could it break here?

Monotonic reads means a user never sees data older than what they saw before. If one request reads from a replica that is 100 milliseconds behind and the next from a replica 3 seconds behind, the user can see a new value and then an old one. Pinning a session to one replica, or using the log position check for every read, prevents it.

Would synchronous replication solve this?

PostgreSQL's synchronous_commit = remote_apply makes a commit wait until the synchronous standbys have applied it, so reads on those standbys see it. It does provide read-your-writes, but every write pays the extra round trip and a slow standby slows down all writes, so it is usually reserved for small, critical workloads.

Does caching make this worse?

Yes, a cache in front of the replica can keep the old value for its whole TTL. The write should evict or update the cache entry for that user, and the cache should be filled from the primary or from the write response.

8Conclusion

In this answer, we saw that seeing the old profile after a save is a missing read-your-writes, or session consistency, guarantee caused by reading from asynchronous replicas that lag behind the primary. We can provide it by routing the user's reads to the primary for a short window after a write, by tracking the write's log position and reading from a replica only once it has caught up, or by returning the updated data in the write response, and we monitor replica lag because every one of these degrades when lag grows.

What to say in the interviewAbout 90 seconds aloud

Open with

The missing guarantee is read-your-writes, which is part of session consistency. The service commits the update on the primary, but the refresh is a read that goes to a replica, and replication is asynchronous, so if the replica is a few hundred milliseconds behind it still returns the old value.

Then, if they want more

Nothing is lost, the read just went to a copy that had not caught up. I would fix it in one of three ways. First, after a user writes, route that user's reads to the primary for a short window, for example five seconds, using a timestamp in the session or a cookie and a routing data source.

That is simple but the window is a guess. Second, track the write position: after the commit, store the primary's log sequence number, and before reading, check that the replica has replayed at least that LSN, waiting briefly or falling back to the primary otherwise; in MySQL the same works with GTIDs. That is precise but needs a shared library.

Third, return the updated data in the write response, so the client renders it without re-reading. In all cases I would monitor replica lag and alert on it, because when lag grows, every one of these workarounds gets weaker or pushes more load onto the primary.

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.
Official documentation
Redis documentation, MongoDB manual
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 "Users sometimes update their profile and then see the old value on refresh. The service...": https://scrivio-interview-library.netlify.app/databases/nosql-fundamentals/ec00579a34/