Tutorials/Transactions

Transactions as blocks

@Transactional applies through a proxy around the bean, and the proxy has rules about which calls it sees. Storm's transaction is a block of code, and its scope is what the block encloses.

Series · JPA to Storm6 min readKotlin

01The task

Insert an order and decrease the inventory in one transaction. Send the confirmation email only once the transaction has committed.

02The Spring way

@Transactional makes the method atomic. It works through a proxy that wraps the bean, and the proxy only sees calls that go through it:

OrderService.kt Kotlin · Spring
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Service
class OrderService(
    private val orders: OrderRepository,
    private val mailer: Mailer,
) {
    @Transactional
    fun placeOrder(order: Order) {
        orders.save(order)
        mailer.sendConfirmation(order)   // sent before the commit
    }

    fun importAll(batch: List<Order>) {
        batch.forEach { placeOrder(it) }   // a call on this: no proxy, no transaction
    }
}

The snippet has two bugs, and neither fails a test on the happy path. The email goes out before the commit, so a failing commit leaves a customer with a confirmation for an order that does not exist. Spring's fix is to publish an event and handle it in a @TransactionalEventListener, or to register a TransactionSynchronization. And importAll calls placeOrder on this, which bypasses the proxy in Spring's default proxy mode: the orders are saved without the transaction the annotation asks for, and nothing in the log says so.

03The Storm way

Storm's transaction is a function you call with a block. The scope is the block, in any class, method or visibility:

OrderService.kt Kotlin · Storm
1
2
3
4
5
6
// The transaction is the block
transaction {
    val order = orders.insertAndFetch(newOrder)
    inventory.decrease(order.product, order.quantity)
}
// commits when the block returns, rolls back when it throws

There is no proxy, so calling a function that opens a transaction block from the same class behaves like calling it from anywhere else. Nested blocks follow the propagation they state, REQUIRED by default.

04Side effects after the outcome

Register the email as a callback inside the block. Running it after the block is not the same thing: with REQUIRED propagation the block may have joined an outer transaction, so the end of the block commits nothing and the outer transaction can still roll back. Callbacks bind to the physical transaction, so they fire on its outcome however deeply the block is nested:

OrderService.kt Kotlin · Storm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
transaction {
    val order = orders.insertAndFetch(newOrder)
    inventory.decrease(order.product, order.quantity)

    onCommit {
        // runs after the commit succeeded
        mailer.sendConfirmation(order)
        events.publish(OrderCreated(order))
    }

    onRollback {
        metrics.increment("orders.failed")
    }
}

onCommit runs once the data is durable. If the commit fails, it is skipped and onRollback runs instead. onCompletion { committed -> } covers work that has to happen either way.

05Settings at the call site

Propagation, isolation, timeout, read-only and reruns are parameters of the block, so the transaction's guarantees are visible where it starts:

OrderService.kt Kotlin · Storm
1
2
3
4
5
6
// Isolation, timeout and reruns, stated at the call site
transaction(isolation = SERIALIZABLE, timeoutSeconds = 5, retries = 2) {
    inventory.decrease(newOrder.product, newOrder.quantity)
    val order = orders.insertAndFetch(newOrder)
    onCommit { mailer.sendConfirmation(order) }
}

Under SERIALIZABLE the database may refuse one of two concurrent transactions with a serialization failure. Storm classifies that failure, a deadlock and an optimistic lock conflict as a TransientPersistenceException, and retries = 2 runs the block up to two more times on one. Each attempt is a transaction of its own with its own timeout, and onCommit fires only for the attempt that committed. A constraint violation is not rerun. A block that joins an outer transaction refuses retries, because only the outer transaction can start over.

06Coroutines

transaction is a suspend function. The transaction travels with the coroutine, so switching dispatchers inside the block keeps it:

BatchJob.kt Kotlin · Storm
1
2
3
4
5
6
7
8
9
10
// A suspend transaction keeps its connection across dispatcher switches
transaction {
    val pending = orders.findAllPending()

    val updated = withContext(Dispatchers.Default) {
        heavyComputation(pending)
    }

    orders.update(updated)   // the same transaction
}

A repository call on the other dispatcher joins the same transaction. Cancelling the coroutine stops the statement the block is waiting on through the driver, and the transaction rolls back and releases its connection, so a request the client aborted does not keep its query running. For blocking code, transactionBlocking takes the same parameters. With a JDBC transaction manager, Spring's @Transactional does not support suspend functions; it needs a ReactiveTransactionManager for those.

07Mixing with Spring

In a Spring application the two systems bridge when the template is wired to Spring's transaction management. The Spring Boot starters do this when a transaction manager is present; outside Boot, build the template with springOrmTemplate. Storm's blocks then run through Spring's transaction manager: a transactionBlocking inside a @Transactional method joins the surrounding transaction, and onCommit waits for Spring's commit.

The suspend transaction is not available while Spring manages Storm's transactions, because Spring binds its transaction state to the calling thread; Storm refuses it with an error that says so. Applications written with suspend functions keep a Storm-managed template, as Ktor applications do. See Spring Integration.

08Side by side

Spring @TransactionalStorm
MechanismA proxy around the beanA function that takes a block
Self-invocationBypasses the transaction in proxy modeA block applies wherever it is called
After-commit effects@TransactionalEventListener or a TransactionSynchronizationonCommit and onRollback in the block
Rerun on deadlock@Retryable on a method around the transactionretries = 2 on the block
Suspend functionsNeed a ReactiveTransactionManagertransaction { } is a suspend function

09Keep going

The reference documentation covers the mechanics in depth: