Concurrency control with optimistic, pessimistic & advisory locks
@Version optimistic locking, SELECT ... FOR UPDATE pessimistic locking, Postgres advisory locks for gap-free numbering, and how to choose.
Optimistic locking: assume no conflict, detect it
Add a version column:
@Version
@Column(name = "version")
private Integer version;
Hibernate then writes:
UPDATE rooms SET current_occupancy = 4, version = 8
WHERE id = ? AND version = 7; -- 0 rows updated => someone else changed it
Zero rows updated throws ObjectOptimisticLockingFailureException, which you return as 409 or retry.
- ✅ No locks are held, so it scales well when conflicts are rare.
- ✅ It works across HTTP requests: send
versionto the client and back (the “lost update” protection for edit forms), or use ETags. - ❌ Under heavy contention, many requests fail and retry.
Pessimistic locking: lock first, then work
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("SELECT r FROM Room r JOIN FETCH r.hostel WHERE r.id = :id")
Optional<Room> findByIdForUpdate(UUID id);
// SQL: SELECT ... FOR UPDATE
Other transactions trying to lock the same row wait until you commit.
- ✅ Correct under heavy contention, with no retry logic.
- ❌ Holds the lock for the whole transaction, so keep it short. Deadlocks are possible.
- Variants:
FOR UPDATE NOWAIT(fail immediately) andFOR UPDATE SKIP LOCKED(skip locked rows, ideal for job queues: many workers each grab different rows).
Advisory locks: lock an idea, not a row
jdbc.sql("SELECT pg_advisory_xact_lock(hashtextextended(?, 0))")
.param("posting:" + companyId)
.query().singleValue();
This takes an application-defined lock keyed by a number (here, a hash of "posting:<companyId>"). The _xact_ variant is released automatically at commit or rollback. Use it to serialise an operation that has no single row to lock.
In your projects
Room.java (@Version) · RoomRepository.findByIdForUpdate · BookingService.approveBookingHostel uses both:
@VersiononRoomcatches stray concurrent edits, andGlobalExceptionHandlermaps them to 409.approveBooking()takes aPESSIMISTIC_WRITElock on the room, then re-checks capacity while holding the lock, then increments occupancy and bulk-rejects the other pending bookings for that room.
Approval is the high-contention moment (many students, one bed), so a pessimistic lock is the right tool there.
WalletRepository.java:22 · EarningsHoldRepository · CreatorRefundRepository@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("SELECT w FROM Wallet w WHERE w.user.id = :userId")
Optional<Wallet> findByUserIdForUpdate(UUID userId);Every money movement locks the wallet first, so two simultaneous withdrawals can’t both pass the balance check.
DefaultPostingEngine · JdbcDocumentNumbers · UserSessionRepository- Advisory lock per company so journal numbers are gap-free (
JE-000001,JE-000002, …), which auditors require. A PostgresSEQUENCEis not gap-free, because rolled-back transactions consume values. @Lock(PESSIMISTIC_WRITE)onUserSessionmakes refresh-token replay detection run one request at a time. Two parallel refreshes with the same token can’t both succeed.@Versioncolumns on aggregates, with 409 on conflict.
How to choose
| Situation | Use |
|---|---|
| Edit forms, rare conflicts | Optimistic (@Version) |
| Hot row, must not oversell (beds, wallet balance, stock) | Pessimistic FOR UPDATE |
| A simple counter | Atomic SQL SET qty = qty - 1 WHERE qty > 0 (often the best option) |
| Serialise an operation with no single row (numbering, “one import per company”) | Advisory lock |
| Worker queue in Postgres | FOR UPDATE SKIP LOCKED |
| Across multiple app instances, non-DB resource | A distributed lock (Redis/ShedLock, see the scaling lesson) |
Related concepts you must know
- Lock ordering prevents deadlocks. If you lock two wallets for a transfer, always lock the lower id first.
lock_timeout/statement_timeoutstop requests from waiting forever.- Row vs table locks.
FOR UPDATEis row-level, while someALTER TABLEs take table-level locks. - Idempotency keys often complement locks (Module 6).