Scrivio Interview library
InternalsFoundations5 min read · updated 12 November 2026

A team routes reads to a replica with an AbstractRoutingDataSource whose determineCurrentLookupKey() returns "replica" when TransactionSynchronizationManager.isCurrentTransactionReadOnly() is true. Methods with @Transactional(readOnly = true) still go to the primary when using JPA. Why, and what is the usual fix?

With JPA, the transaction manager obtains the JDBC connection while it begins the transaction, and only afterwards binds the read-only flag to TransactionSynchronizationManager. So when the routing data source asks isCurrentTransactionReadOnly(), it still sees false and picks the primary. The usual fix is to wrap the routing data source in a LazyConnectionDataSourceProxy, which hands out a placeholder connection and fetches the real one on the first statement, after the flag is set.

Why this question is asked

Read replicas are one of the first tools teams reach for when a database gets busy, and AbstractRoutingDataSource looks like an easy way to use them. Many teams then find that all traffic still goes to the primary, and the reason is hidden in the order of a few calls inside Spring's transaction code. Interviewers like the question because it tests whether we understand when a connection is really taken from the pool. In this answer, we will recap how routing works, follow the order of events in JpaTransactionManager, apply the fix, verify it, and cover replica failures and nested transactions.

1A Quick Recap of AbstractRoutingDataSource

A DataSource is the object that hands out database connections, usually from a pool such as HikariCP. AbstractRoutingDataSource is a DataSource that holds several target data sources in a map and, each time a connection is requested, calls determineCurrentLookupKey() to choose which one to use. Our version returns replica when the current transaction is read-only and primary otherwise.

Java
class ReplicaRouting extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
boolean ro = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
log.debug("routing, readOnly={}", ro); // readOnly=false, even for readOnly = true methods
return ro ? "replica" : "primary";
}
}

The idea is sound. The problem is when determineCurrentLookupKey() is called. It runs at the moment a connection is requested, so it can only see what has been set up by then.

2Why JPA Gets the Connection Too Early

When a @Transactional(readOnly = true) method starts, JpaTransactionManager begins the transaction in its doBegin step. It creates an EntityManager and asks the JPA dialect to begin the transaction. Hibernate's dialect needs the JDBC connection at this point, for example to apply the read-only hint and the isolation level to it, so the connection is fetched right now, and that is when our routing method runs.

Only after doBegin has finished does the transaction manager prepare synchronization, which is the step that binds the transaction's properties, including the read-only flag, to TransactionSynchronizationManager. So the routing data source asks the question one step too early and gets false.

Step throughWhy the routing sees readOnly = false
ProxyJpaTxManagerRouting DSSync manager
begin, readOnly = true
getConnection() during doBegin
isCurrentTransactionReadOnly()?
false: not bound yet
primary connection
bind readOnly = true (too late)

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

The flag is bound after the connection has already been chosen.

3The Fix: LazyConnectionDataSourceProxy

LazyConnectionDataSourceProxy wraps a DataSource and returns a proxy connection that does not touch the pool yet. It records calls such as setReadOnly, setAutoCommit and setTransactionIsolation, and only when the first statement is created does it ask the target data source for a real connection and replay those settings on it. By then, the transaction manager has bound the read-only flag, so the routing decision sees the truth.

Java
@Bean
@Primary
DataSource dataSource(DataSource primary, DataSource replica) {
ReplicaRouting routing = new ReplicaRouting();
routing.setTargetDataSources(Map.of("primary", primary, "replica", replica));
routing.setDefaultTargetDataSource(primary);
routing.afterPropertiesSet();
return new LazyConnectionDataSourceProxy(routing); // real connection on first statement
}
// @Transactional(readOnly = true) findAll() now logs:
// routing, readOnly=true

