Scrivio Interview library
DesignIntermediate6 min read · updated 12 November 2026

Design read-your-writes consistency for a Spring Boot service using a primary and three replicas, without sending all reads to the primary.

After each write, the service records the primary's WAL position with pg_current_wal_lsn() and keeps it with the user, in the session or a token returned to the client. Before a read on a replica, it checks that the replica's pg_last_wal_replay_lsn() has reached that position; if not, it waits a few milliseconds or reads from the primary. A simpler variant sticks to the primary for a few seconds after a write, MySQL does the same with GTIDs and WAIT_FOR_EXECUTED_GTID_SET, and replicas that lag beyond a threshold leave the read pool.

Why this question is asked

Read-your-writes is the promise that once you have changed something, you will see your change. It sounds like a minimum, but replicas break it by default, because they apply changes a little after the primary. Sending all reads to the primary would keep the promise and waste the replicas. Interviewers ask this design to see whether we can keep the promise precisely, only for the reads that need it, with mechanisms the database already offers. In this answer, we will recap the problem, design the LSN-based approach step by step, implement it in Spring Boot, look at the simpler time-based variant, translate it to MySQL and finish with lag-aware pool management.

1A Quick Recap of the Problem

With one primary and three asynchronous replicas, every write goes to the primary, and replicas replay its WAL, the write-ahead log, with some lag, usually milliseconds and sometimes seconds. A user who updates their settings and immediately reloads the page may be served by a replica that has not replayed the update yet, and sees the old settings.

The key observation is that PostgreSQL tells us exactly where it is. Every position in the WAL has an LSN, a log sequence number, a steadily increasing value like 0/3A2B1C8. The primary knows the LSN of what it has written, and each replica knows the LSN of what it has replayed. If a replica's replay LSN is at or past the LSN of our write, the replica has our write. That turns a vague question, is it fresh enough, into a comparison of two numbers.

2Step by Step: Tokens Based on the WAL Position

The design has three steps. After a write commits, the service asks the primary for its current WAL LSN. That value is at or beyond our commit record, so any replica that reaches it has our change. The service stores the LSN as the user's consistency token, in the session, or in a response header or cookie that the client sends back. If the user writes again, the token moves forward.

Before a read, the service picks a replica and asks it for pg_last_wal_replay_lsn(). If that is at least the token, it reads there. If not, it can wait briefly and check again, perhaps for up to 50 ms, try another replica, or give up and read from the primary.

Step throughServing a read with a consistency token
  1. Write commits on the primarythen SELECT pg_current_wal_lsn()
  2. Store the LSN as the user's tokensession, cookie or header
  3. Read arrives with the tokenpick a healthy replica
  4. Replica replay LSN >= token?
    YesRead from the replicaNoWait up to 50 ms or try another
  5. Caught up in time?
    YesRead from the replicaNoRead from the primary

5 steps in order. Play them, or step through them one at a time.

Users who have not written recently carry no token and always read from replicas.

3Implementing It in Spring Boot

We need a small component that captures the token after writes and a routing decision that uses it. The capture happens after the transaction commits, so the LSN includes our commit.

Java
@Service
class ConsistencyTokens {
private final JdbcTemplate primary;
ConsistencyTokens(@Qualifier("primaryJdbc") JdbcTemplate primary) { this.primary = primary; }
String currentPrimaryLsn() {
return primary.queryForObject("SELECT pg_current_wal_lsn()::text", String.class); // "0/3A2B1C8"
}
}
@Component
class ReplicaChooser {
DataSource choose(String token, List<NamedReplica> replicas, DataSource primary) {
if (token == null) return replicas.get(ThreadLocalRandom.current().nextInt(replicas.size())).ds();
for (NamedReplica r : replicas) {
Boolean ok = r.jdbc().queryForObject(
"SELECT pg_last_wal_replay_lsn() >= ?::pg_lsn", Boolean.class, token); // true or false
if (Boolean.TRUE.equals(ok)) return r.ds();
}
return primary; // nobody has caught up: correctness first
}
}

Notice that the check costs one tiny query per read for users with a token. Most users, who are only browsing, carry no token and pay nothing. To avoid even that, the service can cache each replica's replay LSN, refreshed every 100 ms by a background task, and compare against the cache; a cached value can only be older than the truth, so the check stays safe. A TransactionSynchronization afterCommit callback, or simply a filter that runs after the controller, is a natural place to capture the token after writes.

