latches, spinlocks and LWLocks
the short locks that protect memory, not rows. why they never show up in pg_locks.
- address
- everything.locking.latches
- part
- part 15, locks and concurrency control
- chapter
- chapter 8 of 10
- reading time
- 9 min
pg_locks shows heavyweight locks: on tables, transactions, rows in line. underneath them is a second layer that protects postgres's own shared memory: LWLocks (lightweight locks, shared or exclusive, held for microseconds) and spinlocks (a few instructions, busy-waiting). databases textbooks call these latches. they never appear in pg_locks, have no deadlock detector, and you only see them in wait events.
the picture
you know how two sessions can update two different rows on the same 8 KB page at the same moment, and nobody sees a lock in pg_locks? something still stops them from scribbling over each other's bytes. that something lives for a few microseconds.
think of a shared kitchen. a heavyweight lock is a booking on the oven for tonight's dinner: written in the calendar, everyone can see it, held for hours. an LWLock is "hands off the cutting board while I chop this onion": nobody writes it down, it's over in seconds. a spinlock is reaching for the salt at the same time as someone else and waiting half a heartbeat.
| spinlock | LWLock | heavyweight lock | |
|---|---|---|---|
| protects | a few fields of shared memory | a shared structure: a buffer's contents, the WAL insert position, a lock-table partition | a database object: a table, a transaction, a row in line, an advisory number |
| held for | a few instructions | microseconds, never across a client round trip | until the transaction ends (usually) |
| modes | one | shared or exclusive | eight table modes, plus others for other objects |
| a waiter | spins, then sleeps briefly (SpinDelay) | sleeps on a semaphore | sleeps in a queue, first come first served |
| deadlock detection | no: code must never hold one long | no: code takes them in a fixed order | yes, after deadlock_timeout |
| released on error | never needed: nothing that can fail runs while one is held | yes | yes, at abort |
| you can see it in | wait_event Timeout:SpinDelay | wait_event_type LWLock | pg_locks, and wait_event_type Lock |
the textbook word is latch: a short-term lock on an in-memory structure, as opposed to a lock on a database object that lasts the transaction (b-trees under concurrency talks about latch crabbing on index pages). in postgres's source, "latch" means something else (a way to wake a sleeping process), so the code says LWLock.
what they protect
a few LWLocks you'll meet in wait events, each guarding one shared structure:
- BufferContent: one per buffer in the buffer pool. shared to read a page's tuples, exclusive to change them. this is what keeps two UPDATEs on one page from corrupting it.
- BufferMapping: the hash table from (table, block) to buffer. taken to find a page in the pool, or to load one.
- WALInsert and WALWrite: reserving space in the WAL buffers, and writing them out (the commit path).
- LockManager: a partition of the heavyweight lock table. taking a heavyweight lock means taking an LWLock first.
- ProcArray: the list of running transactions that every snapshot is built from.
postgres lists every wait event, with a description, in a view (new in 17):
SELECT type, count(*) FROM pg_wait_events GROUP BY type ORDER BY type;
SELECT name, description FROM pg_wait_events
WHERE type = 'LWLock' AND name IN ('BufferContent', 'BufferMapping', 'LockManager', 'WALInsert', 'WALWrite')
ORDER BY name;| typetext | countint8 |
|---|---|
| Activity | 18 |
| BufferPin | 1 |
| Client | 9 |
| Extension | 1 |
| IO | 81 |
| IPC | 58 |
| LWLock | 84 |
| Lock | 12 |
| Timeout | 10 |
| nametext | descriptiontext |
|---|---|
| BufferContent | Waiting to access a data page in memory |
| BufferMapping | |
| LockManager | Waiting to read or update information about "heavyweight" locks |
| WALInsert | Waiting to insert WAL data into a memory buffer |
| WALWrite | Waiting for WAL buffers to be written to disk |
catching them in the act
an LWLock wait lasts microseconds, so a one-off look at pg_stat_activity almost never sees one. under real contention it does. this is 32 pgbench clients hammering a real postgres 18.6 server on this mac, three ways, with pg_stat_activity sampled every 10 ms:
UPDATE hot SET n = n + 1 WHERE id = 1; · 13,147 tps · 437 samplesshare of backend samples in each state. 4 rarer events left out. LWLock waits are latches; Lock waits are heavyweight locks, the ones pg_locks shows. Timeout:SpinDelay is a backend sleeping between tries for a spinlock.
read the first workload carefully: one hot row produces heavyweight waits (Lock:transactionid, Lock:tuple, the ones from how row locks are stored), and those make the LockManager LWLock hot, because every one of those lock requests goes through a lock-table partition. a latch problem caused by a lock problem.
the reads are the reassuring one: 275,031 transactions a second on one row, and not a single LWLock wait in the samples. shared mode is shared.
-- each of 32 pgbench clients, in a loop:
SELECT n FROM hot WHERE id = 1;pins
one more mechanism sits next to the content lock: a pin. pinning a buffer says "I'm using this page, don't evict it". it's a counter, not a lock: pinned pages can still be read and changed by anyone. a scan pins the page it's on, and an open cursor that stopped halfway keeps its pin.
T1 opens a cursor over accounts and fetches one row. the scan stops there, holding a pin on page 0 until the cursor moves on or closes.
| blockint8 | pinning_backendsint4 |
|---|---|
| 0 | 1 |
- pages: 0 removed, 1 remain, 1 scanned (100.00% of total), 0 eagerly scanned
- tuples: 0 removed, 4 remain, 1 are dead but not yet removable
- tuples missed: 1 dead from 1 pages not removed due to cleanup lock contention
- frozen: 0 pages from table (0.00% of total) had 0 tuples frozen
- pages: 0 removed, 1 remain, 1 scanned (100.00% of total), 0 eagerly scanned
- tuples: 2 removed, 2 remain, 0 are dead but not yet removable
- frozen: 0 pages from table (0.00% of total) had 0 tuples frozen
pinning_backends = 1 on the table's page 0. then the two VACUUM VERBOSE reports, trimmed to the lines that matter."1 dead from 1 pages not removed due to cleanup lock contention" is the pin at work. (the "1 are dead but not yet removable" in the same report is a different story: alice's old version, which T1's open snapshot could still need. see the xmin horizon.) a plain VACUUM skips a pinned page rather than wait; an aggressive one (freezing to prevent wraparound) that has to freeze that page waits for the pin, and that wait shows up as wait_event_type BufferPin.
one level deeperwhy there's no deadlock detector for these
the deadlock detector walks the heavyweight lock table, and it can afford to because it only runs after a backend has waited a whole second. an LWLock wait that took a second would already be a disaster. so postgres avoids LWLock deadlocks by construction instead: code that needs several takes them in a fixed order (all the lock-table partitions in ascending order, for instance), never waits for a heavyweight lock while holding one, and releases them all on error. spinlocks are stricter still: held for a handful of instructions, with no function calls that could fail. a spinlock that never comes free ends in a "stuck spinlock" PANIC: the server prefers crashing to hanging forever.
keylines
- heavyweight locks protect database objects for a transaction. pg_locks shows them.
- LWLocks protect shared memory for microseconds, shared or exclusive. spinlocks for a few instructions.
- neither is in pg_locks, and neither has a deadlock detector: lock ordering prevents cycles.
- you see them as wait events. sample pg_stat_activity, look at the distribution.
- a pin is a reference count, not a lock. VACUUM's cleanup lock is what it gets in the way of.