Video in progress
How does PostgreSQL use memory: how are `shared_buffers` and the OS page cache related, and how much do you set `shared_buffers` to?
shared_buffers is PostgreSQL's own page cache, shared by all processes. On top of that, files are also cached by the OS page cache, so the same data can sit in two places. The usual starting value is about 25% of RAM, leaving the rest for the OS cache.
📖 Answer
PostgreSQL does reads with an ordinary read() (it doesn't use direct I/O), so:
- if the page is in
shared_buffers, it's the fastest, a "hit"; - if not, it asks the OS; if it's in the OS page cache, it still doesn't go to disk;
- if it's in neither, it's a real disk read.
read= in EXPLAIN (ANALYZE, BUFFERS) shows pages that came from the OS, but it doesn't distinguish whether they came from disk or from the OS cache.
For a server with 64 GB of RAM, here is how I start:
shared_buffers = 16GB
effective_cache_size = 48GB # a hint for the planner, doesn't allocate memory
work_mem = 32MB
maintenance_work_mem = 1GB
Why not make shared_buffers 80%? Because the OS cache is needed too, the data would be stored twice, and a very large shared_buffers leads to a lot of dirty pages being written at checkpoint time. For some workloads 40% works better, and you have to check that with a load test.
I look at how well the cache is working in pg_stat_database: blks_hit / (blks_hit + blks_read). On an OLTP database this should be around 99%. If it drops to 90%, the working data set doesn't fit in memory, or some query is reading a big table in full.
Sign up to mark studied questions and save your progress.