Notice that the proxy is the bean JPA sees, and the routing data source sits behind it. A side benefit is that transactions that never run a statement, for example ones answered entirely from a cache, never take a pooled connection at all. Recent Spring versions also let LazyConnectionDataSourceProxy take a separate read-only data source directly, which can replace the custom routing class; check your Spring version.

4Verifying Where Queries Really Go

A log line in determineCurrentLookupKey() is a good start, but the strongest proof is to ask the database server. In an integration test with a real primary and replica, for example two Testcontainers PostgreSQL instances with streaming replication, a read-only method runs SELECT pg_is_in_recovery(), which returns true only on a replica. In MySQL, SELECT @@read_only or @@server_id serves the same purpose.

Java
@Transactional(readOnly = true)
public boolean onReplica() {
return jdbc.queryForObject("select pg_is_in_recovery()", Boolean.class);
}
assertThat(service.onReplica()).isTrue(); // read-only: replica
assertThat(service.onPrimary()).isFalse(); // read-write method: primary

5When the Replica Is Unavailable

Routing to a replica adds a new failure: the replica may be down, restarting, or lagging far behind. If determineCurrentLookupKey() always returns replica, every read fails during a replica outage, even though the primary could serve them. So the routing should know the replica's health, for example from a scheduled check of connectivity and replication lag, and return primary when the replica is unhealthy. With several replicas, it picks a healthy one. We must also make sure the primary has room for those extra reads, or a replica failure turns into a primary overload.

6Follow-up questions

What happens with nested transactions that change readOnly?

With the default REQUIRED propagation, an inner method joins the outer transaction and uses its connection, so its own readOnly setting does not change the routing. A read-only inner method inside a read-write transaction simply reads from the primary, which is fine. The dangerous case is the reverse: a read-write method called inside a read-only transaction joins the replica connection, and its writes fail with a read-only error. REQUIRES_NEW starts a new transaction with a new connection, so it is routed by its own flag.

Does readOnly = true do anything else besides routing?

Yes. Spring sets the JDBC connection to read-only, which some drivers pass to the server, and Hibernate switches the session to a read-only flush mode so it skips dirty checking. That saves work even without replicas.

Would the problem happen with DataSourceTransactionManager and plain JDBC?

It fetches the connection in doBegin too, before synchronization is prepared, so the same early binding applies. The LazyConnectionDataSourceProxy fix works the same way for both transaction managers.

7Conclusion

In this answer, we saw that JpaTransactionManager fetches the connection while beginning the transaction, before it binds the read-only flag, so a routing data source that checks isCurrentTransactionReadOnly() always picks the primary. Wrapping the routing data source in a LazyConnectionDataSourceProxy delays the real connection until the first statement, when the flag is set. We verify the routing by asking the server whether it is in recovery, and we add health-aware fallback to the primary when the replica is unavailable.

What to say in the interviewAbout 70 seconds aloud

Open with

The routing decision happens too early. AbstractRoutingDataSource calls determineCurrentLookupKey when a connection is requested, and with JPA that happens inside JpaTransactionManager's doBegin, because Hibernate's dialect needs the connection to begin the transaction and apply read-only and isolation settings.

Then, if they want more

Spring only binds the read-only flag to TransactionSynchronizationManager after doBegin, when it prepares synchronization. So the routing data source sees readOnly false and returns the primary. The usual fix is to wrap the routing data source in a LazyConnectionDataSourceProxy and expose that as the main DataSource.

It returns a proxy connection, remembers settings like setReadOnly, and only fetches the physical connection when the first statement is created, after the flag is bound, so read-only transactions go to the replica. I would prove it in an integration test by running select pg_is_in_recovery in a read-only method and expecting true.

I would also make routing health-aware, sending reads to the primary when the replica is down or lagging badly, and I would point out that with REQUIRED propagation an inner read-write method inside a read-only transaction will try to write on the replica and fail.

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 "A team routes reads to a replica with an AbstractRoutingDataSource whose...": https://scrivio-interview-library.netlify.app/databases/database-scaling/71626d2ed4/