Why does a Kotlin Spring service's @Transactional suspend transfer function, running JdbcTemplate updates under DataSourceTransactionManager, leave the debit committed when the credit fails, and how do you fix it?
answer
- which manager the interceptor resolves
- suspend call becomes a cold Mono
- commit happens before the await
- thread-bound path never sees the body
basics
~20 sUnder a thread-bound manager like DataSourceTransactionManager, @Transactional does not cover a suspend function's body: with kotlinx-coroutines-reactor present the body runs after the commit, so each statement auto-commits. Fix it with a non-suspend transactional method, or R2DBC with a reactive manager.
solid answer
~50 sSpring's transaction interceptor branches on the manager it resolves. With a `ReactiveTransactionManager` such as `R2dbcTransactionManager`, `TransactionAspectSupport` adapts the suspend method to a `Mono` (a `Flux` for a `Flow` return) and the transaction rides the Reactor context, so commit or rollback follows the body's outcome. With a thread-bound `PlatformTransactionManager` like `DataSourceTransactionManager` it takes the ordinary path: when kotlinx-coroutines-reactor is on the classpath the proxy turns the call into a cold `Mono`, the interceptor treats it as a plain return value and commits an empty transaction, and only then does the proxy await it. The debit and credit therefore run with no transaction bound and each auto-commits. Without that library, the transaction ends the first time the function actually suspends. Fix: put the JDBC work in a non-suspend `@Transactional` method called through `withContext(Dispatchers.IO)`, or move to R2DBC with a reactive manager, where `@Transactional`, `executeAndAwait` or `Flow.transactional(operator)` cover the work.
code
kotlin · 13 linesimport org.springframework.jdbc.core.JdbcTemplate
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
class BrokenTransferService(private val jdbc: JdbcTemplate) {
@Transactional
suspend fun transfer(from: Long, to: Long, amount: Long) {
jdbc.update("UPDATE account SET balance = balance - ? WHERE id = ?", amount, from)
jdbc.update("UPDATE account SET balance = balance + ? WHERE id = ?", amount, to)
}
}go deeper
Recall that @Transactional on a Kotlin suspend function is not automatically safe: whether the body is covered depends on which kind of transaction manager the application uses.
Explain the two paths: a reactive manager adapts the suspend call to a Mono or Flux and keeps the transaction in the Reactor context, while a JDBC or JPA manager uses plain begin, call, commit.
Diagnose the half-committed transfer precisely: with kotlinx-coroutines-reactor the proxy returns a cold Mono, the interceptor commits first and the body runs later, so pick a non-suspend transactional unit or a reactive stack.
Weigh the team rule: keep JDBC and fence transactional work into non-suspending methods, or adopt R2DBC end to end; add a review or test guard for suspend functions on thread-bound managers.
## The symptom A Kotlin service on Spring exposes `@Transactional suspend fun transfer(from, to, amount)`. Inside, it issues two `JdbcTemplate` updates: debit one account, credit another. The application's only transaction manager is `DataSourceTransactionManager`, which binds a JDBC connection to the **current thread**. When the credit fails, the exception reaches the caller, yet the debit is already in the database. The annotation looked right; the transfer was never atomic. The cause is not the coroutine's thread hopping in general. It is the order in which Spring's proxy and its transaction interceptor handle a **suspend function**: a compiled Kotlin method that takes a hidden `Continuation` as its last parameter. Spring detects that parameter and changes how it invokes and awaits the method. ## How the interceptor chooses a path `TransactionAspectSupport.invokeWithinTransaction` first resolves the transaction manager for the method, then branches: | Manager resolved | What happens to a suspend function | |---|---| | `ReactiveTransactionManager` (e.g. `R2dbcTransactionManager`) | Adapted to a `Mono`, or a `Flux` when it returns `Flow`; begin, commit and rollback are wired around that publisher | | Thread-bound `PlatformTransactionManager` (JDBC, JPA) | Ordinary blocking demarcation: begin, call, commit when the call returns | On the **reactive path** the transaction is created when the publisher is subscribed and stored in the Reactor context, not in a `ThreadLocal`. The commit is chained after the body completes, and an error signal triggers the rollback rules. kotlinx-coroutines-reactor carries that Reactor context into the coroutine, so R2DBC calls the body awaits join the transaction. On the **thread-bound path** the interceptor knows nothing about coroutines. It calls the next element in the chain, takes whatever comes back as the return value, and commits. ## Why the body escapes on the thread-bound path What comes back depends on whether **kotlinx-coroutines-reactor** is on the classpath (it is whenever Spring's coroutine support is enabled): 1. **Library present.** The proxy invokes the suspend function through a `mono { }` builder, which is **cold**: nothing in the body has run yet. The interceptor receives that `Mono`, sees a non-null return value that is not a `Future`, and commits a transaction in which nothing happened. Only after the interceptor returns does the proxy's return-value handling await the `Mono`, and that is when the body executes. By then the connection has been released and no transaction is bound, so each `JdbcTemplate` statement takes a connection in its default **auto-commit** mode and commits on its own. The credit's exception surfaces to the caller, but the transaction it should have rolled back already committed, so rollback rules (`rollbackFor` included) are never consulted. 2. **Library absent.** The proxy calls the method reflectively with the caller's continuation. Code before the first real suspension point runs inside the transaction; at that point the method returns the coroutine suspension marker, the interceptor commits, and the rest of the body resumes later with no transaction. If no call actually suspends, the whole body happens to be covered, which makes this variant intermittent. Either way, the guarantee the annotation promises on a plain method does not carry over to a suspend function on a thread-bound manager. ## Fixes, by stack Keep JDBC and make the transactional unit non-suspending: - Move the two updates into a regular `@Transactional fun` on another bean and call it from the suspend function inside `withContext(Dispatchers.IO)`. The whole method runs synchronously on one thread, which is exactly what `DataSourceTransactionManager` needs. - Or use `TransactionTemplate.execute` inside that `withContext` block. Its callback is not a suspend lambda, so the compiler stops you from suspending inside it. Move to a reactive driver and use the coroutine-native forms: - With R2DBC and `R2dbcTransactionManager`, `@Transactional` on the suspend function takes the reactive path and covers the body. - Programmatically, `TransactionalOperator.executeAndAwait { }` runs a suspending block in a transaction, and `Flow.transactional(operator)` wraps a `Flow`. - Both programmatic forms need a `ReactiveTransactionManager`; a `TransactionalOperator` cannot be built from `DataSourceTransactionManager`. ## Catching it before production - Write an integration test that fails between the two writes and asserts the first one is absent afterwards. - Inside the body, `TransactionSynchronizationManager.isActualTransactionActive()` returns `false` on the broken thread-bound path, a cheap assertion in tests. - Treat `@Transactional` on a `suspend fun` as a review flag whenever the resolved manager is JDBC or JPA based. The rule to carry away: a suspend function is transactional only on the reactive path. On a thread-bound manager, the work that must be atomic has to live in code that does not suspend.
- What changes on the thread-bound path if kotlinx-coroutines-reactor is not on the classpath?The proxy calls the suspend method directly with the caller's continuation. Statements before the first real suspension run inside the transaction; when the method suspends it returns the suspension marker, the interceptor commits, and the remainder resumes with no transaction. If nothing actually suspends, the whole body is covered, so the bug appears intermittently rather than every time.
- With R2dbcTransactionManager, why does @Transactional on a suspend function returning Flow get a Flux rather than a Mono?`TransactionAspectSupport` checks whether a suspend function's declared return type is `kotlinx.coroutines.flow.Flow`. If so it adapts the call to a `Flux` and wraps begin and commit around the whole stream, so the transaction lasts until collection completes. For any other suspend function it uses a `Mono`, which commits once the single result is produced.
- @Transactional on a suspend function always wraps the whole body in one transaction.
- Adding rollbackFor fixes the half-committed transfer under a JDBC transaction manager.
- TransactionalOperator.executeAndAwait also works with DataSourceTransactionManager.
- The body stays covered as long as the coroutine never leaves the calling thread.
- Any transaction manager handles suspend functions once kotlinx-coroutines-reactor is present.