Sub topic 1
Where PostgreSQL uses memory
Prerequisites
This chapter assumes you can run queries in psql, edit postgresql.conf, reload or restart the server, and read a simple EXPLAIN plan. You should also know roughly how much RAM and disk your server has.
Where PostgreSQL uses memory
PostgreSQL uses two kinds of memory. Shared memory is allocated once at startup and used by all backend processes. The main shared area is shared_buffers, which caches table and index pages. Per-process memory is allocated separately by each backend and by each operation inside a query. The main per-process settings are work_mem, used by sorts and hash operations, and maintenance_work_mem, used by VACUUM and CREATE INDEX.
The operating system also caches disk files in its page cache. PostgreSQL does not allocate that cache, but it depends on it.
Measuring before tuning: statistics views, EXPLAIN, and logs
Measure current behavior before you change anything. The pg_stat_database view shows how often reads hit shared_buffers:
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();EXPLAIN (ANALYZE, BUFFERS) shows whether a sort fit in memory. A line that reads Sort Method: external merge Disk: means the sort spilled to disk. Setting log_temp_files = 0 in postgresql.conf logs every temporary file, so spills appear in the server log.
Sizing shared_buffers
On a dedicated server, a common starting point is about 25% of RAM. Check the current value:
SELECT name, setting, unit, context
FROM pg_settings
WHERE name = 'shared_buffers';The context column shows postmaster, which means a full restart is needed to change the value.
effective_cache_size and the OS page cache
effective_cache_size does not allocate memory. It tells the planner how much data it can expect to find in cache, including the OS page cache. A common starting point is 50% to 75% of RAM. Because this is only a planner hint, a reload is enough to apply a change.
Exercise
Exercise
On a dedicated 16 GB server, what is a reasonable starting value for sharedbuffers, and what does the context column of pgsettings tell you about applying it?
Show answer
About 4 GB (25% of RAM). A context value of postmaster means the change requires a full server restart.