BBackend CourseLeroy Labs
0/0
Search the course

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.

● advancedHostel-Web-AppIR3D (Kontentt)SperoTek (in dev)

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 version to 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) and FOR 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

Hostel-Web-AppRoom.java (@Version) · RoomRepository.findByIdForUpdate · BookingService.approveBooking

Hostel uses both:

  • @Version on Room catches stray concurrent edits, and GlobalExceptionHandler maps them to 409.
  • approveBooking() takes a PESSIMISTIC_WRITE lock 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.

IR3D (Kontentt)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.

SperoTek (in dev)DefaultPostingEngine · JdbcDocumentNumbers · UserSessionRepository
  • Advisory lock per company so journal numbers are gap-free (JE-000001, JE-000002, …), which auditors require. A Postgres SEQUENCE is not gap-free, because rolled-back transactions consume values.
  • @Lock(PESSIMISTIC_WRITE) on UserSession makes refresh-token replay detection run one request at a time. Two parallel refreshes with the same token can’t both succeed.
  • @Version columns 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)
  • Lock ordering prevents deadlocks. If you lock two wallets for a transfer, always lock the lower id first.
  • lock_timeout / statement_timeout stop requests from waiting forever.
  • Row vs table locks. FOR UPDATE is row-level, while some ALTER TABLEs take table-level locks.
  • Idempotency keys often complement locks (Module 6).

Check yourself

1. Why does SperoTek use an advisory lock instead of a Postgres SEQUENCE for journal numbers?
2. Many workers polling a jobs table without blocking each other should use…
3. Optimistic lock failure means…