Transaction routing (tx)
jeap-spring-boot-tx provides read-replica-aware transaction routing for Spring's standard
transaction management. Together with the
PostgreSQL AWS starter it lets explicitly marked
read-only transactions run against an AWS RDS read replica while all other transactions go to the
primary (writer), relieving the writer from read-heavy load. The module carries no AWS SDK
dependency, so the @TransactionalReadReplica annotation can be used in modules that should not
depend on the RDS starter directly.
Because the replica page cache is updated asynchronously, reads from a replica are only eventually consistent — route there only when a short staleness window is acceptable (dashboards, UIs, read-only consumers), and never for read-after-write patterns where the caller must see just-written data.
How it works
JeapTxTransactionAutoConfig registers two static bean post-processors:
ReadReplicaAwareTransactionManagerBeanPostProcessorwraps the application's defaulttransactionManagerin aReadReplicaAwareTransactionManager(with replica routing off) — so ordinary@Transactionalwork is unchanged but the consistency checks below still apply.ReadReplicaTransactionManagerBeanDefinitionRegistryPostProcessormakes a bean namedreadReplicaTransactionManageralways available. Whenjeap.datasource.replica.enabled=trueit registers a secondReadReplicaAwareTransactionManagerwith replica routing on; when the replica is disabled it simply aliasesreadReplicaTransactionManagertotransactionManager, so the same annotations work transparently in non-replica (and local) environments.
ReadReplicaAwareTransactionManager is a wrapper around the real PlatformTransactionManager. On a
top-level transaction it records, in thread-locals, whether the transaction is read-only and whether
it should route to the replica. ReadReplicaAwareTransactionRoutingDataSource (an
AbstractRoutingDataSource configured by the PostgreSQL AWS starter) reads that flag and resolves
the lookup key to reader or writer accordingly. The routing decision is taken once, when the
top-level transaction is opened.
The manager also enforces consistency: it forbids opening a read-write transaction nested inside a
read-only top-level transaction, and (when routing to the replica) rejects a read-write top-level
transaction annotated for the replica. This fails fast — including in unit/integration tests — and
prevents two subtle bugs: Hibernate setting flush mode to NEVER (silently dropping writes) and a
read replica refusing writes at runtime.
Two Micrometer counters are exported: jeap_db_transaction_readreplica (transactions routed to a
read replica) and jeap_db_transaction_rw (writer-instance transactions).
The module also provides AWS JDBC failover retry advice. Individual operations can opt in with
@RetryOnDatabaseFailover, or applications whose transactional operations are retry-safe can enable
the advice globally. It recognizes only the AWS Advanced JDBC Wrapper's FailoverSuccessSQLException
with SQL state 08S02. When an invocation starts its own transaction, the retry advice repeats the
ordinary Spring transaction interceptor so that every attempt gets a fresh transaction. An invocation
that participates in an existing transaction is not retried and retains normal REQUIRED atomicity.
Transaction state unknown (08007) and other connection failures are deliberately not retried.
In particular, AWS Advanced JDBC Wrapper 4.4 reports a failover during an active transaction as
08007; this advice therefore does not recover that in-flight transaction. It only automates replay
for the unambiguous 08S02 case where the wrapper reports that the connection changed successfully.
See the AWS failover exception codes.
The local tests inject exceptions to verify replay and rollback mechanics; they do not simulate an
RDS failover or establish recovery of an interrupted database transaction.
Using @TransactionalReadReplica
@TransactionalReadReplica is a meta-annotation over @Transactional, bound to
readReplicaTransactionManager with readOnly = true. Annotate a read-only method to route its
transaction to the replica (or to the writer if no replica is configured):
import ch.admin.bit.jeap.db.tx.TransactionalReadReplica;
@TransactionalReadReplica // -> read replica if available, else writer
public List<Order> listOrders() {
return orderRepository.findAll();
}
@Transactional // -> always the writer instance
public void placeOrder(Order order) {
orderRepository.save(order);
}
For programmatic transaction management, inject the manager by name:
@Autowired
@Qualifier("readReplicaTransactionManager")
PlatformTransactionManager readReplicaTransactionManager;
TransactionTemplate template = new TransactionTemplate(readReplicaTransactionManager);
The annotation forwards the usual @Transactional attributes (propagation, isolation, timeout,
timeoutString, rollbackFor, rollbackForClassName, noRollbackFor, noRollbackForClassName).
Retrying after a database failover
The platform-independent @RetryOnDatabaseFailover annotation can be used across deployment
platforms. The current implementation supports only AWS JDBC failover errors described above;
the annotation alone does not add failover recovery for RHOS or other drivers.
@RetryOnAwsJdbcFailover remains available as a deprecated compatibility alias, including its
maxAttempts and backoffMillis attributes. Migrate by changing the annotation name and import.
The AWS-specific global configuration properties remain unchanged.
Annotate only operations that are safe to repeat. The default is one retry after a 100 ms backoff:
import ch.admin.bit.jeap.db.tx.RetryOnDatabaseFailover;
@RetryOnDatabaseFailover
@Transactional
public void updateOrder(Order order) {
orderRepository.save(order);
}
maxAttempts includes the initial call. Both values can be customized per operation:
@RetryOnDatabaseFailover(maxAttempts = 3, backoffMillis = 250)
@Transactional
public void updateOrder(Order order) {
orderRepository.save(order);
}
Applications in which all REQUIRED transactional operations are safe to repeat can enable retries
globally. This mode is disabled by default:
jeap:
datasource:
aws:
failover-retry:
enabled: true
max-attempts: 2
backoff-millis: 100
An explicitly annotated outer retry boundary uses the values from its annotation, overriding the global
defaults. In global mode, transactional methods with propagation modes other than REQUIRED are left
unchanged. Nested transactional calls participate in the outer retry attempt and do not create additional
retry loops or independent transaction boundaries. A REQUIRED operation entered while another transaction
is already active participates in that transaction without retry; this prevents a nested operation from
committing independently if its caller later rolls back.
Because retries repeat Spring's normal transaction interceptor, they use the same transaction manager and
rollback behavior that Spring selects for @Transactional, including an
explicit transaction-manager name, a class-level qualifier, or a default supplied through
TransactionManagementConfigurer.
A matching exception is retried only after an observed successful rollback, or a failed transaction
begin before the business method ran. Spring's transaction execution callbacks provide this information.
Checked exceptions and noRollbackFor rules can cause Spring to commit despite an exception; those
attempts are not repeated. Commit attempts (including failed commits and nested independent commits)
and failed rollbacks also prevent replay.
Completion tracking is registered on Spring ConfigurableTransactionManager beans, including the
standard JDBC and JPA transaction managers. Custom managers without these callbacks continue to execute
normally, but their unobserved outcomes are not retried.
@RetryOnDatabaseFailover requires @Transactional with its default REQUIRED propagation. Other
propagation modes are unsupported. The advice preserves Spring's transaction boundaries and does not
replace propagation with REQUIRES_NEW.
Enable either mode only for operations that do not perform non-idempotent effects outside their database
transaction. Enabling the global mode declares that all matching transaction boundaries in the application
are safe to repeat. In particular, 08007 means that the outcome of the old transaction is unknown and
therefore requires an application-specific reconciliation decision.
Configuration
| Property | Default | Description |
|---|---|---|
jeap.datasource.replica.enabled | false | Enable read-replica transaction routing |
jeap.datasource.aws.failover-retry.enabled | false | Retry eligible top-level REQUIRED invocations on 08S02 |
jeap.datasource.aws.failover-retry.max-attempts | 2 | Maximum attempts in global mode, including the initial call |
jeap.datasource.aws.failover-retry.backoff-millis | 100 | Delay between attempts in global mode |
Common pitfalls
- Nested read-write in read-only — refactor so the top-level transaction matches the most
permissive operation; the manager throws an
IllegalStateExceptionotherwise. spring.jpa.open-in-view— enabled by default in Spring Boot, it keeps the first transaction open across a web request and can trigger the consistency check for an unannotated read-only entry point; annotate the entry method with@Transactionalto mark the top-level transaction read-write.- Stale reads — only annotate methods whose reads tolerate replication lag.
- Unsafe failover retry — use the annotation or global mode only when repeating the complete method is safe. The interceptor cannot determine business idempotency.