Spring › JPA

Routing readOnly JPA transactions to a PostgreSQL replica

Why readOnly JPA transactions leak to Primary in Spring Boot 4.0, how LazyConnectionDataSourceProxy fixes routing, and how replication lag breaks reads.

Routing readOnly JPA transactions to a PostgreSQL replica

I wired up @Transactional(readOnly = true) routing to offload read traffic to a PostgreSQL replica, only to watch monitoring show almost every query still hitting Primary. This post reproduces why routing leaks to Primary, compares two ways to fix it with LazyConnectionDataSourceProxy, and measures both replication lag failures and what readOnly actually changes inside Hibernate.

Tested on Spring Boot 4.0.3, Hibernate ORM 7.2.4.Final, Kotlin 2.2.21, JDK 21, and PostgreSQL 18.1 (1 Primary + 1 async streaming replica built with pg_basebackup -R). I ran Primary (172.19.0.2) and Replica (172.19.0.3) in Docker containers on a 12-core, 32GB RAM machine (Windows with Docker Desktop/WSL2).

The problem

I started with the classic AbstractRoutingDataSource snippet that checks TransactionSynchronizationManager.isCurrentTransactionReadOnly() and routes to either "replica" or "primary":

1
2
3
4
5
6
7
// src/main/kotlin/lab/DataSourceConfig.kt
class ReplicationRoutingDataSource : AbstractRoutingDataSource() {
    override fun determineCurrentLookupKey(): Any {
        val readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly()
        return if (readOnly) "replica" else "primary"
    }
}

To verify which PostgreSQL node actually handled each transaction, I ran select pg_is_in_recovery(), inet_server_addr() inside both a read-only and a read-write transaction. A streaming replica always reports pg_is_in_recovery() = true. Here is what came back:

1
2
readOnly tx  -> Where(txReadOnly=true,  inRecovery=false, serverAddr=172.19.0.2/32)
readWrite tx -> Where(txReadOnly=false, inRecovery=false, serverAddr=172.19.0.2/32)

Inside the method body, Spring confirmed txReadOnly=true, yet the database connection still pointed straight at Primary (172.19.0.2).

Why routing leaks to Primary

The bug comes down to execution order inside Spring’s transaction startup. When JpaTransactionManager.doBegin() starts a transaction, it calls HibernateJpaDialect.beginTransaction(), which immediately fetches a JDBC connection from the DataSource so it can call connection.setReadOnly(true). That getConnection() call triggers determineCurrentLookupKey().

The catch is that Spring doesn’t populate TransactionSynchronizationManager’s readOnly flag until prepareSynchronization() runs—after doBegin() returns. At the moment AbstractRoutingDataSource asks whether the transaction is read-only, the thread-local flag is still false, so every transaction falls back to "primary".

sequenceDiagram
    participant TM as JpaTransactionManager
    participant R as RoutingDataSource
    participant S as SyncManager
    TM->>R: getConnection() inside doBegin
    R->>S: isCurrentTransactionReadOnly()
    S-->>R: false (not set yet)
    R-->>TM: Primary connection
    TM->>S: prepareSynchronization(readOnly=true)

Wrapping the routing data source in LazyConnectionDataSourceProxy fixes the order. Instead of grabbing a real connection during doBegin(), the proxy returns a lightweight handle that merely records setReadOnly and setAutoCommit calls. It waits until the first SQL statement actually executes to acquire the physical connection and replay those settings. By then, prepareSynchronization() has already finished, so isCurrentTransactionReadOnly() returns true and routing picks the replica.

Since Spring Framework 6.1.2, LazyConnectionDataSourceProxy also provides setReadOnlyDataSource(...), letting you route read-only transactions without writing a custom AbstractRoutingDataSource subclass at all.

Fixing connection acquisition order

Here is the minimal configuration comparing both proxy setups.

1
2
3
4
5
6
// build.gradle.kts
dependencies {
    implementation("org.springframework.boot:spring-boot-starter-data-jpa")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    runtimeOnly("org.postgresql:postgresql")
}
1
2
3
4
5
6
7
8
9
10
11
# src/main/resources/application.yml
app:
  datasource:
    primary:
      jdbc-url: jdbc:postgresql://localhost:15444/lab
      username: lab
      password: ${DB_PASSWORD}
    replica:
      jdbc-url: jdbc:postgresql://localhost:15445/lab
      username: lab
      password: ${DB_PASSWORD}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// src/main/kotlin/lab/DataSourceConfig.kt
package lab

import com.zaxxer.hikari.HikariDataSource
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Primary
import org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy
import javax.sql.DataSource

@Configuration
class DataSourceConfig {

    @Bean
    @ConfigurationProperties("app.datasource.primary")
    fun primaryDataSource() = HikariDataSource().apply { poolName = "primary" }

