man postgres-internals/buffer-manager
lesson 5 of 30 · Buffers and durability
Shared buffers: a page cache with pins and locks
In lessons 1 to 4 tinypg treated a table as a file: read a page, change
it, write it back. PostgreSQL doesn’t work on an ordinary table’s file like
that. A page a backend reads or changes is first copied into shared
buffers, an array of 8 KB slots in shared memory that all the server’s
processes see, and it is changed there; the file catches up later.
(Temporary tables are the exception: their pages go to buffers private to
the backend.) Lesson
1 met the edge of this: get_raw_page copies a page out of a buffer, and
the page checksum is computed when the buffer is written.
The pool has two jobs. It is a cache, so a page read once is not read from the file again while it stays in memory. And it is where all the backends meet, so it needs rules for who may look at a page and who may change it. This lesson reads both: how a page is found in the pool, the pin that keeps it there, the content lock that guards its bytes, and the clock sweep that decides which page leaves when a new one needs room. tinypg gets a pool of its own, and the test is whether it predicts what a real server’s pool does, buffer by buffer.
Every psql and shell output below comes from one run of
tools/record_buffers.py in the tinypg repository (tag lesson-05.1)
against PostgreSQL 19.0 on 64-bit ARM macOS, pasted as the script recorded
it. That server was configured for the recording: shared_buffers at its
minimum, 128kB, which is 16 buffers, so that the whole pool fits in a
figure and fills after a few reads; autovacuum off, so that no worker reads
catalog pages behind the script’s back; and bgwriter_lru_maxpages = 0, so
that the background writer writes nothing. The default pool is 128MB, 16384
buffers. The rules are the same.
The experiment
A table of 60 pages, seven 1032-byte rows to a page:
CREATE TABLE books (id int, body text) WITH (autovacuum_enabled = off);
CREATE TABLE
INSERT INTO books SELECT i, repeat('x', 1000) FROM generate_series(1, 420) AS i;
INSERT 0 420
VACUUM (FREEZE) books;
VACUUM
CHECKPOINT;
CHECKPOINT
SELECT pg_relation_size('books') / 8192 AS pages, pg_relation_filenode('books') AS relfilenode;
pages | relfilenode
-------+-------------
60 | 16512
(1 row)
SHOW shared_buffers;
shared_buffers
----------------
128kB
(1 row)
VACUUM (FREEZE) freezes the rows, so reading one later has no hint bits
to set and changes nothing on the page; the checkpoint writes the dirty
pages, so no buffer holds a changed copy.
Everything after that runs in one psql session, and that matters. A new
connection reads dozens of catalog pages while it starts, which in a
16-buffer pool would replace most of the pool between two steps. The
session first evicts books from the pool with
pg_buffercache_evict_relation(), one of the extension’s functions for
testing; here the pool had no page of books to begin with. Then it runs
every other statement it will use once, so that the catalog rows they need
sit in the backend’s own caches (private memory, not shared buffers). The
last of them reads block 58, so by the second summary below, taken at the
end of the warm-up, one buffer held a page of books again:
SELECT * FROM pg_buffercache_summary();
buffers_used | buffers_unused | buffers_dirty | buffers_pinned | usagecount_avg
--------------+----------------+---------------+----------------+----------------
16 | 0 | 0 | 0 | 1.3125
(1 row)
SELECT bufferid, relblocknumber AS block, usagecount, pinning_backends AS pins, isdirty
FROM pg_buffercache WHERE relfilenode = 16512
ORDER BY bufferid;
bufferid | block | usagecount | pins | isdirty
----------+-------+------------+------+---------
(0 rows)
SELECT * FROM pg_buffercache_evict_relation('books');
buffers_evicted | buffers_flushed | buffers_skipped
-----------------+-----------------+-----------------
0 | 0 | 0
(1 row)
SELECT * FROM pg_buffercache_summary();
buffers_used | buffers_unused | buffers_dirty | buffers_pinned | usagecount_avg
--------------+----------------+---------------+----------------+----------------
16 | 0 | 0 | 0 | 0.8125
(1 row)
After that, the session’s only page reads are the ones it asks for. Each
step reads one page with a TID scan, SELECT id FROM books WHERE ctid = '(b,1)', which reads block b and nothing else, under EXPLAIN (ANALYZE, BUFFERS), which counts what the read cost; then it takes a snapshot of all
16 rows of pg_buffercache.
Arrays and a hash table
The pool is allocated once, at server start, as several arrays of
NBuffers entries, among them the blocks themselves, one descriptor per
block, and one condition variable per block for processes waiting on its
I/O. A descriptor names the
page its block holds with a buffer tag:
typedef struct buftag
{
Oid spcOid; /* tablespace oid */
Oid dbOid; /* database oid */
RelFileNumber relNumber; /* relation file number */
ForkNumber forkNum; /* fork number */
BlockNumber blockNum; /* blknum relative to begin of reln */
} BufferTag;
src/include/storage/buf_internals.h, lines 161–168
Tablespace, database, relfilenode, fork and block: enough to find the file and the offset in it without the catalog, which matters because the process that writes a buffer out may not be the one that read it in. The whole descriptor:
typedef struct BufferDesc
{
/*
* ID of page contained in buffer. The buffer header spinlock needs to be
* held to modify this field.
*/
BufferTag tag;
/*
* Buffer's index number (from 0). The field never changes after
* initialization, so does not need locking.
*/
int buf_id;
/*
* State of the buffer, containing flags, refcount and usagecount. See
* BUF_* and BM_* defines at the top of this file.
*/
pg_atomic_uint64 state;
/*
* Backend of pin-count waiter. The buffer header spinlock needs to be
* held to modify this field.
*/
int wait_backend_pgprocno;
PgAioWaitRef io_wref; /* set iff AIO is in progress */
/*
* List of PGPROCs waiting for the buffer content lock. Protected by the
* buffer header spinlock.
*/
proclist_head lock_waiters;
} BufferDesc;
src/include/storage/buf_internals.h, lines 326–359
Nearly everything about a buffer is in state, one 64-bit word, so that
the frequent operations are a single atomic compare-and-swap rather than a
lock:
/*
* Buffer state is a single 64-bit variable where following data is combined.
*
* State of the buffer itself (in order):
* - 18 bits refcount
* - 4 bits usage count
* - 12 bits of flags
* - 18 bits share-lock count
* - 1 bit share-exclusive locked
* - 1 bit exclusive locked
*
* Combining these values allows to perform some operations without locking
* the buffer header, by modifying them together with a CAS loop.
*
* The definition of buffer state components is below.
*/
src/include/storage/buf_internals.h, lines 33–48
pg_buffercache shows three of those fields: pinning_backends is the
refcount, usagecount the usage count, isdirty one of the flags. The
content lock is in the same word; the comment above the struct says it used
to be a separate LWLock, and that putting it in the state word lets
PostgreSQL unlock and unpin a buffer in one atomic operation.
To find a page, a backend hashes its tag and looks it up in the buffer
table, a hash table in shared memory from tag to buffer number. The table
is split into 128 partitions
(NUM_BUFFER_PARTITIONS),
each with its own lock, so that lookups in different partitions don’t
contend for one lock:
/* see if the block is in the buffer pool already */
LWLockAcquire(newPartitionLock, LW_SHARED);
existing_buf_id = BufTableLookup(&newTag, newHash);
src/backend/storage/buffer/bufmgr.c, lines 2224–2226
A miss, then hits
The first read of block 0 is a miss, the second a hit:
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id FROM books WHERE ctid = '(0,1)';
QUERY PLAN
----------------------------------------------
Tid Scan on books (actual rows=1.00 loops=1)
TID Cond: (ctid = '(0,1)'::tid)
Buffers: shared read=1
(3 rows)
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id FROM books WHERE ctid = '(0,1)';
QUERY PLAN
----------------------------------------------
Tid Scan on books (actual rows=1.00 loops=1)
TID Cond: (ctid = '(0,1)'::tid)
Buffers: shared hit=1
(3 rows)
read=1 means the page came from the file (or from the kernel’s cache of
it; PostgreSQL can’t tell the difference), hit=1 that a buffer already
held it. On a hit, BufferAlloc() pins the buffer the table points at. On
a miss it first needs a buffer to put the page in:
/*
* Acquire a victim buffer. Somebody else might try to do the same, we
* don't hold any conflicting locks. If so we'll have to undo our work
* later.
*/
victim_buffer = GetVictimBuffer(strategy, io_context);
victim_buf_hdr = GetBufferDescriptor(victim_buffer - 1);
/*
* Try to make a hashtable entry for the buffer under its new tag. If
* somebody else inserted another buffer for the tag, we'll release the
* victim buffer we acquired and use the already inserted one.
*/
LWLockAcquire(newPartitionLock, LW_EXCLUSIVE);
existing_buf_id = BufTableInsert(&newTag, newHash, victim_buf_hdr->buf_id);
src/backend/storage/buffer/bufmgr.c, lines 2265–2279
and then gives that buffer the new tag and a usage count of 1 (line 2338), before the read fills it.
Pins and the usage count
A pin is a reference held by a backend. While a buffer has one, nobody can give it to another page, so the bytes a backend is looking at stay the page it asked for. Each pin also counts as a use:
buf_state = old_buf_state;
/* increase refcount */
buf_state += BUF_REFCOUNT_ONE;
if (strategy == NULL)
{
/* Default case: increase usagecount unless already max. */
if (BUF_STATE_GET_USAGECOUNT(buf_state) < BM_MAX_USAGE_COUNT)
buf_state += BUF_USAGECOUNT_ONE;
}
src/backend/storage/buffer/bufmgr.c, lines 3332–3342
So the usage count of block 0’s buffer went 1, 2, 3, 4, 5 over its first five reads and stayed at 5 for the sixth. The cap:
/*
* The maximum allowed value of usage_count represents a tradeoff between
* accuracy and speed of the clock-sweep buffer management algorithm. A
* large value (comparable to NBuffers) would approximate LRU semantics.
* But it can take as many as BM_MAX_USAGE_COUNT+1 complete cycles of the
* clock-sweep hand to find a free buffer, so in practice we don't want the
* value to be very large.
*/
#define BM_MAX_USAGE_COUNT 5
src/include/storage/buf_internals.h, lines 136–144
Two details. The refcount in the state word counts backends, not pins. A
backend that pins a buffer it has already pinned only adds to a private
counter of its own, and the usage count doesn’t move either: the code above
sits inside if (ref == NULL)
(line 3309),
where ref is this backend’s private entry for the buffer. The comment
on the refcount in
buf_init.c
says the same, and points at the private reference counts in bufmgr.c.
And a pin may last as long as the transaction: below, a cursor that has fetched one row keeps the page that row is on pinned.
The clock sweep
When the page is not in the pool, GetVictimBuffer() asks
StrategyGetBuffer() for a buffer, and in 19, unless the caller brings a
ring of its own (see the end of this lesson), there is one way to get one:
the clock sweep. Despite its name, freelist.c keeps no list of free
buffers. An unused buffer is one with usage count 0 that the sweep comes
to like any other. The hand is a counter in shared memory,
nextVictimBuffer, which ClockSweepTick() advances and takes modulo
NBuffers:
/* Use the "clock sweep" algorithm to find a free buffer */
trycounter = NBuffers;
for (;;)
{
uint64 old_buf_state;
uint64 local_buf_state;
buf = GetBufferDescriptor(ClockSweepTick());
src/backend/storage/buffer/freelist.c, lines 239–246
/*
* If the buffer is pinned or has a nonzero usage_count, we cannot
* use it; decrement the usage_count (unless pinned) and keep
* scanning.
*/
if (BUF_STATE_GET_REFCOUNT(local_buf_state) != 0)
{
if (--trycounter == 0)
{
/*
* We've scanned all the buffers without making any state
* changes, so all the buffers are pinned (or were when we
* looked at them). We could hope that someone will free
* one eventually, but it's probably better to fail than
* to risk getting stuck in an infinite loop.
*/
elog(ERROR, "no unpinned buffers available");
}
break;
}
/* See equivalent code in PinBuffer() */
if (unlikely(local_buf_state & BM_LOCKED))
{
old_buf_state = WaitBufHdrUnlocked(buf);
continue;
}
if (BUF_STATE_GET_USAGECOUNT(local_buf_state) != 0)
{
local_buf_state -= BUF_USAGECOUNT_ONE;
if (pg_atomic_compare_exchange_u64(&buf->state, &old_buf_state,
local_buf_state))
{
trycounter = NBuffers;
break;
}
}
src/backend/storage/buffer/freelist.c, lines 257–296
When neither test stops it, the buffer is unpinned with usage count 0, and
the else branch pins it and returns it. In words: a pinned buffer is
passed untouched; an unpinned one with a usage count above 0 loses one and
is passed; the first unpinned one at 0 is the victim. So a buffer survives
as many passes of the hand as its usage count, and a page used five times
since the hand last came by survives five passes. That is the cheap
approximation of “least recently used” the comment on BM_MAX_USAGE_COUNT
describes: one small counter per buffer, and no list to reorder on every
access.
No view shows where the hand is. The recorder takes it to be one past the
buffer that the last warm-up read used (block 58 went to buffer 2, so the
hand is at buffer 3), because that is where ClockSweepTick() leaves the
counter. That position is inferred, not read; what supports it is that
every eviction predicted from it below comes out right.
The figure replays the recording. Each frame is the pool after one step,
as tinypg computed it, and says whether pg_buffercache showed the same:
Sixteen shared buffers drawn as a loop, buffer 1 top left and the clock hand as a triangle outside the loop. Each buffer shows the page it holds, its usage count as five pips, and whether it is pinned or dirty. Steps: the pool after warm-up, catalog pages and block 58 of books; block 0 read six times; blocks 1 to 47 read once each, the hand going round, lowering usage counts and taking the first unpinned buffer at zero; a cursor pinning block 1; a buffer marked dirty and later written out by the read that needs it; the cursor closed. (This figure steps through a recorded run; it needs JavaScript.)
The pool of a 16-buffer PostgreSQL 19.0 server through the recorded
session, from python3 -m tinypg trace-buffers tests/fixtures/pg19_buffers.json (tag lesson-05.1, which corrects the
first frame’s caption in lesson-05). The outlined buffer is
the one the step used; −1 marks the buffers whose usage count the sweep
lowered, “skip” a pinned buffer it passed. The middle compares the step’s
EXPLAIN counts and the whole pool with the server’s.
The read of block 0 lowers buffers 3 and 4 and takes buffer 5, which held a
page of pg_operator_oid_index with usage count 0. Block 2’s read lowers
four buffers before it finds one at 0. The catalog pages go one by one:
from the read of block 16 on, every buffer holds a page of
books.
A pinned buffer and a dirty one
Then a cursor fetches one row and stops, keeping its pin, and two more of
pg_buffercache’s test functions try things on the pool:
BEGIN;
DECLARE c CURSOR FOR SELECT id FROM books WHERE ctid = '(1,1)';
FETCH 1 FROM c;
id
----
8
(1 row)
SELECT bufferid, relblocknumber AS block, usagecount, pinning_backends AS pins, isdirty
FROM pg_buffercache WHERE relfilenode = 16512
ORDER BY bufferid;
bufferid | block | usagecount | pins | isdirty
----------+-------+------------+------+---------
1 | 3 | 1 | 0 | f
2 | 58 | 0 | 0 | f
3 | 4 | 1 | 0 | f
4 | 5 | 1 | 0 | f
5 | 0 | 5 | 0 | f
7 | 1 | 2 | 1 | f
12 | 2 | 1 | 0 | f
(7 rows)
SELECT b.bufferid, m.* FROM pg_buffercache b, pg_buffercache_mark_dirty(b.bufferid) m
WHERE relfilenode = 16512 AND relblocknumber = 2;
bufferid | buffer_dirtied | buffer_already_dirty
----------+----------------+----------------------
12 | t | f
(1 row)
SELECT b.bufferid, e.* FROM pg_buffercache b, pg_buffercache_evict(b.bufferid) e
WHERE relfilenode = 16512 AND relblocknumber = 1;
bufferid | buffer_evicted | buffer_flushed
----------+----------------+----------------
7 | f | f
(1 row)
Buffer 7 has one pinning backend, and pg_buffercache_evict() refuses it.
The sweep treats it the same way: while the cursor is open the hand passes
buffer 7 six times and never lowers its usage count, which is still 2 when
the cursor closes. A pin held for a long time is harmless in that sense,
but the buffer can’t be reused while it lasts, and if every buffer were
pinned, the sweep would give up after NBuffers pinned buffers in a row
with “no unpinned buffers available”. tinypg’s tests check that last case;
the recording doesn’t show it.
pg_buffercache_mark_dirty() marked buffer 12 (block 2) dirty without
changing a byte. A real change would also have written to the write-ahead
log, which is the next lesson. When the hand stops at a dirty buffer, the
page has to be written before the buffer can take another one, and the
backend that wants the buffer does the write itself:
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id FROM books WHERE ctid = '(15,1)';
QUERY PLAN
----------------------------------------------
Tid Scan on books (actual rows=1.00 loops=1)
TID Cond: (ctid = '(15,1)'::tid)
Buffers: shared read=1 written=1
(3 rows)
written=1 is that write, by a query that only reads. In
GetVictimBuffer():
if (buf_state & BM_DIRTY)
{
Assert(buf_state & BM_TAG_VALID);
Assert(buf_state & BM_VALID);
/*
* We need a share-exclusive lock on the buffer contents to write it
* out (else we might write invalid data, eg because someone else is
* compacting the page contents while we write). We must use a
* conditional lock acquisition here to avoid deadlock. Even though
* the buffer was not pinned (and therefore surely not locked) when
* StrategyGetBuffer returned it, someone else could have pinned and
* (share-)exclusive-locked it by the time we get here. If we try to
* get the lock unconditionally, we'd block waiting for them; if they
* later block waiting for us, deadlock ensues. (This has been
* observed to happen when two backends are both trying to split btree
* index pages, and the second one just happens to be trying to split
* the page the first one got from StrategyGetBuffer.)
*/
if (!BufferLockConditional(buf, buf_hdr, BUFFER_LOCK_SHARE_EXCLUSIVE))
{
/*
* Someone else has locked the buffer, so give it up and loop back
* to get another one.
*/
UnpinBuffer(buf_hdr);
goto again;
}
src/backend/storage/buffer/bufmgr.c, lines 2586–2613
/* OK, do the I/O */
FlushBuffer(buf_hdr, NULL, IOOBJECT_RELATION, io_context);
LockBuffer(buf, BUFFER_LOCK_UNLOCK);
src/backend/storage/buffer/bufmgr.c, lines 2635–2637
FlushBuffer() writes the page, and before it does, it flushes the
write-ahead log up to the page’s LSN: the rule lesson 6 is about. Normally
the background writer tries to clean such buffers before the hand gets to
them, by looking ahead of the hand for dirty buffers that are unpinned with
usage count 0 and writing them. The recording turned that off.
Content locks
A pin keeps a page in its buffer. It doesn’t stop one backend from reading the page while another changes it; that is the job of the content lock, taken after the pin and held only briefly. In 19 it has three modes, share, share-exclusive and exclusive, and taking one is a compare-and-swap on the state word that succeeds only if nobody holds a conflicting mode:
if (mode == BUFFER_LOCK_EXCLUSIVE)
{
lock_free = (old_state & BM_LOCK_MASK) == 0;
if (lock_free)
desired_state += BM_LOCK_VAL_EXCLUSIVE;
}
else if (mode == BUFFER_LOCK_SHARE_EXCLUSIVE)
{
lock_free = (old_state & (BM_LOCK_VAL_EXCLUSIVE | BM_LOCK_VAL_SHARE_EXCLUSIVE)) == 0;
if (lock_free)
desired_state += BM_LOCK_VAL_SHARE_EXCLUSIVE;
}
else
{
lock_free = (old_state & BM_LOCK_VAL_EXCLUSIVE) == 0;
if (lock_free)
desired_state += BM_LOCK_VAL_SHARED;
}
src/backend/storage/buffer/bufmgr.c, lines 6143–6160
Exclusive needs the lock to be entirely free. Share-exclusive conflicts
with exclusive and with another share-exclusive, but not with share. Share
conflicts only with exclusive. What each is for, from the buffer manager’s
README: looking at tuples, or at their xmin and xmax to decide visibility,
needs share; adding a tuple or changing xmin or xmax needs exclusive, and
MarkBufferDirty() asserts that the caller holds it
(line 3190);
setting hint bits and writing the page out need share-exclusive. That last
pair is why GetVictimBuffer() asks for share-exclusive: while the page is
being written nobody can change it, so the bytes on disk and their checksum
agree, but readers holding share locks can carry on. Removing a tuple for
good needs more again, an exclusive lock taken while no other backend has
the buffer pinned, which is a later lesson’s business (VACUUM).
None of this shows in the recording. pg_buffercache has no column for a
buffer’s content lock, and every lock in the recording was taken and released inside a single
statement. This section comes from the source, and tinypg’s tests check its
own conflict table, not a server’s.
How long a page stays
Block 0 was read six times at the start, so it had usage count 5 and the
other pages of books had 1. Each pass of the hand took one from it: the
reads of blocks 6, 15, 20, 29 and 34 lowered it, and the read of block 43
found it at 0 and replaced it. A page of books read once survived one
pass. The usage count doesn’t record how often a page was used, only up to
five uses since the hand last went by, which is enough to keep a page that
is in steady use and lose one that was busy only for a while.
The pool after the last read, with the cursor still open, then the end of the transaction:
SELECT bufferid, relblocknumber AS block, usagecount, pinning_backends AS pins, isdirty
FROM pg_buffercache WHERE relfilenode = 16512
ORDER BY bufferid;
bufferid | block | usagecount | pins | isdirty
----------+-------+------------+------+---------
1 | 46 | 1 | 0 | f
2 | 42 | 0 | 0 | f
3 | 47 | 1 | 0 | f
4 | 33 | 0 | 0 | f
5 | 43 | 1 | 0 | f
6 | 34 | 0 | 0 | f
7 | 1 | 2 | 1 | f
8 | 35 | 0 | 0 | f
9 | 36 | 0 | 0 | f
10 | 37 | 0 | 0 | f
11 | 38 | 0 | 0 | f
12 | 44 | 1 | 0 | f
13 | 45 | 1 | 0 | f
14 | 39 | 0 | 0 | f
15 | 40 | 0 | 0 | f
16 | 41 | 0 | 0 | f
(16 rows)
CLOSE c;
COMMIT;
SELECT * FROM pg_buffercache_summary();
buffers_used | buffers_unused | buffers_dirty | buffers_pinned | usagecount_avg
--------------+----------------+---------------+----------------+----------------
16 | 0 | 0 | 0 | 0.4375
(1 row)
Buffer 5 holds block 43 now. Buffer 7 still holds block 1 with usage count 2, as it did when the cursor pinned it, and the pin goes with the transaction.
tinypg: bufmgr.py
tinypg/bufmgr.py is the pool: descriptors whose state is an integer
with PostgreSQL 19’s layout, a dict for the buffer table, a Backend with
its private pin counts and its locks, and the sweep:
def strategy_get_buffer(self):
"""StrategyGetBuffer(): run the clock until a buffer is unpinned and
has usage count 0; pin it and return it. Every unpinned buffer the
hand passes loses one from its usage count. Gives up after a whole
round of pinned buffers with nothing changed."""
trycounter = self.nbuffers
while True:
buf = self.descs[self.clock_sweep_tick()]
if refcount(buf.state) != 0:
if self.trace is not None:
self.trace.append(("pinned", buf.buf_id))
trycounter -= 1
if trycounter == 0:
raise NoUnpinnedBuffers("no unpinned buffers available")
continue
if usagecount(buf.state) != 0:
buf.state -= BUF_USAGECOUNT_ONE
if self.trace is not None:
self.trace.append(("decrement", buf.buf_id))
trycounter = self.nbuffers
continue
buf.state += BUF_REFCOUNT_ONE # pin it
if self.trace is not None:
self.trace.append(("victim", buf.buf_id))
return buf
tinypg/bufmgr.py, lines 201–225
A pin, with the private count that keeps a second pin from the same backend out of the shared word:
def pin(self, buf_id):
"""PinBuffer() with the default strategy. The first pin of this
backend adds to the shared refcount and, up to 5, to the usage count."""
buf = self.pool.descs[buf_id]
if buf_id in self.private:
self.private[buf_id] += 1
else:
buf.state += BUF_REFCOUNT_ONE
if usagecount(buf.state) < BM_MAX_USAGE_COUNT:
buf.state += BUF_USAGECOUNT_ONE
self.private[buf_id] = 1
return bool(buf.state & BM_VALID)
tinypg/bufmgr.py, lines 340–351
tinypg is one process, so “another backend” is another Backend object,
and a lock that would make one wait raises WouldWait instead, since
nobody could ever release it. Tables can now go through a pool: HeapFile
takes the page to change in its buffer, pinned and exclusively locked, and
marks the buffer dirty when the row is in:
def get_for_update(self, blkno):
"""(buffer, page) to change: through the pool, the page in its
buffer, pinned and exclusively locked; without one, a copy (buffer
None) that put_tuple() writes back."""
if self.pool is None:
return None, self.read_page(blkno)
buf = self.backend.read_buffer(self.locator, MAIN_FORKNUM, blkno)
self.backend.lock(buf, EXCLUSIVE)
return buf, self.backend.page(buf)
tinypg/heapfile.py, lines 127–135
if buf is None:
self.write_page(blkno, page)
else:
self.backend.mark_dirty(buf)
self.backend.unlock_release(buf)
tinypg/heapfile.py, lines 153–157
A test inserts 200 rows through a pool of three buffers, so that pages are
evicted and read back many times, and the file comes out identical to the
one written page by page as before. The comparison replays the recording:
it seeds a pool with the snapshot taken after warm-up and the inferred
hand, runs the same steps, and compares the EXPLAIN counts and all 16
buffers after each one:
$ python3 -m tinypg compare tests/fixtures/pg19_buffers.json
a pool of 16 buffers, seeded from pg_buffercache; clock hand at buffer 3 (inferred)
0. read block 0: PostgreSQL read=1, tinypg read=1; all 16 buffers the same
1. read block 0: PostgreSQL hit=1, tinypg hit=1; all 16 buffers the same
2. read block 0: PostgreSQL hit=1, tinypg hit=1; all 16 buffers the same
3. read block 0: PostgreSQL hit=1, tinypg hit=1; all 16 buffers the same
4. read block 0: PostgreSQL hit=1, tinypg hit=1; all 16 buffers the same
5. read block 0: PostgreSQL hit=1, tinypg hit=1; all 16 buffers the same
6. read block 1: PostgreSQL read=1, tinypg read=1; all 16 buffers the same
...
56. read block 47: PostgreSQL read=1, tinypg read=1; all 16 buffers the same
57. show; all 16 buffers the same
58. unpin block 1; all 16 buffers the same
59. show; all 16 buffers the same
every step the same
Every step matches: the 48 misses chose the same victim, the 5 hits found the same buffer, every usage count, pin and dirty flag is the same, and the one write happened at the same read.
What tinypg leaves out: the buffer mapping partitions and their locks, the
spinlock in the state word, waiting for I/O, the read streams that let a
sequential scan in 19 read ahead and pin several buffers at once, the small
rings of buffers that large scans, VACUUM and bulk writes use instead of
the whole pool
(GetAccessStrategy()),
the background writer, and local buffers for temporary tables. Its free
space map still reads and writes its own file directly.
Try it yourself
With a PostgreSQL 19 server and pg_buffercache; a small shared_buffers
makes the sweep easy to watch, as in the recording.
A nested loop join can pin the same page twice from one backend at the same moment. What do
pinning_backendsandusagecountshow for it?Answer
pinning_backendsis 1, and the usage count went up once. The second pin finds this backend’s private entry for the buffer (ref != NULLinPinBuffer()) and only increments that, without touching the state word. tinypg’stest_a_backend_counts_oncechecks the same: one backend pinning twice gives refcount 1 and usage count 1, and a second backend makes them both 2. Not tried on the server.All 16 buffers are unpinned and at usage count 5. How many buffers does the hand look at to find a victim, and which one does it take?
Answer
- Each pass lowers every buffer by one, so after five passes (80 buffers
looked at) all are at 0, and the first buffer of the sixth pass, the one
the hand started at, is taken. That is the “as many as
BM_MAX_USAGE_COUNT+1 complete cycles” of the comment. tinypg’stest_at_most_six_passescounts 5 × 16 + 1 = 81 steps of the hand.
- Each pass lowers every buffer by one, so after five passes (80 buffers
looked at) all are at 0, and the first buffer of the sixth pass, the one
the hand started at, is taken. That is the “as many as
In the recording, the read of block 15 shows
written=1. Which page was written, and why by a query that only reads?Answer
Block 2, in buffer 12, which
pg_buffercache_mark_dirty()had marked dirty. The read of block 15 needed a buffer; the hand lowered eight usage counts, passed pinned buffer 7, and stopped at buffer 12, unpinned and at usage count 0. A dirty victim is written by the backend that takes it, under a share-exclusive lock, before it is reused. With the background writer on, it might have been written earlier, and the read would then show no write.Sixteen cursors in one session each fetch a row from a different page and stay open. What does the next read of a seventeenth page do?
Answer
It fails with “no unpinned buffers available”: the sweep counts down
trycounterfromNBuffersat every pinned buffer and gives up when it reaches zero, rather than wait for a pin that may never be released. tinypg raisesNoUnpinnedBuffersintest_every_buffer_pinned, with three buffers. Not tried on the server.
The tinypg side, once the repository is public:
git clone https://github.com/toothywalrus/tinypg && cd tinypg
git checkout lesson-05.1
python3 -m unittest
python3 -m tinypg compare tests/fixtures/pg19_buffers.json
python3 -m tinypg trace-buffers tests/fixtures/pg19_buffers.json
To record your own: set the server up as the docstring of
tools/record_buffers.py says (shared_buffers = '128kB', autovacuum = off, bgwriter_lru_maxpages = 0, then restart), and run it with --out DIR and the usual PGHOST, PGPORT, PGUSER and PGDATABASE. It checks
the three settings, drops and recreates the table books, and takes the
clock hand from its own warm-up, so every run starts from a different pool
and should still match step for step.
Sources
All PostgreSQL code is quoted from tag
REL_19_0 (commit
5c839a2a08b9), with tabs expanded to four spaces and the common indentation
removed.
src/backend/storage/buffer/README: pins, the three content lock modes and what each is for, the clock sweep, rings, the background writersrc/include/storage/buf_internals.h: the state word,BufferTag,BufferDesc,BM_MAX_USAGE_COUNTsrc/backend/storage/buffer/bufmgr.c:BufferAlloc(),GetVictimBuffer(),PinBuffer(),MarkBufferDirty(),BufferLockAttempt(), and the functions behindpg_buffercache_evict()andpg_buffercache_mark_dirty()src/backend/storage/buffer/freelist.c:ClockSweepTick(),StrategyGetBuffer()src/backend/storage/buffer/buf_init.c,buf_table.c: the arrays and the buffer tablepg_buffercache: the view and its test functions- tinypg, tag
lesson-05.1:tinypg/bufmgr.py,tinypg/heapfile.py,tests/test_bufmgr.py, andtools/record_buffers.py, which recorded every psql and shell output above
ls postgres-internals/
Storage
- 01 A table is a file of 8 KB pages draftWhere a table lives on disk, the page header, line pointers, tuples filling from the end, and what a ctid is.
- 02 Inside a tuple: alignment, nulls and varlena draftHow column values are laid out after the header, why column order changes a row's size, and the 1-byte and 4-byte length headers.
- 03 TOAST: values too big for a page draftCompression, out-of-line storage in a TOAST table, and the 2 KB threshold that triggers them.
- 04 The free space map draftThe _fsm fork: a tree of one-byte free-space categories that tells an INSERT which page has room.
Buffers and durability
- 05 Shared buffers: a page cache with pins and locks draftThe buffer table, buffer descriptors, pins, content locks, and clock-sweep eviction.
- 06 The write-ahead log: records and LSNs draftWAL record layout, pd_lsn, and the rule that a page may not reach disk before its log does.
- 07 Checkpoints, full-page writes and checksums draftWhat a checkpoint guarantees, why the first change after one logs the whole page, and how pd_checksum is computed.
- 08 Crash recovery: replaying the log plannedStarting from the last checkpoint's redo point and replaying records whose LSN is newer than the page's.
MVCC
- 09 Transaction IDs and the commit log plannedAssigning xids, and pg_xact: two bits of commit status per transaction.
- 10 xmin, xmax and the life of a row version plannedWhat UPDATE and DELETE really write, and following ctid chains to the newest version.
- 11 Snapshots: what a transaction can see plannedxmin, xmax and the in-progress list, and when READ COMMITTED and REPEATABLE READ take them.
- 12 Visibility rules and hint bits plannedHeapTupleSatisfiesMVCC case by case, and why reading a row can write to its page.
- 13 HOT updates and page pruning plannedHeap-only tuples, redirect line pointers, and cleaning a page while reading it.
- 14 VACUUM: removing dead tuples plannedScanning the heap, cleaning indexes, and marking line pointers unused.
- 15 The visibility map plannedThe _vm fork's all-visible and all-frozen bits, and what index-only scans and VACUUM get from them.
- 16 Freezing and transaction ID wraparound plannedWhy 32-bit xids wrap around, what freezing writes, and multixacts.
Indexes
- 17 B-tree pages and the Lehman–Yao tree plannedSpecial space, high keys and right links: a B-tree you can search while it changes.
- 18 B-tree insertion and page splits plannedDescending the tree, choosing a split point, and finishing a split in the parent.
- 19 Deduplication and bottom-up deletion plannedPosting lists for duplicate keys, and deleting old versions before a page has to split.
- 20 Hash indexes plannedBuckets, overflow pages and linear-hashing splits.
- 21 GIN and GiST, briefly plannedAn inverted index and a balanced tree of predicates: what each stores and when each fits.
Queries
- 22 From text to parse tree plannedThe grammar, the raw parse tree, and why parsing needs no catalog.
- 23 Analysis and rewriting plannedResolving names against the catalog, the Query tree, and the rewriter's views and rules.
- 24 The planner: paths and the cost model plannedseq_page_cost, random_page_cost and cpu_tuple_cost, and how the cheapest path wins.
- 25 Statistics and selectivity plannedWhat ANALYZE samples, most common values, histograms, and estimating a WHERE clause.
- 26 Join algorithms and join order plannedNested loop, hash and merge joins, and searching the join orders.
- 27 The executor: Volcano-style iterators plannedPlan nodes that each return one row per call, from a sequential scan up to a sort.
Concurrency and the server
- 28 Locks: heavyweight, row-level and lightweight plannedThe lock manager, row locks stored in xmax, LWLocks and spinlocks, and deadlock detection.
- 29 Processes and shared memory plannedThe postmaster, one backend per connection, the background workers, and what they share.
- 30 Streaming replication plannedShipping WAL to a standby, replaying it there, and replication slots.