Locking & Deadlocks

Locks

LockTaken byAllows others to...
Shared (S)reads (in locking databases)read, but not write
Exclusive (X)writesnothing (in MVCC databases, readers still see the old version)

Locks can be on a row, a page or a whole table. Row-level locking (InnoDB, PostgreSQL, SQL Server) lets many users work on the same table.

Preventing Lost Updates

-- Pessimistic: lock the row while you work on it
BEGIN;
SELECT Stock FROM Products WHERE ProductID = 5 FOR UPDATE;   -- others wait here
UPDATE Products SET Stock = Stock - 1 WHERE ProductID = 5;
COMMIT;

-- Optimistic: check a version number when writing
UPDATE Products
SET Stock = 44, Version = Version + 1
WHERE ProductID = 5 AND Version = 7;   -- 0 rows updated => someone else changed it, retry

Tip: Better still, do the arithmetic in SQL: UPDATE ... SET Stock = Stock - 1 WHERE Stock > 0 is atomic and needs no read first.

Deadlocks

A deadlock happens when two transactions each hold a lock the other needs:

TimeTransaction ATransaction B
1locks row 1locks row 2
2waits for row 2...waits for row 1...

The database detects the cycle and kills one transaction (the "victim") with a deadlock error. To reduce deadlocks:

  • Access tables and rows in the same order in every transaction.
  • Keep transactions short: no user input or network calls inside them.
  • Index the columns in WHERE so fewer rows get locked.
  • Be ready to retry the transaction that was chosen as victim.