Careeroza
Locking & Deadlocks
Locks
| Lock | Taken by | Allows others to... |
|---|---|---|
| Shared (S) | reads (in locking databases) | read, but not write |
| Exclusive (X) | writes | nothing (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, retryTip: 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:
| Time | Transaction A | Transaction B |
|---|---|---|
| 1 | locks row 1 | locks row 2 |
| 2 | waits 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
WHEREso fewer rows get locked. - Be ready to retry the transaction that was chosen as victim.