Lesson 5 of 9 · 23m
Locks, Deadlocks, and Hot-Row Contention
Locks are how databases keep concurrent mutations honest. Deadlocks are not rare curses; they are what happens when two transactions order the same work differently.
If MVCC is the optimistic side of concurrency, locking is the adult supervision. Databases lock rows, pages, keys, ranges, metadata, and sometimes entire tables. Most production contention is not caused by 'too many locks' in the abstract — it is caused by a small number of hot rows everyone wants.
Lock scope follows what you touch
BEGIN;
UPDATE inventory
SET quantity = quantity - 1
WHERE sku = 'SSD-2TB';
-- the matching row is locked until COMMIT or ROLLBACKAnother transaction updating the same row waits. That wait is not a bug; it is correctness. The failure mode is holding that lock while doing unrelated work: network calls, slow ORM hooks, user interaction, or a queue publish.
Deadlocks are cycles
Transaction A locks row 10 and waits for row 20 while transaction B locks row 20 and waits for row 10. Neither can proceed, so the deadlock detector kills one. Applications must expect that error and retry. The fix is usually lock ordering: touch rows in a deterministic order, shorten transactions, and reduce the amount locked.
Hot rows create invisible queues
A counter table is the canonical trap:
UPDATE metrics SET total = total + 1 WHERE name = 'api_requests';Every worker serializes on the same row. Even if each update takes milliseconds, throughput collapses under concurrency. Alternatives include batching increments in memory, writing event rows and aggregating later, or sharding the counter:
CREATE TABLE metric_shards (
bucket int NOT NULL,
total bigint NOT NULL,
PRIMARY KEY (bucket)
);
-- increment bucket = random 0..15, then SUM(total) when readingObserve the lock graph before guessing
-- PostgreSQL: who is blocked and who is blocking them?
SELECT blocked.pid, blocked.query, blocker.pid, blocker.query
FROM pg_stat_activity blocked
JOIN pg_locks bl ON bl.pid = blocked.pid AND NOT bl.granted
JOIN pg_locks kl ON kl.locktype = bl.locktype AND kl.pid <> bl.pid
JOIN pg_stat_activity blocker ON blocker.pid = kl.pid;Production lock diagnosis is mostly about timeline: what started, what is waiting, what transaction has been open longest. Averages hide the one session holding the keys to the city.
Field notes
- Keep transactions short and never perform application I/O inside them.
- Retry deadlock and serialization errors with jittered backoff; do not loop tightly.
NOWAITandSKIP LOCKEDare excellent for job queues because waiting workers are wasted workers.- Foreign keys and cascades can acquire more locks than expected. Read the exact semantics before designing high-write schemas.
Was this lesson helpful?