Video in progress
How do you design routing read queries to replicas in a Spring Boot application, and where is it easy to make mistakes?
AbstractRoutingDataSource sends a readOnly transaction to the replica and everything else to the primary; LazyConnectionDataSourceProxy is needed so the decision is made once the readOnly flag is known. The main risks are stale data caused by replica lag and incorrectly marked readOnly.
📖 Answer
The basic setup:
public class RoutingDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return TransactionSynchronizationManager.isCurrentTransactionReadOnly()
? "replica" : "primary";
}
}
@Bean
@Primary
DataSource dataSource(DataSource primary, DataSource replica) {
var routing = new RoutingDataSource();
routing.setTargetDataSources(Map.of("primary", primary, "replica", replica));
routing.setDefaultTargetDataSource(primary);
routing.afterPropertiesSet();
return new LazyConnectionDataSourceProxy(routing);
}
Without LazyConnectionDataSourceProxy, JpaTransactionManager may take the connection before the readOnly flag is set, so everything goes to the primary and nobody notices. That's why my first job is to check in the metrics that queries really are reaching the replica.
Places where it's easy to slip:
- Lag. "I placed an order, and it's not in the list." After a write, "pin" that user's requests to the primary for a short time (a mark in a cookie or the session), or always read critical screens from the primary.
- Nested calls. The outer method is
readOnly = trueand the inner one wants to write: withREQUIREDpropagation it stays on the replica connection and getscannot execute UPDATE in a read-only transaction. - Several replicas. You need to spread the load among them and check their health; take a replica with a large lag out of rotation automatically.
- Cache. Reading stale data from a replica and writing it into the cache prolongs the staleness.
First I ask myself: is the primary really choking on reads? Often fixing indexes and queries, or a cache, is enough without replicas, and a replica adds permanent complexity.
Sign up to mark studied questions and save your progress.