Sub topic 3
Sizing shared_buffers
This chapter assumes you can run queries in psql, edit postgresql.conf and restart a server, and read a simple EXPLAIN plan. It also assumes you know that the operating system caches file data in RAM.
What shared_buffers is
shared_buffers sets the size of PostgreSQL's own cache of table and index pages. The server allocates it once at startup as shared memory, and every backend process reads and writes through it. Data is cached in 8 kB blocks, the default block size.
The default is 128MB, which suits a small test machine and is too low for most production servers. Changing it needs a full restart. A reload is not enough.
The read path and double buffering
PostgreSQL does not read data files directly. It asks the kernel for blocks, so the operating system page cache sits underneath shared_buffers. A page can therefore live in both caches at once. This is called double buffering.
This has two consequences:
- A
blks_readin PostgreSQL statistics can still be served from RAM by the kernel. It is not necessarily a disk read. - Giving PostgreSQL more memory does not mean more data is cached overall. Memory given to
shared_buffersis memory the page cache can no longer use for the same pages.
How buffers are used and evicted
Each buffer holds one page and carries a usage count from 0 to 5. Every time a backend uses a page, its count goes up. A clock-sweep algorithm walks the buffers when a free one is needed. It lowers each count as it passes and evicts a buffer whose count has reached zero. Frequently used pages therefore stay cached, and pages touched once drift out.
Some operations deliberately avoid flooding the cache. Large sequential scans, bulk writes, and VACUUM use a small ring of buffers instead of the whole pool. A big table scan will not push your hot index pages out of shared_buffers. It also means a table larger than shared_buffers can be scanned repeatedly without the cache ever holding all of it.
Choosing a starting value
The usual rule for a dedicated database server is to start at about 25% of RAM. Most guidance advises against going far above 40%, because the extra memory competes with the page cache and gives diminishing returns.
| Machine RAM | Starting shared_buffers | Notes |
|---|---|---|
| 2 GB | 512MB | Leave room for the OS and connections |
| 8 GB | 2GB | |
| 16 GB | 4GB | Common starting point |
| 64 GB | 16GB | Check the checkpoint and huge pages settings |
| Shared with other services | 10% to 20% | Other processes need the memory too |
These are starting values, not answers. The right number depends on your working set, which is the set of pages your queries touch regularly.
- If the working set fits in 25% of RAM, a bigger value gains little.
- If the working set is far larger than RAM, no practical
shared_bufferssetting caches it, and storage speed matters more. - Between those cases, test.
Checking and changing the current value
shared_buffers is stored in pg_settings in units of 8 kB blocks. The context column shows postmaster, which means a restart is needed.
SELECT name, setting, unit, context, pending_restart
FROM pg_settings
WHERE name = 'shared_buffers';To change it, write the new value and restart:
ALTER SYSTEM SET shared_buffers = '4GB';ALTER SYSTEM writes to postgresql.auto.conf, which overrides postgresql.conf. Until the restart, pg_settings.pending_restart shows t and SHOW shared_buffers still reports the old value. Restart the service with your platform's tool, for example systemctl restart postgresql, and check again with SHOW shared_buffers;.
Measuring the effect
Hit ratio
The cumulative statistics view pg_stat_database counts block requests served from shared_buffers (blks_hit) and those that were not (blks_read).
SELECT datname,
blks_hit,
blks_read,
round(blks_hit::numeric / nullif(blks_hit + blks_read, 0), 4) AS hit_ratio
FROM pg_stat_database
WHERE datname = current_database();Read the number with care:
- The counters are cumulative since the last statistics reset, so a ratio over months hides recent behavior. Take two snapshots and compare the differences.
- A ratio of 0.99 does not prove the system is healthy. An analytic workload that scans huge tables may legitimately run at 0.80.
- A high ratio on a busy OLTP system with slow queries means the bottleneck is elsewhere.
What is in the cache
The pg_buffercache extension shows the contents of every buffer. It ships with PostgreSQL's contrib modules and needs superuser rights or the pg_monitor role.
CREATE EXTENSION IF NOT EXISTS pg_buffercache;
SELECT c.relname,
count(*) AS buffers,
pg_size_pretty(count(*) * current_setting('block_size')::bigint) AS cached_size
FROM pg_buffercache b
JOIN pg_class c
ON b.relfilenode = pg_relation_filenode(c.oid)
AND b.reldatabase IN (0, (SELECT oid FROM pg_database
WHERE datname = current_database()))
GROUP BY c.relname
ORDER BY buffers DESC
LIMIT 10;This lists the ten relations holding the most cache. If the top entries are your hot tables and indexes, the cache is doing its job. If it is full of a large table that is only scanned once, consider why.
To see how much of the pool is warm and how much is dirty (modified and not yet written):
SELECT usagecount,
count(*) AS buffers,
sum(isdirty::int) AS dirty
FROM pg_buffercache
GROUP BY usagecount
ORDER BY usagecount;A NULL usage count means the buffer is unused. Many unused buffers after the server has been busy for a while suggest shared_buffers is larger than the working set, so a bigger value will not help.
Per-query view
EXPLAIN (ANALYZE, BUFFERS) shows how one query used the cache:
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE customer_id = 42;Look for Buffers: shared hit=... read=... on each node. hit means found in shared_buffers. read means requested from the kernel. Running the same query twice shows whether the second run is mostly hits. If it is not, the pages are not staying cached.
The cost side of a larger pool
Increasing shared_buffers has costs that show up elsewhere:
- Checkpoints. Every dirty buffer must be written at a checkpoint. A larger pool can hold more dirty pages, so write bursts get bigger unless the WAL and checkpoint settings, covered later in this tutorial, are raised with it.
- Startup and memory mapping. Large shared memory regions use many small memory pages by default. On Linux, huge pages reduce this overhead, and a later chapter covers them.
- Less room for everything else. Per-query memory, autovacuum workers, and the OS page cache all draw from the same RAM. A budget for those is built in a later chapter.
A practical approach is to change by modest steps, for example 25% to 30% of RAM, and compare the same workload. If hit ratio, query times, and checkpoint behavior do not improve, return to the smaller value.
Common mistakes
- Setting
shared_buffersto 75% of RAM on the belief that more caching is always better. The page cache shrinks, the OS may start swapping, and checkpoints get heavier. - Treating
blks_readas disk I/O. Some of it is satisfied by the page cache. - Editing
postgresql.confand only reloading. The new value is ignored until restart, andpending_restartwill show it. - Judging a change after a restart without allowing the cache to warm. Right after a restart the pool is empty, so hit ratio starts low. Compare after a representative period of normal load.
Exercise
A server with 32 GB of RAM, dedicated to PostgreSQL, still has the default sharedbuffers of 128MB. You run ALTER SYSTEM SET sharedbuffers = '8GB'; followed by SELECT pgreloadconf(); and then SHOW shared_buffers; which still reports 128MB. Why, how do you confirm the cause with a query, and what do you do next?
Show answer
sharedbuffers has context postmaster, so it only takes effect after a full server restart, and a reload does not apply it. Confirm with SELECT name, setting, context, pendingrestart FROM pgsettings WHERE name = 'sharedbuffers'; which shows context = postmaster and pendingrestart = t. Restart the service, then run SHOW sharedbuffers; to see 8GB, which is the 25% starting value for 32 GB of RAM. After the cache has warmed under normal load, compare hit ratio, query timings, and checkpoint logs against the previous values.
Exercise
After a restart your pgbuffercache query shows that 60% of buffers have a NULL usagecount long after the system reached normal load. What does this suggest about increasing sharedbuffers further?
Show answer
A large share of unused buffers means the working set already fits in the pool, so a larger shared_buffers will not improve caching. The memory is better left to the OS page cache and other uses, and the value may even be reduced.