Tutorials/Exposed vs Storm: transactions

Transactions translate almost one to one

Exposed and Storm agree that a transaction is an explicit block of code. If you know one API you nearly know the other. This page maps the concepts and marks where they differ.

Series · Exposed to Storm5 min readKotlin

01The task

Write an order and an inventory change atomically, set isolation and a timeout, rerun on a deadlock, nest blocks, send a confirmation only after the commit, and do it from coroutine code.

02Where the two agree

Exposed made explicit transaction blocks the norm in Kotlin, with the settings at the call site:

OrderService.kt Kotlin · Exposed
1
2
3
4
5
6
7
8
9
10
11
12
13
// Exposed: the settings sit on the block
transaction(
    transactionIsolation = Connection.TRANSACTION_REPEATABLE_READ,
    readOnly = false,
) {
    maxAttempts = 3      // rerun the block on an SQLException
    queryTimeout = 5     // seconds, per statement

    Orders.insert { it[product] = productId; it[quantity] = 2 }
    Inventory.update({ Inventory.product eq productId }) {
        it[stock] = stock - 2
    }
}

Storm's block has the same shape:

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

transactionIsolation maps to isolation and readOnly to readOnly. Three settings map with a difference:

  • Reruns. Exposed's maxAttempts counts attempts and reruns a top-level block on any SQLException. Storm's retries counts reruns after the first attempt, so retries = 2 matches maxAttempts = 3. It reruns only on a failure the dialect classifies as transient, a deadlock or a serialization failure, plus an optimistic lock conflict; a constraint violation fails on the first attempt. A Storm block that joins an outer transaction refuses retries, since only the outer transaction can start over.
  • Timeout. Exposed's queryTimeout applies to each statement. Storm's timeoutSeconds is a deadline for the whole block: each statement runs with the time left, and a block that passes its deadline rolls back with TransactionTimedOutException.
  • Reads. Exposed runs every operation in a transaction, reads included. Storm's repositories take a connection per operation, and a block appears where atomicity matters.

03Nesting and propagation

In Exposed, a nested transaction block shares the outer transaction by default, and useNestedTransactions = true in the database configuration turns nested blocks into savepoints. Storm chooses per block, with the propagation names Spring uses:

OrderService.kt Kotlin · Storm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Nesting is chosen per block
transaction {
    orders.insertAndFetch(newOrder)

    transaction(propagation = NESTED) {
        // a savepoint for this block only
        audit.record(newOrder)
    }

    transaction(propagation = REQUIRES_NEW) {
        // an independent transaction that commits on its own
        metrics.bump("orders")
    }
}

The default, REQUIRED, joins the surrounding transaction, as Exposed does by default. NESTED is the savepoint mode. REQUIRES_NEW opens an independent transaction, MANDATORY and NEVER assert that a transaction is or is not active, and SUPPORTS and NOT_SUPPORTED cover code that may run without one.

04After the outcome

Code placed after a block runs too early when the block joined an outer transaction: the end of the inner block commits nothing, and the outer transaction can still roll back. Both libraries let you register work for after the commit instead. In Exposed, a StatementInterceptor registered on the transaction has afterCommit and afterRollback hooks:

OrderService.kt Kotlin · Exposed
1
2
3
4
5
6
7
8
transaction {
    registerInterceptor(object : StatementInterceptor {
        override fun afterCommit(transaction: Transaction) {
            mailer.sendConfirmation(order)
        }
    })
    Orders.insert { it[id] = order.id }
}

Storm registers a lambda on the block:

OrderService.kt Kotlin · Storm
1
2
3
4
5
6
7
8
9
10
transaction {
    val order = orders.insertAndFetch(newOrder)

    onCommit {
        mailer.sendConfirmation(order)   // after the physical commit
    }
    onRollback {
        metrics.increment("orders.failed")
    }
}

A Storm callback registered in a joined or NESTED block waits for the outermost physical transaction, so onCommit fires only when the data is durable. If the commit fails, onCommit is skipped and onRollback runs. With useNestedTransactions on, an Exposed nested block is a transaction of its own, so check which boundary its afterCommit follows. Exposed's interceptors also offer beforeCommit and statement-level hooks, and can be registered globally; Storm has no equivalent of those.

05Coroutines

Both libraries run transactions in coroutines: Exposed with suspendTransaction { }, Storm by making transaction a suspend function. A Storm 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
// Exposed: suspendTransaction { }. Storm: transaction is a suspend function
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 rolls the transaction back, so an aborted request does not keep its query running on the database.

06The translation table

ExposedStorm
transaction(transactionIsolation, readOnly)transaction(isolation, readOnly)
queryTimeout, per statementtimeoutSeconds, a deadline for the block
maxAttempts, reruns on any SQLExceptionretries, reruns on deadlocks, serialization failures and optimistic lock conflicts
Nested blocks share the transaction; useNestedTransactions for savepointsPropagation per block: REQUIRED, NESTED, REQUIRES_NEW and four more
StatementInterceptor.afterCommitonCommit { }, onRollback { }, onCompletion { }
suspendTransaction { }transaction { } is a suspend function
Reads run in a transactionRepositories take a connection per operation

07Keep going

The reference documentation covers the mechanics in depth: