Skip to content

Shared Buffers and Memory

This page explains what shared_buffers holds, how Managed PostgreSQL sizes it from a percentage of the service memory, and how it competes for that memory with work_mem and connections.

What shared_buffers Holds

shared_buffers is PostgreSQL’s own cache of table and index pages, in 8 kB blocks. It is one block of shared memory, allocated when the server starts and used by every session, so its size does not depend on the number of connections.

It is not the only cache. Pages not found in shared_buffers are read through the operating system, whose page cache uses the memory PostgreSQL leaves free. A page missing from shared_buffers is therefore often still served from memory. Giving shared_buffers a larger share moves memory from one cache to the other and takes it away from sessions.

How the Size Is Set

You do not set shared_buffers directly: the service derives it from a percentage of its RAM, so the value follows the plan when you change it.

FlagRangeDefault
--pg-shared-buffers-percentage20 to 60, whole numbers20% when not set

On a hobbyist-2 service, with 2 GiB of RAM, 20% gives 390MB and 40% gives 781MB:

SHOW shared_buffers;

Change it with:

exo dbaas update SERVICE_NAME -z ZONE -f --pg-shared-buffers-percentage 30

Parameters:

  • SERVICE_NAME: name of the Managed PostgreSQL service, for example my-postgresql.
  • ZONE: zone the service runs in, for example ch-gva-2.

A value outside the range is rejected with should be an Integer between 20 60. Read the stored value back with:

exo api get-dbaas-service-pg SERVICE_NAME -z ZONE -q '"shared-buffers-percentage"'

It returns null while the flag has never been set.

Important

shared_buffers only changes when PostgreSQL starts, so changing the percentage restarts the service: connections are dropped and refused for a short time. Do it in a maintenance window and make sure the clients reconnect. See Maintenance windows.

Is It Large Enough?

The share of table reads served from shared_buffers, since statistics were last reset:

SELECT sum(heap_blks_read) AS heap_read,
       sum(heap_blks_hit)  AS heap_hit,
       round(100.0 * sum(heap_blks_hit)
             / nullif(sum(heap_blks_hit) + sum(heap_blks_read), 0), 2) AS hit_pct
FROM pg_statio_user_tables;

heap_blks_read counts blocks fetched from outside shared_buffers, which includes blocks served by the operating system cache. Read the figure over time and alongside query latency rather than against a fixed target:

  • On a new or rarely used service the figure means little; wait for a representative workload.
  • If it drops when the data grows, while the plan stays the same, the frequently used data no longer fits. A higher percentage can help, in steps, measured each time.
  • If it stays low at 40% or more, the data the workload uses does not fit in this plan’s memory, and a plan with more RAM is the fix. See Change the service plan.

For a single statement, EXPLAIN (ANALYZE, BUFFERS) reports Buffers: shared hit=... read=... on each plan node.

To see which relations occupy the cache, create pg_buffercache, which avnadmin can use:

CREATE EXTENSION IF NOT EXISTS pg_buffercache;

SELECT c.relname,
       pg_size_pretty(count(*) * 8192) AS cached,
       round(100.0 * count(*)
             / (SELECT setting::bigint FROM pg_settings WHERE name = 'shared_buffers'), 1) AS pct_of_cache
FROM pg_buffercache b
JOIN pg_class c ON b.relfilenode = pg_relation_filenode(c.oid)
JOIN pg_database d ON d.oid = b.reldatabase AND d.datname = current_database()
WHERE c.oid >= 16384
GROUP BY c.relname
ORDER BY count(*) DESC
LIMIT 10;

The c.oid >= 16384 condition leaves out the system catalogs. pg_buffercache_summary() gives the number of used, unused and dirty buffers in one row.

After a restart the cache is empty. pg_prewarm, also available to avnadmin, loads a relation into it ahead of the traffic and returns the number of blocks read:

CREATE EXTENSION IF NOT EXISTS pg_prewarm;
SELECT pg_prewarm('public.customers');

Loading more than fits in shared_buffers only evicts what was loaded first.

What Else Needs the Memory

Memory given to shared_buffers is not available for:

  • the server process of each connection;
  • work_mem, used per sort or hash operation, in each backend and each parallel worker;
  • maintenance_work_mem, used by VACUUM, index builds and autovacuum workers;
  • PgBouncer and the platform’s monitoring, backup and failover processes;
  • the operating system page cache.

This is why a percentage well above 40 rarely improves anything.

The Interaction with work_mem

work_mem multiplies where shared_buffers does not. A query with three sort or hash nodes, run by a leader and two parallel workers, can allocate nine times work_mem; twenty such queries at once, 180 times. Read the value in force with SHOW work_mem;. The service-wide default is set with --pg-work-mem, in MB, from 1 to 1024, and is 1 MB plus 0.075% of the RAM, capped at 32 MB, when not set. Before raising it, multiply it by your realistic concurrency and compare the result with the memory left after shared_buffers.

Prefer raising it where it is needed:

BEGIN;
SET LOCAL work_mem = '64MB';
-- the statement that sorts or hashes a large result
COMMIT;

SET LOCAL lasts until the end of the transaction. ALTER ROLE ... SET work_mem applies to every new session of a role. See Optimize slow queries.

When Memory Runs Out

When the operating system runs out of memory, it kills a process. If that process is a PostgreSQL backend, PostgreSQL ends every other connection and goes through crash recovery before it accepts connections again. A high shared_buffers percentage, a raised work_mem and many concurrent connections can each be reasonable on their own and exhaust the memory together.

Reduce the pressure before adding memory:

  1. Route clients through a connection pool, so that the number of active backends stays bounded.
  2. Fix the queries that sort or hash large results; an index that removes a sort saves memory.
  3. Drop unused indexes and data, which shrinks what needs to be cached.
  4. Then adjust the parameters, or move to a plan with more RAM.

Related Pages

Last updated on