Quick revision
The short answer
We put an AbstractRoutingDataSource in front of a primary and a replica DataSource, choosing the target from TransactionSynchronizationManager.isCurrentTransactionReadOnly(), so @Transactional(readOnly = true) methods go to the replica. We wrap the router in LazyConnectionDataSourceProxy so the real connection is taken only after the transaction's read-only flag is set. The main risk is replica lag, which causes read-your-writes bugs, so we route reads that follow a write to the primary for a while, monitor lag and fall back to the primary when it is too high, and compare this with routing done by a managed proxy or driver outside the application.
What to remember
In this answer, we designed read/write splitting with an AbstractRoutingDataSource that routes @Transactional(readOnly = true) to a replica based on TransactionSynchronizationManager.isCurrentTransactionReadOnly(), wrapped in a LazyConnectionDataSourceProxy so the connection is chosen after the read-only flag is set. We saw that replica lag breaks read-your-writes, so reads after a write, or by a user who just wrote, go to the primary. Lag is monitored and the router falls back to the primary when it crosses a threshold, and routing in drivers or proxies is an alternative to compare for consistency and operations.
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 put an AbstractRoutingDataSource in front of a primary and a replica DataSource, choosing the target from TransactionSynchronizationManager.isCurrentTransactionReadOnly(), so @Transactional(readOnly = true) methods go to the replica. We wrap the router in LazyConnectionDataSourceProxy so the real connection is taken only after the transaction's read-only flag is set. The main risk is replica lag, which causes read-your-writes bugs, so we route reads that follow a write to the primary for a while, monitor lag and fall back to the primary when it is too high, and compare this with routing done by a managed proxy or driver outside the application.
Why this question is asked
Read replicas are the usual first step when a database becomes busy: most traffic is reads, and a replica can serve them while the primary handles writes. The hard part is not configuring the replica, it is deciding in the application which statements may go there, and living with the fact that a replica is always slightly behind. Interviewers ask this design question at senior level because a naive version works in testing and then shows users stale data in production. In this answer, we will recap how replicas work, build the routing DataSource, explain why it needs a lazy proxy, look at replica lag and how to protect read-your-writes, add monitoring and fallback, and compare with routing outside the application.
1A Quick Recap of Replicas and Replica Lag
A read replica is a copy of the primary database that receives the primary's changes continuously, through streaming replication in PostgreSQL or the binary log in MySQL. It accepts reads, rejects writes, and can be scaled out, for example one primary and three replicas.
Replication is usually asynchronous: the primary commits first and the replica applies the change shortly after. The delay is called replica lag. It is often a few milliseconds, but under heavy write load, a long query on the replica or a network problem, it can grow to seconds or minutes. Any design that reads from replicas must decide what to do about that gap.
2Routing With AbstractRoutingDataSource
Spring's AbstractRoutingDataSource is a DataSource that holds several target DataSources and picks one for each getConnection() call, based on a lookup key we return. Spring already marks transactions as read-only when we write @Transactional(readOnly = true), and TransactionSynchronizationManager exposes that flag for the current thread, so it makes a natural key.
Notice that the default target is the primary. Anything we are not sure about, including code that runs without a transaction, goes to the primary, which is the safe direction to be wrong in.
3Why the Lazy Proxy Is Needed
There is a timing problem. When a transaction starts, the transaction manager takes a connection first and only afterwards registers the transaction's properties, including the read-only flag, with TransactionSynchronizationManager. So at the moment our router is asked for a connection, isCurrentTransactionReadOnly() still returns false, and every transaction would go to the primary.
LazyConnectionDataSourceProxy solves this. It hands the transaction manager a placeholder connection and remembers the settings applied to it, such as read-only and isolation. The real getConnection() on the router happens only when the first statement runs, by which time the read-only flag is set and the routing decision is correct. It also avoids taking a connection at all for transactions that never run a statement. Since Spring Framework 6.1.2, LazyConnectionDataSourceProxy can also be given a separate read-only DataSource directly, which covers this case without a custom router; check your version.
7 messages in order. Play them, or step through them one at a time.
The real connection is chosen after the read-only flag exists.
4The Main Risk: Read-Your-Writes
Now the hard part. A user changes their address, the write commits on the primary, and the page redirects to their profile, which is a read-only method and goes to the replica. If the replica is 300 ms behind, the user sees their old address and assumes the change failed. This is a read-your-writes violation: a user does not see their own write.
The fix is to send some reads to the primary even though they are read-only. Common rules are: reads in the same request after a write go to the primary; a user who wrote something in the last few seconds has their reads pinned to the primary, using a timestamp in the session or a cookie; and business-critical reads, such as balances before a payment, always use the primary. Each rule trades replica load for correctness, so we choose them per use case.
5Monitoring Lag and Falling Back
We measure lag continuously and publish it as a metric. On a PostgreSQL replica, now() minus pg_last_xact_replay_timestamp() gives the age of the last applied change (with a caveat that it grows when the primary is idle). On MySQL, SHOW REPLICA STATUS reports Seconds_Behind_Source. A small scheduled check every few seconds is enough.
If lag passes a threshold, say 2 seconds, the router stops using the replica and sends read-only traffic to the primary until lag recovers, and an alert fires. The primary must therefore have the capacity to take all reads for a while, which is a capacity planning point worth stating explicitly. Without fallback, a lagging replica silently serves stale data to everyone.
6Routing Outside the Application
Routing does not have to live in our code. Some drivers and proxies do it: the AWS Advanced JDBC Wrapper has a read/write splitting plugin, MySQL Router can send traffic to primary or replicas by port, and PostgreSQL setups use tools such as Pgpool-II or provider endpoints for readers. These move routing into infrastructure, which helps when many services and languages share the database.
The comparison comes down to consistency and operations. In-application routing knows about our transactions and users, so it can implement read-your-writes rules precisely. Outside routing is shared and consistent across services, but usually only knows read-only flags or ports, not user intent, and it is another component to run and upgrade. Many teams use outside routing for failover and in-application rules for the critical reads.
| Approach | Strength | Cost |
|---|---|---|
AbstractRoutingDataSource | Knows transactions and users; precise read-your-writes rules | Code in every service; needs lazy proxy and fallback |
| Driver plugin (for example AWS JDBC wrapper) | No custom code, handles failover | Provider-specific; check behaviour for read-only flags |
| Proxy (MySQL Router, Pgpool-II) | Shared by all services and languages | Extra component; little knowledge of user intent |
| Separate reader endpoint per use case | Simple and explicit | Code must choose the endpoint itself |
7Follow-up questions
What happens when a read-only method is called from inside a read-write transaction?
It joins the outer transaction with the default propagation, so it uses the outer transaction's connection on the primary. The readOnly flag of the inner method does not start a new transaction or change the connection. That is usually what we want, because the inner read then sees the outer transaction's uncommitted writes.
Does readOnly = true do anything else besides routing?
Yes. Spring calls setReadOnly(true) on the JDBC connection, which some drivers pass on to the database, and with Hibernate it sets the session to read-only flush mode, so entities loaded there are not dirty checked and the session is not flushed. That saves memory and CPU even without replicas.
How many replicas should we start with?
Usually one, sized like the primary, so that it can also act as a failover target. We add more when measured read load justifies it. Every extra replica adds cost and a little more load on the primary for replication, so the number should come from read traffic and lag measurements, not from a guess.
8Conclusion
In this answer, we designed read/write splitting with an AbstractRoutingDataSource that routes @Transactional(readOnly = true) to a replica based on TransactionSynchronizationManager.isCurrentTransactionReadOnly(), wrapped in a LazyConnectionDataSourceProxy so the connection is chosen after the read-only flag is set. We saw that replica lag breaks read-your-writes, so reads after a write, or by a user who just wrote, go to the primary. Lag is monitored and the router falls back to the primary when it crosses a threshold, and routing in drivers or proxies is an alternative to compare for consistency and operations.
Open with
I would build it with Spring's AbstractRoutingDataSource holding a primary and a replica DataSource, and return the lookup key from TransactionSynchronizationManager.isCurrentTransactionReadOnly, so methods marked @Transactional readOnly true go to the replica and everything else, including non-transactional code, defaults to the primary.
Then, if they want more
I would wrap the router in LazyConnectionDataSourceProxy, because the transaction manager takes its connection before it sets the read-only flag; the lazy proxy delays the real connection until the first statement, when the flag is known. The main risk is replica lag.
A user who saves something and is redirected to a read-only page may read from a replica that has not applied the write yet and see old data.
So I would route reads to the primary in the same request after a write, and pin a user to the primary for a few seconds after they write, and keep critical reads like balances on the primary.
I would monitor lag as a metric, for example with pg_last_xact_replay_timestamp on PostgreSQL, and fall back to the primary with an alert when it passes a threshold like two seconds. I would also compare with routing in the driver or a proxy, which is simpler to share across services but knows less about our users.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Spring Framework 6
- 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
- java.sql, package 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 "Many services read from replicas and write to a primary. Design read/write splitting at...": https://scrivio-interview-library.netlify.app/databases/jdbc/3571e1e20d/