Quick revision
The short answer
We route a user's reads to the primary for a short window after they write, and to replicas otherwise. In Spring Boot this is an AbstractRoutingDataSource that picks primary or replica from a context value, with @Transactional(readOnly = true) marking replica-safe reads and a signed cookie or session attribute remembering the user's last write time. Returning the updated profile in the write response, optionally tracking the WAL position for precise routing, and falling back to the primary when replica lag exceeds the budget complete the design.
What to remember
In this answer, we met the read-your-writes requirement without giving up replicas. An AbstractRoutingDataSource wrapped in LazyConnectionDataSourceProxy sends read-only transactions to a replica and everything else to the primary. A signed cookie or session attribute with the last write time forces the primary for a short window after the user writes, and tracking the WAL LSN makes that decision precise. Returning the updated profile in the write response removes many reads altogether, and monitoring replica lag with a fallback, while watching primary load, keeps the scheme safe.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We route a user's reads to the primary for a short window after they write, and to replicas otherwise. In Spring Boot this is an AbstractRoutingDataSource that picks primary or replica from a context value, with @Transactional(readOnly = true) marking replica-safe reads and a signed cookie or session attribute remembering the user's last write time. Returning the updated profile in the write response, optionally tracking the WAL position for precise routing, and falling back to the primary when replica lag exceeds the budget complete the design.
Why this question is asked
Read replicas are the cheapest way to scale reads in PostgreSQL, and nearly every growing service ends up with them. The trap is that replicas lag behind the primary, so a user who saves their profile and reloads can see the old version, which feels like the save failed. Read-your-writes, the guarantee that a user always sees their own changes, is the usual product requirement. Interviewers ask this design question to see whether we can meet it without sending every read to the primary. In this answer, we will recap how replication lag happens, design the routing data source in Spring, choose how to remember that a user wrote recently, look at the more precise WAL-position approach, and finish with the response shape and the safety fallback.
1A Quick Recap of Replicas and Lag
In PostgreSQL streaming replication, the primary writes every change to its write-ahead log (WAL), an append-only record of changes, and streams it to the replicas, which replay it. A write commits on the primary first; the replica sees it once it has received and replayed that part of the WAL. Here that can take up to two seconds.
Strong consistency for everyone would mean reading only from the primary, which defeats the replicas. But the requirement is narrower: other users may see a profile change a couple of seconds late, but the user who made it must not. So we only need to treat that one user's reads specially, for a short time after their own write.
2Routing Reads With AbstractRoutingDataSource
Spring's AbstractRoutingDataSource is a DataSource that holds several target data sources and chooses one per connection request by calling determineCurrentLookupKey(). We keep the choice in a ThreadLocal context that a filter or aspect sets per request.
Notice the LazyConnectionDataSourceProxy. The transaction manager normally fetches a connection at the start of the transaction, before the read-only flag is visible to our router. The lazy proxy delays fetching the real connection until the first statement, by which time the flag is set. Without it, every transaction may be routed to the default. Recent Spring versions also offer a read-only data source option on the lazy proxy itself; check your version.
Read paths are then marked @Transactional(readOnly = true), and they go to a replica by default. Writes stay on ordinary @Transactional methods and always hit the primary.
3Remembering That the User Just Wrote
After a successful write we record the time. The simplest place is a signed cookie, a cookie with an HMAC so the client cannot forge it, holding the user id and last write timestamp. A session attribute works too when sessions are sticky or shared. A request filter reads it and, if the write happened within the window, sets forcePrimary for this request.
The window must be longer than the worst lag we tolerate. With up to two seconds of lag, five seconds is a reasonable margin. Notice the finally block: a ThreadLocal that is not cleared leaks into the next request on the same thread.
4A More Precise Option: Tracking the WAL Position
A time window is a guess. A precise alternative uses the log sequence number (LSN), the position in the WAL. After the write commits, the service reads pg_current_wal_lsn() on the primary and keeps it with the user, again in a cookie or session. Before reading from a replica, it compares that LSN with pg_last_wal_replay_lsn() on the replica. If the replica has replayed past it, the user's write is visible there and the replica is safe; otherwise we use the primary or another replica.
- Read-only transaction?YesCheck the userNoPrimary
- User wrote in the last 5 s?or has an LSN not yet replayedYesPrimaryNoCheck replica health
- Replica lag over budget?e.g. above 2 sYesPrimaryNoReplica
3 steps in order. Play them, or step through them one at a time.
Only a user's own recent writes and unhealthy replicas send reads to the primary.
This keeps far more reads on replicas, because a replica that is only 50 milliseconds behind passes immediately. The cost is an extra query per routing decision, which we usually cache for a few hundred milliseconds per replica.
5Returning the Result and Falling Back Safely
The cheapest way to avoid a stale read is to not need one. The PUT /profile endpoint returns the updated profile in its response body, so the client renders the saved state without reading at all. Many reloads never happen once the UI already shows the result.
We also monitor replica lag, for example with pg_stat_replication on the primary or the replay timestamp on the replica, and treat a replica whose lag exceeds the budget as unhealthy, sending reads to the primary instead. But there is a catch: if all replicas lag at once, the fallback moves the whole read load onto the primary, which can overload it. So we watch primary load and connection pool usage alongside the fallback rate, and may cap the fallback to recent writers only.
6Follow-up questions
How does this interact with caching in front of the replicas?
A cache is one more copy that can be stale, so the user who just wrote must bypass it or see it updated. The usual approach is to evict or overwrite the user's cache entry after the write commits, and to skip the cache for that user during the same window that forces the primary. Otherwise the routing is correct but the cache still serves the old profile.
What happens to this scheme when the user switches devices?
A cookie lives in one browser, so the new device does not know about the recent write and may read a stale replica. If cross-device read-your-writes matters, we store the last write time or LSN on the server keyed by user id, for example in Redis with a short TTL, and look it up for any request from that user. With a two-second lag, the practical risk is small, which is why many teams accept the per-device guarantee.
Why not read everything from the primary while lag is high?
Because the replicas exist to take load off the primary. Sending all reads to it during a lag spike can turn a replication problem into a primary outage. Routing only the users who need fresh data keeps the primary's extra load small.
7Conclusion
In this answer, we met the read-your-writes requirement without giving up replicas. An AbstractRoutingDataSource wrapped in LazyConnectionDataSourceProxy sends read-only transactions to a replica and everything else to the primary. A signed cookie or session attribute with the last write time forces the primary for a short window after the user writes, and tracking the WAL LSN makes that decision precise. Returning the updated profile in the write response removes many reads altogether, and monitoring replica lag with a fallback, while watching primary load, keeps the scheme safe.
Open with
Only the user who wrote needs fresh data, so I would route just their reads to the primary for a short time and keep everyone else on replicas.
Then, if they want more
In Spring Boot I would add an AbstractRoutingDataSource whose lookup key is primary or replica. It chooses replica when the transaction is read-only, so read paths are annotated with Transactional readOnly true, and primary when a request context flag says force primary. I wrap it in LazyConnectionDataSourceProxy so the connection is chosen after the read-only flag is set.
To set that flag, after a successful write I store the last write time in a signed cookie or session attribute, and a filter forces the primary if it is within about five seconds, which covers the two-second lag with margin.
If I want to be precise, I store the primary's WAL LSN after the write and only read from a replica whose replay LSN is past it. I would also return the updated profile in the PUT response so the client often does not need to read at all.
Finally I monitor replica lag and route to the primary when a replica exceeds the budget, while watching primary load so the fallback cannot overload it. For multiple devices I would keep the last write marker server side, keyed by user.
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
- Spring Cloud documentation, Resilience4j documentation
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 "You are designing a profile service where writes go to a primary PostgreSQL database and...": https://scrivio-interview-library.netlify.app/spring-boot/distributed-data/c76745f0f3/