Courses / Databases for Backend Interviews / Chapter 21
Module 9 · Transactions, isolation and locking · Chapter 21 of 27
Locks and Concurrency Control: Row Locks, Deadlocks and Optimistic Updates
Builds on Transactions: ACID, the Write-Ahead Log and Crash Recovery and Isolation Levels and MVCC: Anomalies, Snapshots and Vacuum. Next up: Replication: Streaming Standbys, Lag, Failover and Logical Replication.
Part 1 · Table lock modes
Locks beside MVCC
A bus booking service lets thousands of riders change seats while a maintenance job adds a column to the same table. Locks are how PostgreSQL keeps those two kinds of work from colliding.
The isolation chapter showed that MVCC lets readers and writers work on different versions of a row, so a plain SELECT does not wait for an UPDATE. Locks still exist because some work cannot be done on versions: changing a table's structure, rewriting it, building an index, or deciding which of two writers gets a row. A lock is a claim on an object, held by a transaction until it commits or rolls back, that makes conflicting requests wait.
PostgreSQL takes locks at two levels. Table-level locks are taken automatically by every statement on the whole table. Row-level locks protect single rows, and the next lesson uses them. Each level has several lock modes, and a mode matters because of which other modes it conflicts with. Two requests in modes that do not conflict proceed together. Two in conflicting modes make the later one wait for the earlier transaction to finish.
The names of the modes sound alike and are easy to confuse. It helps to remember that they describe what a statement intends to do to the table, from the gentlest, reading, to the strictest, which locks everyone else out.