Choosing JPA locking strategies for DDD aggregates
Compare pessimistic locks, optimistic versions, and expiring edit leases in Kotlin, then test order updates for deadlocks and stale writes.
A shipping change can pass every domain check and still commit after the order has started shipping. In these notes on Chapter 8 of Getting Started with Domain-Driven Development, I use that race to compare JPA locking modes and a lease that spans multiple HTTP requests.
The examples use Kotlin 1.9, Java 21, Spring Boot 3.x, and Spring Data JPA with Hibernate 6.
Reproduce a stale shipping decision
An operator starts shipping while a customer changes the address for the same order. Both transactions load PREPARING. The operator moves the order to SHIPPED and commits. The customer still has a Java object in PREPARING, so the aggregate’s validation passes and the address update can commit after shipment.
An ordinary snapshot read under InnoDB REPEATABLE READ or PostgreSQL READ COMMITTED does not take a write lock. The aggregate invariant is still useful, but it needs a mechanism to make a decision based on stale state fail. I distinguish a short database transaction from a user-facing edit session before choosing that mechanism.
flowchart TD
Start["Concurrent aggregate edits"]
Span{"One transaction<br/>for read and write?"}
Freq{"Frequent conflicts?"}
Pess["Pessimistic write lock"]
Opt["Optimistic version check"]
Off["Offline edit lease"]
Start --> Span
Span -->|"Yes"| Freq
Span -->|"No, user editing"| Off
Freq -->|"High"| Pess
Freq -->|"Low"| Opt
Serialize conflicting changes with a write lock
A repository query with @Lock(LockModeType.PESSIMISTIC_WRITE) asks the provider to lock rows for a subsequent update. With a compatible dialect, Hibernate issues a query comparable to SELECT ... WHERE order_number = ? FOR UPDATE. In the example, the second writer waits for the first transaction. It then sees the changed state or encounters a database-specific lock or serialization failure.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// com/example/shop/order/domain/OrderRepository.kt
package com.example.shop.order.domain
import jakarta.persistence.LockModeType
import jakarta.persistence.QueryHint
import org.springframework.data.jpa.repository.Lock
import org.springframework.data.jpa.repository.Query
import org.springframework.data.jpa.repository.QueryHints
import org.springframework.data.repository.Repository
import org.springframework.data.repository.query.Param
interface OrderRepository : Repository<Order, OrderNo> {
fun findById(id: OrderNo): Order?
@Lock(LockModeType.PESSIMISTIC_WRITE)
@QueryHints(
QueryHint(name = "jakarta.persistence.lock.timeout", value = "2000")
)
@Query("select o from Order o where o.number = :id")
fun findByIdForUpdate(@Param("id") id: OrderNo): Order?
fun save(order: Order): Order
}
Taking the same locks in the same order helps prevent deadlocks when a transaction really needs more than one root. A stable ascending ID is one simple convention. I also set a lock timeout appropriate to the database and verify the SQL and actual wait time. The jakarta.persistence.lock.timeout hint is not implemented identically by every provider and dialect. In MySQL, database settings such as innodb_lock_wait_timeout can affect the outcome. Spring Data JPA locking
Reject stale writes with an optimistic version
An entity with @Version includes its previously read version in the update condition. The database can update the row only while that version still matches. Hibernate treats a zero-row update as an optimistic conflict. At a Spring boundary, the failure can surface as ObjectOptimisticLockingFailureException or another translated optimistic locking exception.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// com/example/shop/order/domain/Order.kt (excerpt)
package com.example.shop.order.domain
import jakarta.persistence.EmbeddedId
import jakarta.persistence.Entity
import jakarta.persistence.EnumType
import jakarta.persistence.Enumerated
import jakarta.persistence.Table
import jakarta.persistence.Version
@Entity
@Table(name = "purchase_order")
class Order(
@EmbeddedId val number: OrderNo,
@Enumerated(EnumType.STRING) var state: OrderState,
@Version var version: Long = 0,
) {
fun matchVersion(expectedVersion: Long): Boolean = this.version == expectedVersion
fun changeShippingInfo(newShippingInfo: ShippingInfo) {
verifyNotYetShipped()
// Update the shipping address here
}
private fun verifyNotYetShipped() {
check(state == OrderState.PAYMENT_WAITING || state == OrderState.PREPARING) {
"Cannot change an order after shipment starts."
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// com/example/shop/order/application/ChangeShippingService.kt
package com.example.shop.order.application
import com.example.shop.order.domain.OrderNo
import com.example.shop.order.domain.OrderRepository
import com.example.shop.order.domain.ShippingInfo
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
data class ChangeShippingRequest(
val orderNumber: String,
val shippingInfo: ShippingInfo,
val version: Long,
)
@Service
class ChangeShippingService(
private val orderRepository: OrderRepository,
) {
@Transactional
fun changeShipping(request: ChangeShippingRequest) {
val order = orderRepository.findById(OrderNo(request.orderNumber))
?: throw NoOrderException(request.orderNumber)
if (!order.matchVersion(request.version)) {
throw VersionConflictException("Another user has already updated the order.")
}
order.changeShippingInfo(request.shippingInfo)
}
}
The example sends the expected version from the request so an edit opened in one HTTP request can be checked on a later save. The database version condition still matters because another transaction can commit after the explicit comparison. Handle optimistic exceptions at a boundary that includes flush or commit, where they can actually occur.
If a change touches a child row without making Hibernate increment the version on purchase_order, two actions can each believe the root version is current. A lock with OPTIMISTIC_FORCE_INCREMENT can force the root version forward for an operation that needs the entire aggregate to carry one concurrency token. Verify your collection mapping’s behavior against real SQL before choosing this mode.
Use an expiring lease for long edit sessions
When a back-office operator opens an edit form, the transaction that served the page can end long before the next request. Holding a database lock for that duration would consume a connection. The offline example gives each editor a token in a locks table with a unique (type, id) key and an expiration time.
1
2
3
4
5
6
7
8
9
10
11
// com/example/shop/lock/LockManager.kt
package com.example.shop.lock
data class LockId(val value: String)
interface LockManager {
fun tryLock(type: String, id: String): LockId
fun checkLock(lockId: LockId)
fun releaseLock(lockId: LockId)
fun extendLockExpiration(lockId: LockId, incMillis: Long)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// com/example/shop/lock/SpringLockManager.kt
package com.example.shop.lock
import org.springframework.dao.DuplicateKeyException
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.stereotype.Component
import org.springframework.transaction.annotation.Propagation
import org.springframework.transaction.annotation.Transactional
import java.sql.Timestamp
import java.util.UUID
@Component
class SpringLockManager(
private val jdbcTemplate: JdbcTemplate,
) : LockManager {
private val lockTimeoutMillis: Long = 5 * 60 * 1000L
@Transactional(propagation = Propagation.REQUIRES_NEW)
override fun tryLock(type: String, id: String): LockId {
val rows = jdbcTemplate.query(
"select expiration_time from locks where type = ? and id = ?",
{ rs, _ -> rs.getTimestamp("expiration_time").time },
type, id,
)
if (rows.isNotEmpty()) {
if (rows.first() > System.currentTimeMillis()) throw AlreadyLockedException()
jdbcTemplate.update("delete from locks where type = ? and id = ?", type, id)
}
val lockId = LockId(UUID.randomUUID().toString())
try {
jdbcTemplate.update(
"insert into locks (type, id, lockid, expiration_time) values (?, ?, ?, ?)",
type, id, lockId.value, Timestamp(System.currentTimeMillis() + lockTimeoutMillis),
)
} catch (ex: DuplicateKeyException) {
throw LockingFailException(ex)
}
return lockId
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
override fun checkLock(lockId: LockId) {
val rows = jdbcTemplate.query(
"select expiration_time from locks where lockid = ?",
{ rs, _ -> rs.getTimestamp("expiration_time").time },
lockId.value,
)
if (rows.isEmpty() || rows.first() < System.currentTimeMillis()) {
throw LockExpiredException()
}
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
override fun releaseLock(lockId: LockId) {
jdbcTemplate.update("delete from locks where lockid = ?", lockId.value)
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
override fun extendLockExpiration(lockId: LockId, incMillis: Long) {
val updated = jdbcTemplate.update(
"update locks set expiration_time = ? where lockid = ?",
Timestamp(System.currentTimeMillis() + incMillis),
lockId.value,
)
if (updated == 0) throw LockExpiredException()
}
}
REQUIRES_NEW makes lease operations commit independently of the business transaction. The unique key provides an atomic check when concurrent insertions target the same object. The excerpt sketches the lease mechanism. In production, make expired-row replacement atomic as well. A client that read an expired row can otherwise delete a newer lease when the delete predicates only on the resource ID. Guard refresh and release with ownership and expiration, and make the protected write reject a stale token if a lease expires between checking and saving.
Choose by the contention you can tolerate
| Concern | Pessimistic write lock | Optimistic version | Offline edit lease |
|---|---|---|---|
| Conflict handling | Contenders wait or fail on the database lock | A stale update fails its version check | Only a holder of a valid token may edit |
| Duration | One short database transaction | One transaction or a version passed across requests | Multiple HTTP requests until release or expiration |
| Operational risk | Long waits and deadlocks if locks are taken in different orders | Retries under contention. The SQL write can still wait on database locks. | Orphaned or stale leases if expiration and ownership are mishandled |
| Typical use | Frequent conflicts over inventory or settlement rows | Infrequent order or profile changes | An exclusive back-office editing session |
A transaction that holds a pessimistic lock should stay short. Avoid network calls while it holds the database connection and row lock.
- Reproduce the shipping race with two transactions and assert that the stale update fails.
- Release offline leases when an edit completes and allow them to expire when a browser closes. Renew only a lease the same owner still holds.
- Retry a transient conflict only when the whole operation can run safely against new state. If the order has shipped, return
409 Conflictand let the user review the current state. - Confirm how lock timeouts and optimistic failures surface to the application, including failures at commit.