4The Simpler Variant: Time-Based Stickiness

If the LSN machinery feels heavy, the time-based variant is a reasonable first version: after a write, the user's reads go to the primary for, say, five seconds. It needs no database calls, only a timestamp per user. The cost is precision. If a replica is ever more than five seconds behind, the user sees stale data again, and in the meantime we send reads to the primary even when replicas are already current. Many teams start here and move to tokens when lag spikes or primary load make the difference matter.

5The MySQL Equivalent With GTIDs

MySQL offers the same idea with GTIDs, the global transaction identifiers attached to every transaction. After a write, the service reads the GTID of its transaction, for example by enabling session_track_gtids so the server returns it with the commit, or from @@gtid_executed. Before reading from a replica, it calls WAIT_FOR_EXECUTED_GTID_SET with a timeout.

SQL
-- on the replica, before the read
SELECT WAIT_FOR_EXECUTED_GTID_SET('3e11fa47-71ca-11e1-9e33-c80aa9429562:1-1042', 0.05);
-- 0 the replica has applied it, read here
-- 1 timed out after 50 ms, read from the source instead

So the pattern is the same in both databases: capture a position after the write, compare or wait on the replica, and fall back to the primary when the replica is too far behind.

6Keeping Lagging Replicas Out of the Pool

Tokens protect users who just wrote. Everyone else still deserves data that is not wildly old. So the service exports each replica's lag as a metric, for example a Micrometer gauge based on pg_wal_lsn_diff or replay time, and removes a replica from the read pool when its lag passes a threshold such as 5 seconds, adding it back once it recovers below, say, 1 second. The two thresholds stop a replica from flapping in and out. If all replicas lag, reads fall back to the primary, with an alert, because a primary carrying all reads for a few minutes is better than serving minutes-old data.

7Follow-up questions

Why capture pg_current_wal_lsn() after commit rather than before?

Before commit, the commit record is not yet in the WAL, so a replica could reach the captured LSN without having our commit. After commit, the current LSN is at or beyond the commit record, so reaching it guarantees the replica has our change. The value may be slightly ahead because of other users' writes, which only makes us a little more conservative.

Does this work across several devices of one user?

If the token lives in the server-side session or a per-user store such as Redis, yes. If it lives only in a cookie in one browser, a second device does not have it and may read stale data. For most products, per-device read-your-writes is acceptable; if not, store the token per user.

Is pg_last_wal_replay_lsn() available on a primary?

It returns null on a server that is not in recovery, so the chooser should only call it on standbys. The primary is always current by definition.

8Conclusion

In this answer, we saw that read-your-writes can be kept precisely by capturing the primary's LSN after a write, storing it as a token, and only reading from a replica whose replay LSN has reached it, waiting briefly or falling back to the primary otherwise. Time-based stickiness is a simpler variant with rare violations, MySQL offers the same with GTIDs and WAIT_FOR_EXECUTED_GTID_SET, and lag metrics with thresholds keep slow replicas out of the pool.

What to say in the interviewAbout 90 seconds aloud

Open with

I would make freshness a comparison of log positions. After a write commits, the service runs SELECT pg_current_wal_lsn() on the primary and stores the result as the user's consistency token, in the session or in a header or cookie the client sends back.

Then, if they want more

When that user reads, the service picks a replica and checks pg_last_wal_replay_lsn() >= token. If it has caught up, read there; if not, wait a few milliseconds, try another replica, or read from the primary. Users without a recent write have no token and always use replicas, so the primary only takes the small share of reads that need it.

To avoid a query per check, I would cache each replica's replay LSN every hundred milliseconds; a stale cache is only more conservative. A simpler first version is time-based: send a user's reads to the primary for five seconds after a write. It is cheap but breaks if lag exceeds the window.

On MySQL the same idea uses GTIDs: capture the transaction's GTID, for example with session_track_gtids, and call WAIT_FOR_EXECUTED_GTID_SET with a short timeout on the replica.

Finally, I would export replica lag as a metric and take a replica out of the pool above, say, five seconds, back in below one, falling back to the primary with an alert if all of them lag.

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 "Design read-your-writes consistency for a Spring Boot service using a primary and three...": https://scrivio-interview-library.netlify.app/databases/replication-and-ha/3f3657cd23/