skip to content

b-trees under concurrency

latch crabbing, lehman and yao's right-links, and why readers never wait for a split.

address
everything.index_internals.btree_concurrency
part
part 13, inside indexes
chapter
chapter 4 of 12
reading time
8 min

many sessions read and write one b-tree at once. the textbook protects a descent with latch crabbing: hold a page until you've latched the next one, and hold the parent while a child might split. postgres uses Lehman and Yao's design instead: every page has a right link and a high key, so a reader holds one page at a time, and if a split moved its key away while it was between pages, it just moves right. readers never wait for a split. and none of these page locks are in pg_locks: they're short LWLocks on buffers, not lock-manager locks.

the picture

you know how a page split moves half a page somewhere new and only then tells the parent? imagine a reader that read the parent just before the split, and arrives at the child just after. the key it wants isn't there anymore. in a naive tree it would conclude the key doesn't exist, which is wrong.

think of a library that's reshelving. you looked up "aisle 4" in the catalog, but by the time you walk there, half of aisle 4 has been moved to a new aisle 4b. the textbook fix is to stop anyone reshelving while you walk (latches). the Lehman and Yao fix is a sign at the end of every aisle: "this aisle ends at M. for anything after that, go next door". you walk one more aisle, and nobody had to wait for anybody.

first, what's observable: three real sessions on one tiny index. T1 and T2 insert neighbouring keys into the same leaf and stay open, and T3 scans that leaf.

T1
·
T2
·
T3
·
1
BEGIN; INSERT INTO c VALUES (55)→ INSERT 0 1
pg_locks
  • T1RowExclusiveLockc
  • T1ExclusiveLockxid 760
  • T1ExclusiveLock4/4

T1 inserts 55 and stays open. its entry goes into the only leaf.

step 1/5
real output, a postgres 18.6 server · same-leaf
three sessions on a postgres 18.6 server, all touching the same leaf. step through and watch the lock manager on the side: row-exclusive on the table, each transaction's own id, and that's all. no lock on the index, its pages, or its entries. nobody waits.

two writers modified the same 8 KB page within a millisecond of each other and neither waited, because neither held the page for longer than it took to add one entry. T3 read the page while it held two uncommitted entries and counted 2 rows, not 4: an index entry carries no visibility information, so the scan checks each row in the heap and skips the ones from transactions that haven't committed (visibility rules).

two kinds of lock

heavyweight lockspage locks (latches)
protecttables, rows, transaction ids: logical thingsa buffer's 8 KB of memory while it's read or changed
held foruntil the transaction ends (usually)a few microseconds, one page operation
deadlock detectionyesno: code takes them in a fixed order instead
where you see thempg_lockspg_stat_activity.wait_event = BufferContent, if anyone ever waits

an index page is protected by the second kind: a shared or exclusive LWLock on the buffer holding it (latches, spinlocks and LWLocks). you can see the first kind for yourself, in the browser:

sqlempty db
CREATE TABLE c (id int);
CREATE INDEX c_id ON c (id);
BEGIN;
INSERT INTO c VALUES (55);
SELECT locktype, relation::regclass AS rel, mode
FROM pg_locks
WHERE pid = pg_backend_pid() AND relation IS DISTINCT FROM 'pg_locks'::regclass
ORDER BY locktype, rel;
SET LOCAL enable_seqscan = off;
SELECT count(*) FROM c WHERE id = 55;
SELECT locktype, relation::regclass AS rel, mode
FROM pg_locks
WHERE pid = pg_backend_pid() AND relation IS DISTINCT FROM 'pg_locks'::regclass
ORDER BY locktype, rel;
COMMIT;
output, from postgres 18.6
#1 · CREATE TABLE
#2 · CREATE INDEX
#3 · BEGIN
#4 · INSERT 0 1
#5 · SELECT 3
locktypetextrelregclassmodetext
relationcRowExclusiveLock
transactionidnullExclusiveLock
virtualxidnullExclusiveLock
(3 rows)
#6 · SET
#7 · SELECT 1
countint8
1
(1 row)
#8 · SELECT 5
locktypetextrelregclassmodetext
relationcAccessShareLock
relationcRowExclusiveLock
relationc_idAccessShareLock
transactionidnullExclusiveLock
virtualxidnullExclusiveLock
(5 rows)
#9 · COMMIT

after the INSERT: a lock on the table and on the transaction's id, and nothing at all on c_id, though the insert just wrote a leaf of it. (what stops the index from being dropped meanwhile is the table lock: DROP INDEX needs ACCESS EXCLUSIVE on the table.) the index scan adds an ACCESS SHARE on the index, which only conflicts with dropping or rebuilding it. there is no row in pg_locks for any page or entry, ever.

the textbook: latch crabbing

1020303540506040rootleaves
child and sibling linkssearch path

latch the root, read it: 25 goes to the left leaf.

step 1/3
drawn by hand · the textbook protocol, 4 keys a page
latch crabbing, the textbook way to insert 25. pages lit hot are latched. the root stays latched while the leaf might split, because the split will need to change it.

the name is from how a crab walks: one leg always holding on. the rule is "latch the child, then release the parent if the child is safe" (it can't split or merge from this operation). it's correct, and it's how many engines work. the cost is the top of the tree: every writer starts by latching the root, and a writer that might split holds latches on several levels at once, blocking every reader behind it.

Lehman and Yao ("efficient locking for concurrent operations on B-trees", ACM TODS, 1981) add two things to every page, and postgres's nbtree has both on every level: a right link to the next page, and a high key, the upper bound of the page. with those, a reader never needs to hold two pages:

102030354040506040rootleaves
child and sibling linkshigh keysearch path

the reader reads the root: 35 < 40, so the left leaf. it lets go of the root before it touches the leaf.

step 1/5
drawn by hand · the Lehman and Yao protocol as postgres implements it, 4 keys a page
a reader looking for 35 races a writer that splits the page it's heading for. the reader holds at most one page, hot. the high key tells it the split happened, and the right link tells it where to go.

that move-right check is in every descent postgres makes (_bt_moveright in the source). and it's why a split can be done in two steps, the page first and the parent later, with no lock spanning them. if the backend crashes in between, the next insert that finds the missing downlink finishes the job (an "incomplete split" flag on the page says it has to).

predict the output
a reader holds no lock while it walks from a parent page to a child. can a concurrent split make it miss a key?
text
reader: read root → "go to leaf A" → (no locks held) → read leaf A
writer:                 split leaf A into A and B

what writers still wait for

writers still take exclusive latches, just for less time:

  • an insert latches only the leaf it inserts into. if the leaf splits, it also latches the new page and the right neighbour (to fix its left link), writes the split, and lets go of all but the old leaf. it keeps that one only until it has latched the parent (so it can clear the page's "split not finished" flag), then goes on up with one or two pages at a time. no writer holds the root while it works on a leaf.
  • latches are always taken left to right and bottom to top, so two splits can't deadlock on each other.

the waits you can see in pg_locks are the logical ones: a unique index insert that finds a possible duplicate from an uncommitted transaction waits on that transaction's id, in the lock manager (how a unique index says no). that's a row-level question, not a page one.

keylines

  • index pages are protected by short buffer latches (LWLocks), not lock-manager locks. pg_locks never shows them.
  • the textbook descent, latch crabbing, holds a parent while a child might split.
  • postgres follows Lehman and Yao: right links and high keys on every page, one latch at a time.
  • a reader whose key moved during a split sees it's above the high key and moves right.
  • splits happen in two steps, page then parent, so nobody waits for a whole split.