Scrivio Interview library
DesignIntermediate7 min read · updated 12 November 2026

Design read replica routing in a Spring Boot service so that read-only transactions go to a replica and others go to the primary. What pitfalls exist?

We put an AbstractRoutingDataSource in front of two connection pools, and it picks the replica when TransactionSynchronizationManager.isCurrentTransactionReadOnly() is true and the primary otherwise. We wrap the router in a LazyConnectionDataSourceProxy, because the real connection must be fetched only after Spring has recorded that the transaction is read-only. The main pitfalls are replication lag, which breaks read-your-writes, pools that are not sized per target, nested transactions that mix reads and writes, and a replica that goes down.

Why this question is asked

Most services read far more than they write, and a PostgreSQL or MySQL replica is a cheap way to take read load off the primary. Spring has no single switch for this, so interviewers ask the question to see whether we understand when Spring decides on a connection, what the read-only flag really is, and what can go wrong once reads see slightly old data. In this answer, we will recap what a routing data source is, build one step by step, see why the lazy proxy is needed, and then go through the pitfalls and how we test them.

1A Quick Recap of Replicas and Read-Only Transactions

A read replica is a copy of the primary database that receives the primary's changes through replication, usually asynchronously. It can answer queries but refuses writes. Because replication is asynchronous, the replica is always a little behind, typically a few milliseconds, sometimes seconds or minutes under heavy load.

In Spring, @Transactional(readOnly = true) is a hint. It tells the transaction manager that the method will not write. Spring records the flag in TransactionSynchronizationManager, a holder of per-thread transaction state, and passes it to the JDBC connection with setReadOnly(true). Hibernate also uses it to skip dirty checking. Nothing in Spring sends read-only work anywhere special by itself; we have to build that routing.

2Building the Routing DataSource

AbstractRoutingDataSource is a DataSource that holds several target data sources in a map and asks a method, determineCurrentLookupKey(), which one to use each time a connection is requested. We return a key based on the read-only flag of the current transaction.

Java
enum Target { PRIMARY, REPLICA }
class ReadWriteRoutingDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return TransactionSynchronizationManager.isCurrentTransactionReadOnly()
? Target.REPLICA : Target.PRIMARY;
}
}
@Configuration
class DataSourceConfig {
@Bean
DataSource dataSource(@Qualifier("primaryPool") DataSource primary,
@Qualifier("replicaPool") DataSource replica) {
var router = new ReadWriteRoutingDataSource();
router.setTargetDataSources(Map.of(Target.PRIMARY, primary, Target.REPLICA, replica));
router.setDefaultTargetDataSource(primary); // no transaction -> primary
router.afterPropertiesSet();
return new LazyConnectionDataSourceProxy(router);
}
}
// @Transactional(readOnly = true) findOrders() -> replica pool
// @Transactional placeOrder() -> primary pool
// no transaction at all -> primary pool

Notice that the default target is the primary. Anything we did not mark as read-only, including code that runs with no transaction at all, goes to the primary. That is the safe direction to be wrong in.

3Why LazyConnectionDataSourceProxy Is Needed

There is a catch in the order of events. When a transaction begins, the transaction manager fetches a connection first, and only afterwards does it publish the transaction's attributes, including the read-only flag, into TransactionSynchronizationManager. So at the moment our router is asked for a key, isCurrentTransactionReadOnly() still returns false, and every transaction would go to the primary.

LazyConnectionDataSourceProxy fixes this. It hands the transaction manager a stand-in connection object and remembers the settings applied to it, such as readOnly and autoCommit. The real connection is fetched from the router only when the first SQL statement runs. By then the flag is set, so the router chooses correctly. A side benefit is that a transaction which never runs a query never takes a connection from the pool.

Since Spring Framework 6.1 (check your version), LazyConnectionDataSourceProxy can also take a separate read-only data source directly through setReadOnlyDataSource(), choosing it when the connection was marked read-only. That removes the need for our own router in the simple two-target case.

Step throughWhen the replica is chosen
Service proxyTx managerLazy proxyRouterReplica pool
begin, readOnly = true
getConnection()
stand-in connection, nothing fetched yet
record readOnly flag for this thread
first SELECT runs
fetch real connection now
isCurrentTransactionReadOnly() is true
borrow a replica connection

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

Without the lazy proxy, the router is asked before the flag is recorded and always picks the primary.

4Pitfall: Replication Lag and Read-Your-Writes

