skip to content

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.

spinlockLWLockheavyweight lock
protectsa few fields of shared memorya shared structure: a buffer's contents, the WAL insert position, a lock-table partitiona database object: a table, a transaction, a row in line, an advisory number
held fora few instructionsmicroseconds, never across a client round tripuntil the transaction ends (usually)
modesoneshared or exclusiveeight table modes, plus others for other objects
a waiterspins, then sleeps briefly (SpinDelay)sleeps on a semaphoresleeps in a queue, first come first served
deadlock detectionno: code must never hold one longno: code takes them in a fixed orderyes, after deadlock_timeout
released on errornever needed: nothing that can fail runs while one is heldyesyes, at abort
you can see it inwait_event Timeout:SpinDelaywait_event_type LWLockpg_locks, and wait_event_type Lock
drawn by hand · from the postgres source: src/backend/storage/lmgr/README
postgres's three kinds of lock. a statement takes a few heavyweight locks and hundreds or thousands of LWLock and spinlock acquisitions. only the heavyweight ones are in pg_locks.

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):

sqlempty db
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;
output, from postgres 18.6
#1 · SELECT 9
typetextcountint8
Activity18
BufferPin1
Client9
Extension1
IO81
IPC58
LWLock84
Lock12
Timeout10
(9 rows)
#2 · SELECT 5
nametextdescriptiontext
BufferContentWaiting to access a data page in memory
BufferMapping
LockManagerWaiting to read or update information about "heavyweight" locks
WALInsertWaiting to insert WAL data into a memory buffer
WALWriteWaiting for WAL buffers to be written to disk
(5 rows)

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:

workload =
UPDATE hot SET n = n + 1 WHERE id = 1; · 13,147 tps · 437 samples
LWLock:LockManager45.4 %
Lock:transactionid31.6 %
Lock:tuple10.9 %
running (no wait)7.9 %
IO:WalWrite2.2 %
LWLock:BufferContent1.6 %
Client:ClientRead0.3 %
Timeout:SpinDelay0.1 %

share 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.

measured on this mac (m4 pro, 14 cores), postgres 18.6 from Postgres.app, pgbench -c 32 -j 8, pg_stat_activity sampled every 10 ms for 5 s. one run; the numbers move between runs, the order doesn't
switch the workload. 32 updates of one row mostly wait on heavyweight locks (the row's transaction id and tuple lock), plus the LockManager LWLock that guards them. 32 reads of one row barely wait at all: everyone takes the page's content lock in shared mode. 32 inserts wait on WALWrite and BufferContent: the log and the table's last page are the bottlenecks.

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.

predict the output
32 sessions run SELECT on the same single row, flat out. what do they mostly wait on?
sql
-- 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
·
T2
·
1
BEGIN; DECLARE c CURSOR FOR SELECT id, owner FROM accounts; FETCH 1 FROM c→ 1 row

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.

step 1/6
real output, a postgres 18.6 server · buffer-pin
step through. T1's cursor fetches one row and stops, holding a pin on page 0. T2 updates a row on that page anyway: it only needs the content lock, for a moment. VACUUM needs a cleanup lock (the content lock plus nobody else's pin) to remove dead tuples, can't get it, and leaves bob's dead version behind. after T1 commits, the next VACUUM removes it.
blockint8pinning_backendsint4
01
(1 row)
VACUUM, cursor open
  1. pages: 0 removed, 1 remain, 1 scanned (100.00% of total), 0 eagerly scanned
  2. tuples: 0 removed, 4 remain, 1 are dead but not yet removable
  3. tuples missed: 1 dead from 1 pages not removed due to cleanup lock contention
  4. frozen: 0 pages from table (0.00% of total) had 0 tuples frozen
VACUUM, cursor closed
  1. pages: 0 removed, 1 remain, 1 scanned (100.00% of total), 0 eagerly scanned
  2. tuples: 2 removed, 2 remain, 0 are dead but not yet removable
  3. frozen: 0 pages from table (0.00% of total) had 0 tuples frozen
real output, a postgres 18.6 server · buffer-pin
pg_buffercache while the cursor is open: 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.