What you'll learn: By the end of this lesson you will be able to explain the lost update and why it needs a defence, implement optimistic locking with a version column and retry, implement pessimistic locking with a row lock, say when each fits, explain how a deadlock forms and how a database detects it, and remove it with a consistent lock order, using a Spring Boot lab on an in-memory H2 database and a clear list of what a real PostgreSQL adds.
Two people edit the same shared spreadsheet row. The optimistic way is to make your change on a copy and, when you save, check that nobody changed the row since you copied it; if they did, you redo your edit. The pessimistic way is to put a "do not touch" sign on the row before you start, so the other person waits. The first costs nothing when conflicts are rare and some rework when they happen; the second costs waiting every time, but never rework. A deadlock is two people each holding a sign the other needs.
Databases: Basics introduces transactions. The lesson backend-acid-and-isolation-levels names the guarantees, MVCC shows how PostgreSQL stores versions so readers do not block, and this lesson covers what happens when two writers want the same row. Spring's @Transactional has its own lesson, backend-spring-transactional. For locks across several services, see Distributed locks and fencing tokens.
Verified with Spring Boot 4.1.2, Java 25, H2 2.4.240, the PostgreSQL 18 documentation and the Jakarta Persistence 3.2 specification, on 2026-12-01.
The core idea
Two transactions that read a value, compute from it and write it back can overwrite each other's work. Optimistic locking detects the overwrite at write time with a version check and makes the loser retry; pessimistic locking prevents it by making the second transaction wait at a row lock; a deadlock is a cycle of waits that the database breaks by aborting one transaction.
Three labelled illustrations run through it: the minimal example (two buyers and one stock row, in the lab), the realistic example (ShopStream's checkout reserving stock) and the failure example (two transactions locking two rows in opposite order).
The lost update
Stock is 10. Alice and Bob each read it, each subtract one, each write 9. Both sales happened and the stock says 9. Nothing failed; a write silently replaced another. An explicit defence is needed whenever code reads, computes outside the database, then writes.
Figure 1. A write built on a stale read. How to read this: the write by Alice is computed from a value that stopped being true when Bob committed. Both defences in this lesson attack the gap between the read and the write.
There is a third option that needs neither: let the database do the arithmetic. PostgreSQL's documentation says that in Read Committed, a second updater that waited for the first to commit applies its operation to the updated version of the row after re-evaluating its WHERE clause. So update item set stock = stock - 1 where id = ? and stock > 0 is safe on its own. Locking is for the cases where the computation cannot be one statement: validate against several rows, call another service, or show the user a form and save later.
Optimistic locking
Add a version column. A reader remembers the version it saw. The write says "set the new value, and bump the version, but only if the version is still the one I read". If zero rows change, someone else got there first: report a conflict or retry from a fresh read. No lock is held between the read and the write, so a user can think for minutes.
The Jakarta Persistence specification calls this an entity version: "a persistent field or property used by the persistence provider to perform optimistic locking", marked with @Version, and a mismatch makes the provider throw OptimisticLockException. The lab writes the SQL by hand so you can see the check:
public int updateIfVersionUnchanged(Item readCopy, int newStock) {
return jdbc.sql("update item set stock = ?, version = version + 1 where id = ? and version = ?")
.param(newStock).param(readCopy.id()).param(readCopy.version()).update();
}
tx.executeWithoutResult(status -> {
if (items.updateIfVersionUnchanged(readCopy, newStock) == 0) {
throw new OptimisticConflictException(readCopy.id(), readCopy.version());
}
});
A conflict is not an error to hide: the caller decides. A web form shows "this record changed, reload"; a batch job reads again and retries a bounded number of times, which is why the lab's retry takes a maximum.
Pessimistic locking
Take the lock first. select ... for update returns the row and locks it. The PostgreSQL manual says FOR UPDATE "prevents them from being locked, modified or deleted by other transactions until the current transaction ends", and that row-level locks "do not affect data querying; they block only writers and lockers to the same row". Jakarta Persistence exposes the same idea as LockModeType.PESSIMISTIC_WRITE, and Spring Data JPA lets you put @Lock on a repository query method. The lab uses the SQL:
public Item findForUpdate(long id) {
return jdbc.sql("select id, stock, version from item where id = ? for update").param(id).query(Item.class).single();
}
The second transaction waits at that statement until the first commits or rolls back, then reads the committed row, so no retry code is needed. The cost is hold time: the lock lasts until the transaction ends, so anything slow inside the transaction (a network call, a user prompt) makes every other writer queue. Two controls limit the waiting. A timeout makes the waiter give up. PostgreSQL's SELECT adds NOWAIT (error instead of waiting) and SKIP LOCKED (skip rows that are locked, "not suitable for general purpose work" but useful for queue tables read by several consumers).
Deadlocks
A deadlock needs two things: transactions that hold one lock while asking for another, and an order that differs between them. T1 locks item 1 then asks for item 2; T2 locks item 2 then asks for item 1; each waits for the other forever.
Figure 2. A cycle of waits. How to read this: each arrow labelled "waits for" is a wait. T1 waits for the lock T2 holds, and T2 waits for the lock T1 holds, so neither can proceed.
The database detects it by keeping a wait-for graph, with an edge from a waiting transaction to the one holding the lock it needs, and looking for a cycle. PostgreSQL's manual says it "automatically detects deadlock situations and resolves them by aborting one of the transactions involved, allowing the other(s) to complete", and that which one is aborted "is difficult to predict and should not be relied upon". The check is not free: deadlock_timeout is "the amount of time to wait on a lock before checking to see if there is a deadlock condition", one second by default, because the check is "relatively expensive". The error code for a detected deadlock is 40P01.
The manual's advice on avoiding them is "the best defense against deadlocks is generally to avoid them by being certain that all applications using a database acquire locks on multiple objects in a consistent order". Locking rows by ascending id is the usual rule. Keep transactions short, and treat a deadlock error as retryable: the aborted transaction did nothing permanent.
Choosing a strategy
Figure 3. A first-pass decision. How to read this: prefer the simplest tool that closes the read-write gap. The choice between the last two boxes is about how often writers collide and what a repeat costs.
What a real PostgreSQL adds
The lab runs on H2, an in-memory database. It shows the patterns, not PostgreSQL's behaviour. Reading the PostgreSQL manual, a real server adds:
- Four row-lock modes, not one:
FOR UPDATE,FOR NO KEY UPDATE,FOR SHAREandFOR KEY SHARE, with different conflicts.FOR KEY SHAREis weaker thanFOR SHAREand blocks only deletes and updates that change key values. MVCC shows that a row lock is stored inxmax, and the manual notes that locking a row can cause a disk write. NOWAITandSKIP LOCKEDon the locking clause.- A delayed detector.
deadlock_timeout(1 second by default) sets how long a waiter waits before the deadlock check runs, and the error is SQLSTATE40P01. - Isolation-level conflicts. Under Repeatable Read, updating a row another transaction changed after your snapshot fails with
could not serialize access due to concurrent update(40001), and the manual says the application must retry. That is optimistic behaviour built into the engine. - A named error for "lock not available", SQLSTATE
55P03, beside40P01for deadlocks and40001for serialization failures.
This lesson does not claim how PostgreSQL's deadlock victim is chosen, how long any lock wait takes, or any timing: none of that ran here.
Build it: locking in Spring on H2
This is the minimal example, with a failure case. Goal: see a lost update, an optimistic conflict and retry, a pessimistic wait, a lock timeout, a real deadlock and its fix, and the detection logic in an in-memory model. Not a real PostgreSQL: the database is H2 2.4.240 in memory, and the wait-for graph is a small Java class, named as a model.
Setup. From the repository (Docker is not needed):
cd examples/spring-labs
./gradlew :labs:locking-optimistic-pessimistic:test
It runs 7 tests, one of which compares the report below with the golden file examples/spring-labs/golden/locking-optimistic-pessimistic.txt, and five repeated runs gave the same report. The code is in examples/spring-labs/labs/locking-optimistic-pessimistic/. The test waits on H2's own session table (INFORMATION_SCHEMA.SESSIONS, whose BLOCKER_ID column names a blocking session) to know a transaction is really waiting.
Scenarios 1 to 3: lost update, conflict, retry. Without a version check the last writer wins and one sale vanishes. With the version column, the second writer updates zero rows and gets an OptimisticConflictException. The retry reads again and keeps both sales.
Expected output, captured from a real run (Spring Boot 4.1.2, Java 25, H2 2.4.240, 2026-12-01):
== 1. Without a version check the last writer wins (stock 10, two buyers each take 1)
after both writes: stock=9 version=2 (expected stock=8: one sale is lost)
== 2. Optimistic locking with a version column (stock 10, two buyers each take 1)
both read: Item[id=1, stock=10, version=0]
bob writes stock=9 where version=0 -> ok, now stock=9 version=1
alice writes stock=9 where version=0 -> 0 rows updated, OptimisticConflictException; still stock=9 version=1
== 3. Retry after an optimistic conflict (stock 10; another user takes 1 between our read and write)
attempts needed: 2; stock=8 version=2 (both sales kept)
Scenarios 4 and 5: pessimistic waits and timeouts. The first buyer locks the row and holds it; the second is blocked (H2 reports a blocking session), then reads the committed value when the first commits. With H2's lock timeout set to 600 ms, a second buyer who is kept waiting too long gives up with a Spring QueryTimeoutException and SQLSTATE HYT00; H2's documentation says that when connections change the same row the database waits "at most until the lock timeout expires".
Expected output, captured from a real run (the same run):
== 4. Pessimistic locking: the second buyer waits at the row lock (stock 10, two buyers each take 1)
first buyer holds the row lock; second buyer is blocked: true
first buyer commits, new stock 9
second buyer then reads the committed row, new stock 8
final: stock=8 version=2 (both sales kept, no retry code)
== 5. Pessimistic locking: a waiter gives up when the lock is held too long (H2 LOCK_TIMEOUT 600 ms)
second buyer after the timeout: QueryTimeoutException, SQLSTATE HYT00
first buyer commits, new stock 9
final: stock=9 version=1
Scenarios 6 and 7: a deadlock and its fix. Two transactions lock two rows in opposite order. H2 detects the cycle and rolls one back, shown by Spring as CannotAcquireLockException with SQLSTATE 40001. Which of the two is rolled back varies between runs, so the report prints only the count, and the final stocks show that one move survived. Scenario 7 runs the same two moves with both locking the lowest id first: no cycle, both commit.
Expected output, captured from a real run (the same run):
== 6. A deadlock in H2: transaction 1 locks item 1 then item 2, transaction 2 locks item 2 then item 1
transactions rolled back by the database: 1 of 2 (CannotAcquireLockException, SQLSTATE 40001)
the other transaction committed
which of the two is chosen is the database's decision, so the lab does not print it
final stocks, lowest first: [9, 11] (only the survivor's move was applied: one unit moved)
== 7. The same two moves, both locking the lowest id first: no cycle
transaction 1: committed
transaction 2: committed
final: item 1 stock=10 version=2, item 2 stock=10 version=2 (two moves in opposite directions cancel out)
Scenario 8: detection logic in a model. WaitForGraph stores "waiter waits for holder" edges and searches for a cycle. This is the idea, not any database's implementation:
public void addWait(String waiter, String holder) {
waitsFor.computeIfAbsent(waiter, k -> new LinkedHashSet<>()).add(holder);
}
Expected output, captured from a real run (the same run):
== 8. The detection logic on an in-memory wait-for graph (a model, not a database)
T1 waits for T2: cycle []
T2 waits for T3: cycle []
T3 waits for T1: cycle [T1, T2, T3], victim by 'youngest' policy: T3
victim removed: cycle []
Adding the third edge closes the cycle; the "youngest" policy (abort the transaction that started last) is one possible rule, not the one H2 or PostgreSQL uses.
Break it. In ItemStore.updateIfVersionUnchanged, remove and version = ? and the .param(readCopy.version()) that feeds it: the update no longer checks the version, and the conflict and retry tests fail. Restore both and re-run.
Left out: PostgreSQL's lock modes, NOWAIT, SKIP LOCKED, deadlock timing, JPA itself and several services.
Trade-offs
| Option | Gain | Cost | Wrong when |
|---|---|---|---|
Atomic UPDATE |
One statement, no lock code | Only for arithmetic on one row | The rule spans several rows or services |
| Optimistic (version column) | No lock held, scales on rare conflicts | Retries or user-visible conflicts | Conflicts are frequent, so work is repeated |
| Pessimistic (row lock) | No retries, simple reasoning | Waiting, deadlock risk, hold time | The transaction does slow work while holding the lock |
| Fixed lock order | Removes lock-order deadlocks | Needs discipline across all code paths | Locks are taken in places you cannot see |
SKIP LOCKED |
Workers never wait on each other | Rows are skipped, so views are inconsistent | You need every row, in order |
In practice: ShopStream reserves stock at checkout
This is the realistic example, an educational scenario on the course's running example ShopStream; nothing in it describes a real company. Every number is illustrative.
This is a realistic scenario, not a case history.
The situation
A checkout reserves stock for every line of a cart, up to five lines. A popular item is bought by many carts at once. The team must choose how to guard the stock rows so no item is oversold and checkout does not stall.
Starting architecture
Figure 4. Reserving stock, then charging. How to read this: the payment call is slow and outside the database, so a lock that is still held while it runs makes every other buyer of that item wait.
Options considered
| Option | Behaviour | Risk |
|---|---|---|
A. Atomic update ... where stock >= n per line |
One statement per line | Partial reservations if a later line fails; needs compensation |
| B. Row locks for all lines in one transaction | All-or-nothing | Deadlocks if carts lock in different orders; waiting behind slow work |
| C. Optimistic version check per line, retry | No locks while thinking | Retry storms on a hot item |
The decision
Option B for the reservation transaction, kept short and with locks taken in ascending item id, and the payment call made after the transaction commits. Option A is used for the single-line fast path. The team records two rules: no network calls while holding a row lock, and a deadlock error is retried a bounded number of times.
Rollout and verification
A rollout would first run two carts with the same items in opposite order, once without ordering and once with it, as the lab does. In production the checks are counts and ages: lock waits per minute, deadlock errors per hour, the longest transaction, and retries per checkout.
The 2 a.m. failure
The page reads: checkout latency has spiked and deadlock errors are appearing. A deploy added a gift-wrap line that is locked before the items for some carts, so lock order now differs between code paths and cycles form. The checks are the deploy diff around the reservation code, the statements named in the deadlock errors, and the transaction age. The mitigation is to roll back the change or sort the lines before locking. The lasting fix is a single reservation function that sorts by item id for every caller, plus a test that runs two carts in opposite order, as scenario 6 and 7 of the lab do.
Architect's notes
- Start with the atomic update. It removes the problem for counters.
- Never hold a row lock across a network call. Reserve, commit, then call.
- Order your locks. One shared rule (ascending id) beats ad hoc care.
- Treat conflicts as normal. Optimistic conflicts and deadlock aborts are retryable outcomes; bound the retries.
Common mistakes
- Using a version column and ignoring the update count. The check only works if zero rows changed is treated as a conflict.
- Locking inside a long transaction. The lock lasts until commit.
- Locking in different orders. That is how deadlocks start.
- Assuming the deadlock victim is predictable. The manual says not to rely on it.
Key takeaways
- A lost update is a write based on a stale read; it raises no error unless you add a defence.
- Prefer one atomic
UPDATEwhen the change is arithmetic on one row. - Optimistic locking checks a version at write time and retries on conflict; it holds no lock while the user thinks.
- Pessimistic locking takes a row lock first; the cost is waiting and hold time.
- A deadlock is a cycle in the wait-for graph; a consistent lock order prevents it, and the database breaks the ones that happen.
- Real PostgreSQL adds lock modes,
NOWAIT,SKIP LOCKEDand a delayed detector that this lab did not run.
Practice exercises
Exercise 1 (20 min). For a "save profile" form, a stock counter, and a job queue table, choose atomic update, optimistic or pessimistic locking, and say why.
Exercise 2 (45 min). Run the lab. In scenario 2, change Bob's write to happen after Alice's and say what changes.
Exercise 3 (1 hour). Run "Break it". Then give scenario 7 three rows and a three-way opposite order, and show that sorted locking still avoids the cycle.
Related reading
- MVCC: where row versions and
xmaxlocks live in PostgreSQL. - Databases: Basics: transactions and indexes.
- Distributed locks and fencing tokens: when the lock must span services.
Official documentation
- PostgreSQL 18, Explicit Locking and Transaction Isolation.
- PostgreSQL 18, Lock Management settings, SELECT and error codes.
- H2, Advanced features and system tables.
- Jakarta Persistence 3.2, specification and Spring Data JPA locking.