    @Bean
    @ConfigurationProperties("app.datasource.replica")
    fun replicaDataSource() = HikariDataSource().apply { poolName = "replica" }

    @Bean
    @Primary
    fun dataSource(primaryDataSource: DataSource, replicaDataSource: DataSource): DataSource {
        val routing = ReplicationRoutingDataSource().apply {
            setTargetDataSources(mapOf<Any, Any>("primary" to primaryDataSource, "replica" to replicaDataSource))
            setDefaultTargetDataSource(primaryDataSource)
            afterPropertiesSet()
        }
        // Defer physical connection acquisition until the first SQL statement runs
        return LazyConnectionDataSourceProxy(routing)
        // Spring Framework 6.1.2+ alternative without a routing class:
        // LazyConnectionDataSourceProxy(primaryDataSource).apply { setReadOnlyDataSource(replicaDataSource) }
    }
}

Running the same service method against all three configurations confirmed the fix:

ConfigurationreadOnly transaction targetreadWrite transaction target
Routing data source onlyPrimary (inRecovery=false)Primary (172.19.0.2)
LazyConnectionDataSourceProxy + routingReplica (172.19.0.3, inRecovery=true)Primary (172.19.0.2)
LazyConnectionDataSourceProxy#setReadOnlyDataSourceReplica (172.19.0.3, inRecovery=true)Primary (172.19.0.2)

Replication lag and Hibernate readOnly behavior

Once read traffic actually reached the replica, a second issue surfaced immediately: read-after-write inconsistency. I ran a loop 1,000 times that saved a new member in a write transaction, committed, and immediately queried that ID in a readOnly transaction. Even though pg_stat_replication.replay_lag hovered around just 0.8ms on my local Docker network, the replica missed the freshly committed row 467, 444, and 429 times across three runs (a 44.4% median miss rate). When I set recovery_min_apply_delay = '100ms' on the replica to simulate real network or load lag, all 1,000 reads missed.

xychart-beta
    title "Immediate read-after-write miss rate on replica (%, median of 1,000 runs)"
    x-axis ["Natural lag (~0.8ms replay_lag)", "recovery_min_apply_delay = 100ms"]
    y-axis "missing (%)" 0 --> 100
    bar [44.4, 100]

I also verified what @Transactional(readOnly = true) changes inside Hibernate 7.2 regardless of whether routing is enabled. All three data source setups behaved identically:

BehaviorreadOnly transactionreadWrite transaction
session.hibernateFlushModeMANUALAUTO
session.isDefaultReadOnly / entity read-onlytrue / truefalse / false
Mutating an entity field then committing0 UPDATE statements, value unchanged1 UPDATE statement, value persisted
Calling save on a new entitycannot execute INSERT in a read-only transactionSucceeds

To check the memory and latency impact of skipping dirty checking, I loaded 100,000 entities from the same Primary node under both transaction modes. A readOnly transaction allocated 50.1MB versus 55.1MB for readWrite, because Hibernate skips creating dirty-checking snapshots for read-only entities. Median latency was 64.8ms vs. 64.3ms—well within measurement noise. In practice, readOnly pays off mainly by blocking accidental writes and trimming heap overhead, not by magically speeding up queries.

Choosing when to route and checklist

ScenarioRecommended routing
Lists, feeds, and analytics tolerating a few seconds of stalenessreadOnly → Replica
Post-submit confirmation or redirect screens reading newly written dataRead inside the write transaction, or force Primary
Payments, inventory, and balance checks needing linearizable readsAlways Primary
Single-node databaseSkip routing; still use readOnly for safety and memory

When not to use read/write routing: If you don’t have a replica or Primary CPU and I/O aren’t under pressure, routing only adds failure modes. And if most of your user flows write a record and immediately read it back, sub-millisecond replication lag is enough to break nearly half of those reads. Keep in mind that routing also means maintaining two separate HikariCP pools—if you need to size both pools without exhausting PostgreSQL connections, see HikariCP connection pool sizing and connection wait analysis.

Watch out for nested transactions and propagation: if a class is annotated with @Transactional(readOnly = true) and a write method overrides it with @Transactional, any internal readOnly method it calls joins the outer REQUIRED transaction and stays on Primary. The reverse is worse—calling a write method from inside an already-open readOnly transaction reuses the replica connection and fails with cannot execute INSERT in a read-only transaction. The outermost transaction always decides the route.

  • Wrap your routing DataSource with LazyConnectionDataSourceProxy (or use setReadOnlyDataSource).
  • Add an integration test asserting pg_is_in_recovery() or inet_server_addr() for both transaction modes.
  • Audit read-after-write flows and pin them to Primary.
  • Monitor pg_stat_replication.replay_lag and define an acceptable lag threshold for alerts.
  • Make “outermost transaction decides routing” part of your team’s code review checklist.
This post is licensed under CC BY 4.0 by the author.