An erratum for three earlier posts. backend_flush_after, bgwriter_delay and bgwriter_lru_maxpages all send you to pg_stat_bgwriter.buffers_backend to find out whether backends are writing their own dirty pages. PostgreSQL 17 removed that column, and it was never in pg_stat_checkpointer, where the first of those posts also tells you to look. (buffers_checkpoint left pg_stat_bgwriter in the same release and is now pg_stat_checkpointer.buffers_written.) On 17 and later, backend writes are in pg_stat_io, which is covered below. The third post also has the background writer scanning “the buffer pool’s LRU list”; there is no such list, and what it scans is described below as well.
shared_buffers is the parameter everybody changes and almost nobody looks inside. The advice fits in a sentence (a quarter of RAM, restart, done), has not really moved since 2010, and gets repeated with great confidence, usually without any account of what the server does when the quarter fills up. So this parameter gets two posts. This one is the machinery: what a shared buffer is, how PostgreSQL picks a page to throw out, and what goes on between PostgreSQL’s cache and the kernel’s cache directly underneath it. The second is the number, along with shared_memory_size, shared_memory_size_in_huge_pages and shared_memory_type, three parameters about the memory that the number turns into.
The facts first. The default is 128MB, written into postgresql.conf by initdb once it has confirmed that the kernel will hand over that much (when it won’t, initdb works down a list that bottoms out at 400kB, and you have other problems). The context is postmaster, so changing it takes a restart; that is as true in PostgreSQL 19 as it was in 7.1. A value without units is in blocks of block_size, which means 8kB. The minimum is 16 blocks, and the maximum is 1,073,741,823 of them, eight terabytes less one block.
(The minimum does work. I started 19.0 with shared_buffers = 128kB, sixteen buffers, and it ran a count(*) over a 61MB table and a five-way catalog join without complaint. The eighth open cursor got ERROR: no unpinned buffers available, which is the buffer manager reporting that all sixteen were spoken for.)
An array, a hash table and a counter
Shared buffers is an array. At startup the postmaster allocates one 8kB slot per buffer, a 64-byte header for each slot, and a hash table that maps a page’s identity (tablespace, database, relation file, fork, block number) to the slot holding it. Every backend maps the same memory, and nearly every read and write of table or index data, by any process, goes through this array. (The exceptions are bulk operations that write whole files at once, such as index builds, and temporary tables, whose pages live in each backend’s private temp_buffers.)
A backend that wants a page hashes its identity, takes one of the hash table’s 128 partition locks in share mode, and looks. If the page is there, the backend pins the buffer, which means incrementing a reference count in the header, and gets on with its work; a pinned buffer cannot be handed to anybody else. That is a hit. If the page is not there, it has to be read into some buffer, and on a busy server with more data than buffers, every buffer already holds something. Reading a page in means throwing a page out.
Two more things in the header matter for that decision. One is a dirty flag. A modified page is not written out at commit (the WAL is; that is the point of having WAL); it stays in the array, marked dirty, until somebody gets around to writing it. The other is the usage count, an integer from 0 to 5, and it is the entire basis on which PostgreSQL decides what to keep.
Worse on purpose
Choosing the victim is an old problem. The ideal answer (evict the page that will go unused the longest) requires a time machine, so everybody approximates, and the classic approximation is LRU: evict the page used least recently. PostgreSQL through 7.4 did LRU the obvious way. Unpinned buffers sat on a linked list; a buffer came off the list when it was pinned and went back on the tail when it was released, and the head of the list was the next victim. All of it happened under one lock that covered the whole buffer manager. On a single CPU, nobody minded.
8.0, released in January 2005, replaced the list with ARC, an algorithm from IBM’s Almaden lab that tracks recently used and frequently used pages separately and adapts the balance between them. Jan Wieck implemented it. Two days before the release, a thread on pgsql-hackers took up the fact that IBM had a patent application pending on it. A month later the core team announced that it was coming out, in a minor release, and 8.0.2 shipped in April with an older algorithm called 2Q in its place and a release note of unusual candor: 2Q might be a few percent slower, and “A better cache management algorithm will appear in 8.1.”
It did, that November, and “better” meant something specific. The trouble with 8.0 was never how it chose its victims. (Nobody had shown that it chose them especially well, either; Tom Lane observed at the time that there was no hard evidence ARC was far better than the alternatives, and that its implementer had withdrawn his own opinion that it was a big improvement.) The trouble was the lock, which the 8.1 release notes own up to as a serious scaling problem on multiprocessor machines. The replacement in 8.1, the clock sweep, is a cruder judge of which pages matter than either ARC or 2Q. What it offers is that a hit costs next to nothing. There is no list to maintain, so a hit no longer needs an exclusive lock on anything global: only a counter to bump, in a header the backend was touching anyway. On anything with more than a couple of CPUs that trade is not close, and PostgreSQL has been making it for twenty-one years. The ceiling of 5 on the usage count shipped in 8.1 and has never changed.
The rules fit in a paragraph. A page read into a buffer starts with a usage count of 1. Each time a backend takes a new pin on the buffer, the count goes up by one, stopping at 5. A backend that needs a victim advances a shared pointer, the clock hand, around the array one buffer at a time. If the buffer under the hand is pinned, the hand moves on. If its count is above zero, the count drops by one and the hand moves on. The first unpinned buffer found at zero is the victim. Nothing else is consulted.
Both halves of that are easy to watch with pg_buffercache. Here is one heap page on 19.0, fetched by ctid so that each query pins it exactly once, with its usage count read back after every fetch:
1 after INSERT and CHECKPOINT usagecount = 1
2 after fetch 1 usagecount = 2
3 after fetch 2 usagecount = 3
4 after fetch 3 usagecount = 4
5 after fetch 4 usagecount = 5
6 after fetch 5 usagecount = 5
7 after fetch 8 usagecount = 5
8
9 evicted, then fetched 100,000 times usagecount = 5
Four fetches took the page from 1 to 5, and a hundred thousand could not take it any higher. That is as popular as a page gets. The root of the busiest index on the system and a page that five queries happened to touch in the last minute carry the same score.
Decay is the other half. I shrank the pool to 16MB (2,048 buffers), pinned one page until it reached 5, left it alone, and loaded new pages 256 at a time through the ordinary path:
1 new pages loaded usage count of the idle page
2 0 5
3 1,536 5
4 1,792 4
5 2,048 3
6 3,584 3
7 3,840 1
8 5,376 1
9 5,632 0
10 5,888 (evicted)
Nobody touched that page, and it outlasted somewhere between 5,600 and 5,900 arrivals, close to three times the capacity of the pool. (The count falls in pairs because the hand makes two laps per pool-full here. Every page it loads comes in at 1, so after a lap spent evicting it finds nothing but 1s ahead, and it has to go all the way around knocking them down before it can evict again.) A count of 5 buys five passes of the hand, and the sixth takes the buffer.
Two things follow. The count rises fast and falls slowly, so on a server whose working set fits in the pool nearly every buffer sits at 5, and the algorithm has no opinion about any of them. (In one of the tests in the second post, with 3.7GB of data in a 4.5GB pool, 478,980 of the 479,130 buffers in use were at 5.) That is fine, since nothing needs evicting. And when a pool in that state does need victims, because a new table has become hot or a report is reading something unusual, the hand can need five full laps of the array before anything reaches zero, and takes its victim on the sixth. That work grows with the size of the pool, and it is done by whichever backend happened to need a buffer. It is the mechanical basis of the old belief that a large shared_buffers costs CPU.
(pg_buffercache_usage_counts(), new in 16, reports the distribution of counts far more cheaply than the pg_buffercache view does; pg_buffercache_summary(), also from 16, gives the average.)
What has changed since 2005 is everything around the algorithm. 8.1 broke up the one big lock. 8.2 split the lock on the hash table sixteen ways; 9.5 made that 128 and turned the clock hand into an atomic counter, so that advancing it takes no lock except once per lap; 9.6 made pinning a compare-and-swap on the header instead of a spinlock acquisition. PostgreSQL 19 has been the busiest release in this code since then. It deleted the free list (through 18, buffers that had never been used, or had been emptied by a DROP or TRUNCATE, were handed out from a linked list under a spinlock, the same spinlock that starred in the Linux 7.0 regression in April; in 19 an empty buffer is just a buffer at zero, found by the sweep like any other). It stopped locking buffer headers during the sweep. And it widened the header’s state word to 64 bits so that the lock on the page’s contents could move into it. The algorithm is the one from 2005. What it costs to run on a 96-core machine is a different matter.
Scans that don’t count
Left to itself, the sweep has an obvious failure. One SELECT count(*) over a table larger than the pool brings every page of that table in at a count of 1, the hand grinds every other count down to make room, and a query nobody will run again has replaced the working set with pages nobody will ask for again.
Since 8.3, the sweep has not been left to itself. A sequential scan of any table larger than one quarter of shared_buffers gets a buffer access strategy: a small private ring of buffers that the scan reuses over and over, so that the table passes through the ring and the rest of the pool never notices. VACUUM gets a ring too (vacuum_buffer_usage_limit, 2MB by default since 17), and since 8.4 so have bulk writes such as COPY and CREATE TABLE AS (16MB, or an eighth of the pool if that is smaller). A pin taken through a ring raises a usage count from 0 to 1 and no further, so a ring scan cannot make pages look hot. The scan ring is 256kB at minimum. Since 18 it grows by io_combine_limit times effective_io_concurrency, to leave room for reads in flight, which with the default I/O settings makes it 2.25MB. It is also capped by a per-backend pin limit (the pool divided by the number of process slots), and with an otherwise default configuration that cap binds below about 400MB of shared_buffers; at 128MB it holds the ring to 94 buffers.
Here is a 128MB pool on 19.0, so the threshold is 32MB. hot is a 61MB table already loaded, with every page at a usage count of 3. big is 337MB. mid is 31MB, just under the line.
1 buffers holding pg_stat_io
2 hot big mid evictions reuses
3 hot loaded, usage count 3 7,808 0 0
4 SELECT count(*) FROM big (ring) 7,808 94 0 0 43,011
5 SELECT count(*) FROM mid (no ring) 7,808 94 3,904 0
6 pg_prewarm('big') (no ring) 0 16,255 0 38,875
The scan of big read 337MB through 94 buffers and evicted nothing. The scan of mid went through the pool the ordinary way and left all 3,904 of its pages behind at a count of 1. Reading big a second time with pg_prewarm, which does not use a ring, took 38,875 evictions and left not one page of hot in memory.
The ring has consequences that surprise people. A table bigger than a quarter of the pool never gets into the pool by being sequentially scanned, however often you scan it; every such scan reads it from the kernel again, and whether that is fast is the kernel’s business. The threshold also moves when the setting does. Raise shared_buffers from 2GB to 16GB and every table between 500MB and 4GB stops being ring-scanned and starts being loaded into the pool, which is not always what the person raising it had in mind.
Somebody has to write it
A clean victim costs nothing to evict: the backend drops it from the hash table and reuses the slot. A dirty victim has to be written first, by the backend that drew it, in the middle of whatever query needed the buffer. Because a data page must never reach storage ahead of the WAL that describes it, that backend may have to flush WAL up to the page’s LSN before it can write the page. That is a write(), and possibly an fsync(), charged to somebody’s SELECT.
Two background processes exist to keep that from happening. The background writer scans ahead of the clock hand and cleans buffers that are about to become victims; its parameters have their own posts. (The lru in bgwriter_lru_maxpages is a courtesy title. The name arrived in 8.1, the release that removed the last LRU list from the buffer manager.) The checkpointer writes every buffer that was dirty when its checkpoint began, in file order since 9.6, which is the checkpoint tour.
The view that says who is doing the writing is pg_stat_io, from 16 on: writes by backend_type, alongside evictions and, for the ring contexts, reuses. If client backend owns a meaningful share of the writes in the normal context, the background writer is losing. Here it is losing badly: five minutes of a write-heavy pgbench on 19.0, with a pool less than half the size of the data and the background writer at its defaults.
1 backend_type writes
2 client backend 2,297,440
3 background writer 145,493
4 autovacuum worker 65,304
5 checkpointer 62,677
Nine page writes in ten were done by a backend in the middle of somebody’s transaction. (pg_stat_bgwriter.maxwritten_clean went up 1,449 times over the same five minutes, which is the background writer reporting that it hit bgwriter_lru_maxpages and stopped with work still to do.)
The cache under the cache
Everything so far describes one cache. There are two.
PostgreSQL does ordinary buffered I/O. When a backend misses in shared buffers, it asks the kernel for the block with a pread() (since 18 the request may go through the asynchronous I/O subsystem instead, but it is the same request to the same kernel). The kernel keeps its own cache of file pages, checks it first, and fills it as it goes. So a block that has been read once is in memory twice. I restarted 19.0 with a 1GB pool, dropped the kernel’s cache, and read the 337MB table once, checking the kernel’s side with vmtouch:
1 blocks in 4kB pages in the /proc/meminfo
2 shared buffers kernel's page cache Cached Shmem
3 after restart and drop_caches 0 0 / 86,210 227 MB 57 MB
4 after SELECT pg_prewarm('big') 43,105 86,210 / 86,210 908 MB 396 MB
All 43,105 blocks are in shared buffers, and all 43,105 are also in the page cache, as 86,210 kernel pages. Cached rose by 681MB for a 337MB table (Linux counts shared memory there as well as file pages). This is double buffering, and it is the price of a decision PostgreSQL made thirty years ago and has not finished unmaking.
The two caches do not coordinate. The kernel cannot see usage counts and has no idea which of its pages PostgreSQL also holds. PostgreSQL cannot see the kernel’s lists and does not know, when it evicts a page, whether the kernel still has a copy. Each runs its own replacement policy over an overlapping set of pages.
The kernel’s cache does things PostgreSQL’s cannot, though. It is elastic: it grows into whatever memory nobody else is using and shrinks the moment somebody wants it, where shared buffers is one fixed allocation made at startup. It schedules and merges writes. And for most of PostgreSQL’s history it did all the read-ahead; a sequential scan asked for one block at a time, and it was the kernel that noticed the pattern and fetched the next ones early. (PostgreSQL has been taking that job back. Since 17, scans ask for blocks in runs of up to io_combine_limit, and since 18 they issue those requests ahead of need, which is why the ring scan earlier fetched its 43,105 blocks in 2,698 reads.)
Writes take the same route. A dirty buffer “written” by a backend, the background writer or the checkpointer has been copied into the page cache and nothing more. It reaches storage when the kernel gets around to it, when one of PostgreSQL’s *_flush_after hints asks for it, or when the checkpointer calls fsync(), whichever comes first; that story is the writeback tour and the fsync post.
What makes the arrangement tolerable is the price of a miss. I ran 200,000 primary-key lookups inside a single query against a 2.5-million-row table (337MB of heap, 54MB of index) three ways: with everything in shared buffers; with shared_buffers at 16MB, so that the index leaf and the heap page for nearly every lookup had to come from the kernel, which had them; and the same again while evicting the files from the page cache continuously, so that those reads went to storage.
1 200,000 lookups, 800,000 buffer accesses query time per read
2 all hits in shared buffers 0.39 - 0.45 s -
3 400,000 reads, served by the page cache 0.99 - 1.10 s 1.6 - 1.8 µs
4 400,000 reads, served by storage 19.6 - 20.3 s 47 - 49 µs
A read that the page cache can satisfy costs under two microseconds: a system call and an 8kB copy. That is enough to make this query about two and a half times slower than the all-hits case. It is also nearly thirty times cheaper than a read from this machine’s storage, a virtio disk that answers in under 50 microseconds; on a network-attached cloud volume, the last row is far worse.
So the page cache is a respectable second tier, and two practical points fall out of the table. The first is about instrumentation. shared read in EXPLAIN (BUFFERS) and blks_read in pg_stat_database count blocks requested from the kernel, reads in pg_stat_io counts the requests, and none of them knows whether the kernel had to go any further. The buffer cache hit ratio is computed from exactly those numbers, which is why it is such a poor guide: it cannot tell the second row of that table from the third. With track_io_timing on, you can. Divide read_time by reads in pg_stat_io for client backends; a few microseconds per read means the page cache is absorbing the misses, and tens of microseconds or more means storage is. (The figure is per request, and a request made through a read stream can cover many blocks, so compare like with like.) The planner has to be told about both caches as well, which is the whole job of effective_cache_size.
The second is that the page cache would be working for PostgreSQL even if every table fit in shared buffers. WAL is written through it. Sort and hash spill files exist nowhere else. A base backup reads through it, and so does every ring-scanned table from two sections ago. Memory given to shared buffers is memory taken from all of that.
The way out of double buffering is direct I/O, with PostgreSQL bypassing the page cache and owning the only copy. The switch exists and is named debug_io_direct, and the name is still accurate: the 19 documentation says it reduces performance and is for developer testing only. Asynchronous reads arrived in 18 and became operable in 19; writes are still synchronous and still buffered. Until that changes, every PostgreSQL you can run yourself has two caches, and no parameter decides what goes in which.
shared_buffers sets one number, the length of the array. The sweep, the ceiling of 5, the quarter-pool threshold and the kernel’s cache underneath are either compiled in or somebody else’s. What the number buys is the difference between the first row of that last table and the second, for as many pages as will fit, at the price of keeping some of them in memory twice.
(I consult on PostgreSQL through PGX Inc..)