The most common bug appears right after a write. A user creates an order, the browser is redirected to the order page, and the page loads the order with a read-only transaction. If the replica is 200 milliseconds behind, the order is not there yet and the user sees a 404.

So read-only is not the same as safe to read from a replica. Flows that must see their own writes should read from the primary: for a few seconds after a user writes, or always for screens that confirm an action. We can do this with a separate annotation or a thread-local hint that forces the primary key, checked before the read-only flag in determineCurrentLookupKey().

5Pitfall: Nested Transactions and Mixed Work

Routing is decided once per physical transaction, when the first statement runs. If a read-write method calls a read-only method with the default REQUIRED propagation, the inner method joins the outer transaction and keeps using the primary connection. That is harmless. The opposite is not: if a read-only method calls a method that writes and joins the same transaction, the write runs on the replica connection and PostgreSQL rejects it with an error such as cannot execute UPDATE in a read-only transaction. The fix is to put the read-write transaction boundary outermost, or to give the writing method REQUIRES_NEW deliberately.

6Pitfall: Pools, Failover and Testing

Each target needs its own pool, sized for its own load. If reads are 90 percent of traffic, the replica pool may need 30 connections while the primary needs 10; one shared size wastes connections on one side and starves the other. Each pool also needs its own timeouts and metrics, so we can see which side is waiting.

We also have to decide what happens when the replica is unavailable. A common choice is to fall back to the primary for reads, with a circuit breaker so we do not overload the primary at the worst moment. We should test this on purpose: stop the replica in a Testcontainers test and check that read endpoints still answer, add artificial lag and check that read-your-writes flows still go to the primary, and check that the primary pool is not exhausted by the fallback.

7Follow-up questions

Why not choose the data source in an aspect around @Transactional methods?

We can, by setting a thread-local key in an aspect that runs before the transaction interceptor, but it depends on aspect ordering and is easy to break. Reading the flag that Spring already maintains, together with the lazy proxy, uses the transaction attributes exactly as the transaction manager sees them and needs no ordering rules.

Does readOnly = true alone stop writes?

Not reliably. The JDBC driver receives setReadOnly(true), and PostgreSQL then runs the transaction as read-only and rejects writes, but other drivers may only treat it as a hint. Hibernate skips flushing for read-only transactions, so entity changes are silently not written. On a replica, the database itself refuses writes, which is the real guarantee.

How does the router behave with Open Session in View?

With Open Session in View, the EntityManager lives for the whole web request, and depending on the connection handling mode it may hold on to its connection after the first transaction. A later transaction in the same request can then reuse a connection chosen for an earlier one. Disabling Open Session in View with spring.jpa.open-in-view=false keeps each transaction's routing decision clean.

8Conclusion

In this answer, we saw that replica routing in Spring is an AbstractRoutingDataSource that reads TransactionSynchronizationManager.isCurrentTransactionReadOnly(), wrapped in LazyConnectionDataSourceProxy so the decision is made after the flag is known. We then went through the pitfalls: stale reads after writes, read-only transactions that call writers, pools sized per target, and a replica that fails, each of which needs its own rule and its own test.

What to say in the interviewAbout 80 seconds aloud

Open with

I would put an AbstractRoutingDataSource in front of two Hikari pools, one for the primary and one for the replica, and have determineCurrentLookupKey return the replica when TransactionSynchronizationManager.isCurrentTransactionReadOnly is true.

Then, if they want more

The important detail is wrapping the router in LazyConnectionDataSourceProxy. The transaction manager takes a connection before it records the read-only flag, so without the lazy proxy the router always sees false and everything goes to the primary. With it, the real connection is fetched at the first statement, when the flag is set.

In newer Spring versions LazyConnectionDataSourceProxy can also take a read-only data source directly. Then the pitfalls. Replication lag means a user who just created an order might not see it, so read-your-writes flows must be forced to the primary, for example with a hint that the router checks first.

A read-only transaction that calls a writing method with REQUIRED propagation will try to write on the replica and fail, so the read-write boundary should be outermost. Each pool needs its own size and metrics, because reads and writes have very different volumes.

And I would decide and test what happens when the replica is down, usually falling back to the primary behind a circuit breaker, plus a test with artificial lag to prove the read-your-writes paths are routed correctly.

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.
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 replica routing in a Spring Boot service so that read-only transactions go...": https://scrivio-interview-library.netlify.app/databases/transactions/1d87aad1cc/