Tutorials/Optimistic locking

Optimistic locking with immutable entities

Two people edit the same record, and the second save must not overwrite the first. JPA and Storm both use a version column for this. They differ in when the check runs and in what you hold when it fails.

Series · JPA to Storm5 min readKotlin

01The task

An owner record is open in two browser tabs. Both tabs edit it and save. Without a guard, the later save overwrites the earlier one. A version column turns that into an error the application can handle.

02The JPA way

JPA puts @Version on the entity and checks it in the UPDATE it writes:

OwnerService.kt Kotlin · JPA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Entity
class Owner(
    @Id @GeneratedValue var id: Int? = null,
    var firstName: String = "",
    var lastName: String = "",
    @Version var version: Int = 0,
)

@Transactional
fun rename(id: Int, lastName: String) {
    val owner = ownerRepository.findById(id).orElseThrow()
    owner.lastName = lastName
    // the UPDATE and its version check run at flush, here at commit
}

Changing a managed entity schedules the UPDATE for the next flush. In a Spring @Transactional method that is usually the commit, after the method body has run, so the conflict surfaces as ObjectOptimisticLockingFailureException where the transaction ends. saveAndFlush() moves the check to the call. Across two requests, the version from the form reaches the check through a detached entity and merge().

03The Storm way

Storm has no persistence context. The update runs when you call it, and it checks the version that the entity value carries:

OwnerService.kt Kotlin · Storm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
data class Owner(
    @PK val id: Int = 0,
    val firstName: String,
    val lastName: String,
    @Version val version: Int = 0,
) : Entity<Int>

val owners = orm.entity(Owner::class)

// GET: the version leaves with the record
val owner = owners.getById(ownerId)

// PUT: the version comes back with the edit
val updated = owners.updateAndFetch(owner.copy(lastName = form.lastName, version = form.version))
↳ generated sql
UPDATE owner
SET first_name = ?, last_name = ?, version = version + 1
WHERE id = ? AND version = ?
-- no row matched: OptimisticLockException, thrown by this call

The version travels to the client with the record and comes back with the edit. copy() puts it on the entity, and the UPDATE matches no row when another save got there first. updateAndFetch() returns the row with its new version, ready for the next edit.

04Handling the conflict

The entity you tried to write and the row in the database are both plain values, so the handler can compare them field by field:

OwnerService.kt Kotlin · Storm
1
2
3
4
5
6
7
8
val edited = owner.copy(lastName = form.lastName, version = form.version)
try {
    owners.update(edited)
} catch (exception: OptimisticLockException) {
    val current = owners.getById(edited.id)
    // edited and current are both values: return them with a 409
    // and let the user decide which change wins
}

With the Spring Boot starter, the exception arrives as Spring's OptimisticLockingFailureException, with Storm's exception as the cause.

05Rerunning the transaction

OptimisticLockException is a TransientPersistenceException, like a deadlock or a serialization failure: running the whole transaction again may succeed. retries on the transaction block does that, each attempt in a transaction of its own:

OwnerCleanup.kt Kotlin · Storm
1
2
3
4
5
// Reads and writes in one block: a rerun reads the row again
transaction(retries = 2) {
    val owner = owners.getById(ownerId)
    owners.update(owner.copy(lastName = owner.lastName.trim()))
}

A rerun helps when the block reads the row it writes. The form above brings its version from the client, so a rerun would send the same stale version and fail again; return the conflict instead. A change computed from a column's current value, such as a counter or a stock level, needs no version: set it in the database with the update() builder, which also increments @Version on the rows it sets.

06Timestamp versions

If the table tracks a last-modified timestamp, it can serve as the version:

Visit.kt Kotlin · Storm
1
2
3
4
5
6
7
8
// A timestamp works as the version too
data class Visit(
    @PK val id: Int = 0,
    val visitDate: LocalDate,
    val description: String? = null,
    @FK val pet: Pet,
    @Version val timestamp: Instant?,
) : Entity<Int>

07Side by side

JPA with HibernateStorm
When the check runsAt flush, usually the commit; saveAndFlush() runs it at the callOn the update call
Version checked across requestsThe detached entity's, through merge()The one the entity value carries
Exception with SpringObjectOptimisticLockingFailureExceptionOptimisticLockingFailureException with the starter
Rerunning the transactionA retry around the transactional method, such as @Retryabletransaction(retries = 2) { }

08Keep going

The reference documentation covers the details: