SteelReed

Search

Search posts, questions…

4. Database & SQL

Databases: transactions, isolation levels and locking

Why correct code goes wrong under concurrency: ACID in InnoDB, isolation levels and anomalies (lost update, write skew), locks, gap locks, deadlocks, MVCC, SKIP LOCKED and retrying the right way.

17 Nov 202611 min readSenior

–

1. The problem

A wallet holds 100. Two top-ups of 10 and 50 arrive at once; each reads the balance and writes it back. The result is 110 instead of 160 on a default MySQL 8.4, with no error at all.

2. Key idea

A transaction groups statements: all of them succeed or none do. The isolation level decides how much of other transactions' unfinished work you see. The default level does not save you from "read into the app, compute, write back".

2.1 Which anomalies get through the defaults?

Anomaly What it is MySQL RR PostgreSQL RC
Dirty read reading uncommitted data blocked blocked
Non-repeatable read re-reading a row gives a different value blocked gets through
Phantom read re-reading returns new rows blocked for plain reads gets through
Lost update a later write overwrites an earlier one gets through gets through (RR raises an error)
Write skew two sides change two different rows and together break a rule gets through gets through (only SERIALIZABLE stops it)

2.2 What fixes it?

Fix Use when Don't use when
UPDATE ... SET x = x + ? (atomic) the DB can do the math complex logic in the app
Condition in WHERE (AND stock >= 1) decrementing stock, changing status
SELECT ... FOR UPDATE (pessimistic) conflicts are frequent long transactions, HTTP calls inside
version column (optimistic) conflicts are rare, spans several requests many conflicts: constant retries
Unique constraint "create if missing", idempotency

2.3 Where do locks cause incidents?

  • InnoDB locks every index record it scans: an UPDATE on an unindexed column locks almost the whole table.
  • RR adds gap locks (locks on the space between records). Two requests that FOR UPDATE a missing row and then both INSERT deadlock.
  • Deadlock: InnoDB aborts one side's whole transaction (error 1213). Prevent it by locking in id order.
  • A long-open transaction blocks MVCC from cleaning old versions: tables bloat, queries slow down.
  • Several workers taking jobs: FOR UPDATE SKIP LOCKED skips rows already locked.

3. In Java

The retry goes outside the transaction, because a deadlock has already rolled back the whole transaction.

JAVA
// NO @Transactional on this method
public void transfer(long from, long to, BigDecimal amount) {
    for (int attempt = 1; ; attempt++) {
        try {
            tx.executeWithoutResult(s -> doTransfer(from, to, amount)); // a fresh transaction each time
            return;
        } catch (ConcurrencyFailureException e) { // deadlock 1213, serialization 40001, optimistic
            if (attempt == 3) throw e;
            sleepQuietly(ThreadLocalRandom.current().nextLong(20, 50L * attempt)); // random backoff
        }
    }
}
// doTransfer locks the smaller id first: 200 requests both ways, total=2000.00

JPA has @Version and @Lock(PESSIMISTIC_WRITE). Other languages: the same retry loop, catching error 1213 or SQLState 40001.

Common @Transactional traps
  • Calling a @Transactional method from another method in the same class: it bypasses the proxy, so there is no transaction.
  • Spring only rolls back on RuntimeException/Error; checked exceptions need rollbackFor.
  • No HTTP calls or emails inside a transaction: they hold locks and connections longer, and get sent again on retry.
Write skew: two doctors asking for the same night off

Shift 7 has two doctors on call, and the rule is "at least 1 on call". Each counts 2 and then updates their own row: nobody waits for anybody, and shift 7 ends up with 0. The fix is to force the conflict onto one row:

SQL
SELECT id FROM shift WHERE id = 7 FOR UPDATE;  -- lock one row that stands for the whole shift
-- then count and UPDATE doctor_shift

On PostgreSQL you can also run SERIALIZABLE and retry on serialization failures.

4. Working with AI

Hand to AI: concurrent tests with Testcontainers, migrations that add indexes, version, unique constraints.

Check in AI-written code:

  • No "read into the app, compute, write back" without FOR UPDATE or version.
  • "Create if missing" has a unique constraint, not just findBy... then save.
  • Several rows are locked in id order; the WHERE of UPDATE/DELETE has an index.
  • The retry loop sits outside @Transactional, bounded and with backoff.

5. Exercises

Exercise 1: Flash sale with negative stock

1,000 requests buy a product with 1 left. The AI's code reads stock, and if (stock > 0) subtracts 1. More than 1 gets sold. Fix it.

Solution to Exercise 1

Push the condition into one atomic UPDATE:

SQL
UPDATE product SET stock = stock - 1 WHERE id = :id AND stock >= 1;
-- 1st call: 1 row; 2nd call: 0 rows = sold out

The UPDATE takes an X lock on the row, so requests queue up on their own; no separate FOR UPDATE needed. Add CHECK (stock >= 0) as a last safety net.

Exercise 2: Pick one of two proposals

When A pays B and B pays A at the same time, the log shows error 1213. The AI proposes: (A) catch the error and rerun just the failed UPDATE; (B) lock both accounts in ascending id order and retry the whole transaction from outside. Pick one and explain.

Solution to Exercise 2

Pick B. (A) is wrong: the deadlock already rolled back the whole transaction, so rerunning one UPDATE runs it in a new autocommit transaction and leaves half-done data. Spring also marks the transaction rollback-only, so the final commit throws UnexpectedRollbackException.

SQL
SELECT id FROM account WHERE id = LEAST(:from_id, :to_id) FOR UPDATE;
SELECT id FROM account WHERE id = GREATEST(:from_id, :to_id) FOR UPDATE;
-- check the balance, then the two UPDATEs

Two opposite transfers both ask for the smaller id first, so one waits until the other is completely done.

Summary

  • The isolation level only decides what you see of other people's work.
  • MySQL RR does not stop lost updates or write skew.
  • Fix lost updates with an atomic update, a condition in WHERE, FOR UPDATE or version.
  • "Create if missing" relies on a unique constraint.
  • Retry the whole transaction, from outside, bounded and with backoff.

Further reading: Locks in InnoDB.

Practice interview questions on this topic

All Transactions & Locking questions →

Loading comments…
Next on the roadmapTransactions from the inside: WAL, MVCC and the undo log