Sub topic 4
effective_cache_size and the OS page cache
This chapter assumes you can run queries in psql, edit postgresql.conf, and read a simple EXPLAIN plan. It also assumes you know that the operating system caches file contents in unused RAM. By the end you should be able to set effective_cache_size from a machine's memory, explain what it does and does not do, and recognize when it is set wrongly.
Two caches, one data path
PostgreSQL reads table and index data in 8 kB blocks. A block can be in one of three places when a query needs it:
- In
shared_buffers, PostgreSQL's own cache in shared memory. - In the operating system page cache, which holds recently used file contents in otherwise free RAM.
- On disk only.
Most PostgreSQL data files are read through the normal file system interface, not with direct I/O. A block read from disk therefore usually lands in the OS page cache, and PostgreSQL then copies it into shared_buffers. The same block can sit in both caches at once. That double caching is normal.
This has a consequence for the statistics. In pg_stat_database, a block counted in blks_read was not in shared_buffers. It may still have come from the OS page cache and not from the physical disk. A low blks_hit ratio therefore does not prove that the disk is busy.
What effective_cache_size does
effective_cache_size is a planner hint. It is the planner's estimate of how much memory is available for caching data files, counting both shared_buffers and the OS page cache. It is used only while the planner chooses a plan.
It allocates nothing. Changing it does not make PostgreSQL use more or less RAM, and it does not resize any cache. If you set it to 100 GB on a machine with 8 GB of RAM, the server will start normally. It will simply make plans based on a false assumption.
Because it is only an estimate, changing it needs a reload, not a restart. It is also a normal user-level setting, so you can change it with SET in one session to test its effect on a plan.
How the planner uses the value
The planner compares the cost of plan alternatives. When it estimates an index scan, it must guess how many of the pages it touches will need a physical read and how many will already be cached. A larger effective_cache_size makes the planner assume more of the data is cached, so repeated page visits look cheaper.
The effect shows up mainly in these decisions:
- Index scan versus sequential scan. Index scans make many random page visits, so a high value makes them look cheaper.
- Index scan versus bitmap scan on medium-selectivity queries.
- The cost of the inner side of a nested loop that probes an index repeatedly. Many probes into the same index are more likely to hit cache.
It is compared against the size of the tables and indexes involved. If the value is small relative to a large index, the planner assumes the index will be read from disk often. If it is large, the planner assumes that index pages stay in cache.
The planner does not check whether the data is actually cached. It trusts the number you give it.
Choosing a starting value
The right value is the memory that PostgreSQL's data can realistically use for caching. That is roughly the RAM left over after the operating system, other programs, and per-query memory are accounted for, plus shared_buffers, which is already part of that RAM.
A common rule of thumb is 50 to 75 percent of total RAM on a machine dedicated to PostgreSQL. Treat it as a starting point and reason from the machine:
| Machine | Total RAM | shared_buffers | Starting effective_cache_size |
|---|---|---|---|
| Dedicated database server | 64 GB | 16 GB | 40 to 48 GB |
| Dedicated database server | 16 GB | 4 GB | 10 to 12 GB |
| Shared with an application | 16 GB | 4 GB | 6 to 8 GB |
| Container with 4 GB limit | 4 GB | 1 GB | 2 to 3 GB |
Do not add shared_buffers to the estimate again. The value already includes it. A common mistake is to compute "OS cache" from free memory and then set effective_cache_size to that number alone, which undercounts.
Memory used by many concurrent queries, by maintenance_work_mem, and by other services reduces what is available for caching. If those are large, lower the value.
Checking what the OS is using
On Linux, free shows how much memory is used for the page cache. Look at the buff/cache column.
free -hOn a busy, steady-state server, buff/cache plus shared_buffers gives a reasonable picture of what is available for caching data. This is an observation of current behavior, not a guarantee. After a restart or reboot, the cache is empty even though the setting is unchanged.
Containers and cgroups
Inside a container, free often reports the host's memory, not the container's limit. The page cache is charged to the container's memory cgroup, and it competes with the processes in that container. Base the value on the container limit, not on what free shows. Keep headroom, because the kernel reclaims cache when the limit is reached, and that shrinks the real cache below your estimate.
Reading and changing the setting
Use pg_settings to see the current value and how it can be changed.
SELECT name, setting, unit, context, source
FROM pg_settings
WHERE name IN ('effective_cache_size', 'shared_buffers');The setting column is in units of 8 kB blocks for these two parameters, and the unit column says so. Use SHOW for a readable value. The context for effective_cache_size is user, which means any session can change it.
To change it for the whole server:
ALTER SYSTEM SET effective_cache_size = '12GB';
SELECT pg_reload_conf();
SHOW effective_cache_size;To test a plan in one session without touching the server configuration:
SET effective_cache_size = '2GB';
EXPLAIN SELECT * FROM orders WHERE customer_id = 42;
RESET effective_cache_size;Plain EXPLAIN is enough here, because only the planner's choice matters and you do not need to run the query.
Seeing the effect in a plan
The setting is easiest to understand by changing it and watching the plan. The example below builds a table with an indexed column that is only loosely correlated with the physical row order, so index scans touch many different pages.
CREATE TABLE cache_demo AS
SELECT g AS id,
(random() * 100000)::int AS key,
repeat('x', 200) AS payload
FROM generate_series(1, 500000) AS g;
CREATE INDEX cache_demo_key_idx ON cache_demo (key);
ANALYZE cache_demo;
SET effective_cache_size = '128kB';
EXPLAIN SELECT * FROM cache_demo WHERE key BETWEEN 1000 AND 3000;
SET effective_cache_size = '16GB';
EXPLAIN SELECT * FROM cache_demo WHERE key BETWEEN 1000 AND 3000;
RESET effective_cache_size;With the tiny value, the planner assumes almost nothing is cached. The estimated cost of the index-based plan goes up, and it may switch to a sequential scan. With the large value, the cost of the index-based plan goes down. The exact plan depends on your version, table size, and other settings, so compare the cost estimates in both outputs and not only the node names. If both runs choose the same plan, the query is not near the decision boundary, and this setting is not the lever.
Verifying the cache assumption
Because the planner trusts your number, you need to check that the assumption is reasonable. Two checks help.
First, look at buffer hits and reads in a real execution:
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM cache_demo WHERE key BETWEEN 1000 AND 3000;shared hit counts blocks found in shared_buffers. read counts blocks requested from the OS. Run the statement twice. If the second run shows far fewer reads and is much faster, the working set fits in cache.
Second, enable track_io_timing to see time spent on reads. This setting adds a small timing overhead on some platforms, so test it before enabling it everywhere.
SET track_io_timing = on;
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM cache_demo WHERE key BETWEEN 1000 AND 3000;The plan then includes I/O Timings lines. A block counted as read that took microseconds came from the OS page cache. One that took milliseconds came from the disk. This is the only practical way inside PostgreSQL to tell the two apart. The pg_buffercache extension shows only shared_buffers contents, not the OS cache.
Common errors
- Setting it as if it were an allocation. It reserves nothing. Raising it does not use more RAM and does not speed up queries by itself. It only changes plan choices.
- Setting it to total RAM or more. The OS, connections, and maintenance operations need memory. The planner will then choose plans that assume everything is cached, and they can be slow when it is not.
- Leaving the default. The default is small, 4 GB in recent versions, and older versions used less. On a large machine, the planner will underestimate the cache and may avoid useful index scans.
- Adding shared_buffers on top. The value already includes it.
- Tuning it in isolation. If
random_page_costis wrong for your storage, a bettereffective_cache_sizewill not fix plan choices. Treat the two together, as a later chapter explains. - Expecting it to change a plan that is not close to a tipping point. If a plan is wrong because statistics are stale, run
ANALYZEfirst. - Ignoring cold cache. After a restart, real caching is far below the setting until the workload warms the cache. Plans stay the same, but performance can be poor for a while.
Summary of the working model
shared_buffersis a real allocation.effective_cache_sizeis a number the planner believes.- The value should cover
shared_buffersplus the OS cache that PostgreSQL data can realistically use. - It changes plan costs, mostly for index-heavy plans. It needs only a reload.
- Confirm the assumption with
EXPLAIN (ANALYZE, BUFFERS)and I/O timings, and not with theblks_hitratio alone.
Exercise
A dedicated PostgreSQL server has 32 GB of RAM and sharedbuffers = 8 GB. A colleague sets effectivecache_size = 8GB + 20GB = 28GB, reasoning that 20 GB of RAM is free for the OS cache. Another colleague says this double-counts memory. Who is right, and what is a sensible starting value?
Show answer
Neither adjustment is quite right. The setting already includes sharedbuffers, so it should be the total cache-capable memory, not sharedbuffers plus the OS cache computed separately from a free-memory figure. If 20 GB is the OS page cache seen in steady state, then the cache available for data is about 20 GB plus the part of shared_buffers not duplicated in it, so a value near 20 to 24 GB is sensible. The usual 50 to 75 percent rule gives 16 to 24 GB for a 32 GB machine. A starting value of about 22GB is reasonable, then verify with EXPLAIN (ANALYZE, BUFFERS).
Exercise
You run EXPLAIN (ANALYZE, BUFFERS) twice on the same query and the second run shows read=0 and is ten times faster. Does this show that effectivecachesize is set correctly?
Show answer
No. It shows that this query's working set is cached, either in sharedbuffers or the OS page cache. effectivecache_size is only the planner's estimate, so it is correct only if it is consistent with how much memory is realistically available to cache all the data your workload uses, not one query.
Exercise
Why does changing effectivecachesize not require a restart, and why can it change a query plan without changing memory use?
Show answer
It is a planner parameter with context user, so the server only reads it when planning a query and it needs no shared memory allocated at startup. It feeds into the cost estimates for page fetches, so a different value can produce a different cheapest plan, but PostgreSQL never allocates memory based on it.