dataiotech Labs
Back to Performance Guide
[PostgreSQL]RUNBOOKPostgreSQL 16 / 1725 minSenior DBA / SRE

[PostgreSQL] RUNBOOK: Memory Tuning — shared_buffers, work_mem, effective_cache_size

PostgreSQL memory architecture divides RAM between shared memory and per-operation client memory. Improper work_mem allocation triggers OOM killer events under concurrent load.

Production Incident Scenario

A 32GB RAM server runs with default 128MB shared_buffers. Cache hit ratio hovers at 82%, forcing heavy disk I/O. Sort operations spill to disk. The team suggests upgrading hardware, but parameter balancing resolves the issue.

Overview and Memory Architecture

The majority of database performance regressions do not originate from hardware deficiencies; they stem from improperly balanced memory allocations.

If shared_buffers is undersized, queries constantly thrash physical disk storage. If work_mem is too small, complex sort and hash join operations spill onto disk as temporary files. Conversely, if work_mem is over-allocated, a sudden concurrency surge of 100 connections executing multi-step joins will exhaust host RAM, triggering the Linux Out-Of-Memory (OOM) killer to terminate the PostgreSQL postmaster process.

In this operational runbook, you will learn how to configure the 4 core memory parameters: `shared_buffers`, `work_mem`, `maintenance_work_mem`, and `effective_cache_size`. For each setting, you will find empirical sizing formulas, diagnostic queries, safe deployment steps, and verification procedures.


Scenario

The Default 128 MB Trap. An enterprise host is provisioned with 32 GB of RAM and 8 CPU cores. PostgreSQL was installed with default distribution settings.

The engineering team reports severe performance degradation during business hours. The DBA inspects SHOW shared_buffers; and uncovers the reality:

shared_buffers = 128MB

Out of 32 GB of physical RAM, PostgreSQL was restricted to a microscopic 128 MB buffer cache. Every query was forced to read pages from disk. The database cache hit ratio hovered at a miserable 82%. Sorting operations continuously spilled to disk.

The management reflex was to double server RAM from 32 GB to 64 GB. However, scaling hardware on misconfigured software merely provides an expensive 64 GB server still constrained by a 128 MB cache. A properly balanced 32 GB instance runs significantly faster than an improperly configured 64 GB host.


The Dual-Layer Memory Architecture: Shared vs Local

PostgreSQL partitions RAM into two primary structures:

▸1. Shared Memory

Allocated once when the PostgreSQL cluster starts and shared across every connected backend process.

  • •`shared_buffers`: The database cache holding table and index data pages.
  • •WAL Buffers: Staging memory for Write-Ahead Log entries before flushing to disk.

▸2. Per-Process / Per-Operation Memory (Local Memory)

Allocated independently by individual backend processes on demand.

  • •`work_mem`: Allocated per sort, hash join, or aggregation node. A single complex query with 4 joins and 2 sorts can allocate 6x `work_mem` simultaneously.
  • •`maintenance_work_mem`: Allocated by maintenance utilities such as VACUUM, CREATE INDEX, and ALTER TABLE ADD FOREIGN KEY.

Step 0: Baseline Audit

Before altering any configuration files, record current host metrics and PostgreSQL parameters:

sql
SHOW shared_buffers; SHOW work_mem; SHOW maintenance_work_mem; SHOW effective_cache_size; SHOW max_connections; SHOW autovacuum_max_workers;

Inspect host resources from the Linux terminal:

bash
free -h nproc cat /proc/sys/vm/overcommit_memory

Document your baseline:

  • •Host RAM: 32 GB
  • •CPU Cores: 8
  • •Active max_connections: 100
  • •Initial shared_buffers: 128 MB

Step 1: Tuning shared_buffers (The Dedicated Cache)

▸Purpose

shared_buffers represents PostgreSQL's primary data cache. When a backend query reads a table page, it checks shared_buffers first. Reading from RAM is approximately 100 times faster than reading from NVMe storage.

▸The 25% Baseline Formula

📐 Formül:\text{shared\_buffers} = \text{Total System RAM} \times 0.25
Total Host RAMRecommended shared_buffers
8 GB2 GB
16 GB4 GB
32 GB8 GB
64 GB16 GB
128 GB32 GB

▸Why 25% and Not 80%? (The Double Buffering Dilemma)

Unlike database engines that bypass the host OS using Direct I/O, PostgreSQL relies intentionally on the Linux Kernel Page Cache.

When PostgreSQL reads a page from disk, that page is cached in the operating system's page cache *and* in PostgreSQL's shared_buffers. If you allocate 80% of RAM to shared_buffers, the operating system page cache is starved, causing cache duplication and inefficient eviction algorithms. A 25% allocation achieves the optimal equilibrium between PostgreSQL's internal cache and the kernel cache across production workloads.

▸Telemetry: Evaluating Cache Hit Ratio

sql
SELECT datname, blks_hit, blks_read, round(100.0 * blks_hit / NULLIF(blks_hit + blks_read, 0), 2) AS cache_hit_ratio_pct FROM pg_stat_database WHERE datname = current_database();

Standard: An OLTP workload should maintain a cache_hit_ratio_pct of 99% or higher. If this value is below 95%, shared_buffers is undersized or unindexed sequential scans are flushing the cache.


Step 2: Tuning effective_cache_size (Planner Costing)

▸Purpose

effective_cache_size does not allocate memory. It is purely an informational heuristic provided to the query planner. It tells the cost optimizer how much total memory (PostgreSQL shared_buffers + OS Page Cache) is likely available to hold table pages.

▸Sizing Formula

📐 Formül:\text{effective\_cache\_size} = \text{Total System RAM} \times 0.75
  • •On a 32 GB host: effective_cache_size = 24GB.
  • •On a 64 GB host: effective_cache_size = 48GB.

▸Planner Impact

If effective_cache_size is set too low (e.g., the default 4 GB), the planner assumes requested data resides on slow physical disk. It penalizes Index Scan paths due to expected random I/O and favors brute-force Seq Scan operations. Setting it to 75% of RAM encourages the planner to select faster index scans for medium-to-large result sets.


Step 3: Tuning work_mem (Per-Operation Allocation)

▸Purpose

work_mem dictates the maximum amount of RAM an individual query node may allocate for sorting (ORDER BY, DISTINCT), Hash Joins, and aggregations before spilling data into temporary disk files.

▸The Multiplier Risk

work_mem is not allocated per connection; it is allocated per operation node within a query plan. If a single complex query contains 3 Hash Joins and 2 Sorts, it can allocate $5 \times \text{work\_mem}$.

If you have 100 concurrent connections, the theoretical maximum memory consumption is:

📐 Formül:\text{Max Potential RAM} = \text{max\_connections} \times (\text{work\_mem} \times 2)

▸Safe OLTP Sizing Formula

📐 Formül:\text{work\_mem} = \frac{\text{Total RAM} - \text{shared\_buffers}}{\text{max\_connections} \times 3}

On a 32 GB host with 100 active connections: $$\frac{32\text{GB} - 8\text{GB}}{100 \times 3} = \frac{24,000\text{MB}}{300} = 80\text{MB}$$

For high-concurrency OLTP, a safe global default is 16 MB to 32 MB.

▸Session-Level Overrides for Heavy Reporting

Never raise global work_mem to 512 MB to satisfy an occasional overnight batch export. Instead, configure large allocations dynamically at the session level:

sql
-- Set high work_mem exclusively within the reporting script SET work_mem = '256MB'; SELECT customer_id, count(*), sum(total) FROM orders GROUP BY customer_id ORDER BY sum(total) DESC; RESET work_mem;

▸Auditing Disk Spills (Temporary Files)

Verify whether current work_mem is causing disk spills:

sql
SELECT datname, temp_files, pg_size_pretty(temp_bytes) AS total_spill_size FROM pg_stat_database WHERE datname = current_database();

Step 4: Tuning maintenance_work_mem

▸Purpose

Allocates memory for database maintenance utilities:

  • •VACUUM and Autovacuum worker processes
  • •CREATE INDEX and REINDEX
  • •Adding foreign key constraints

▸Sizing Formula

📐 Formül:\text{maintenance\_work\_mem} = \min\left(\text{Total RAM} \times 0.05, 2\text{GB}\right)
  • •On a 32 GB server: 1 GB to 2 GB.
  • •Setting maintenance_work_mem = 2GB dramatically accelerates index creation and allows VACUUM to hold larger lists of dead tuple pointers before flushing.

Step 5: Applying Changes Safely

  1. 1Parameters requiring database restart (`shared_buffers`):

Update postgresql.conf or use ALTER SYSTEM:

sql
ALTER SYSTEM SET shared_buffers = '8GB';

Restart during an approved maintenance window.

  1. 1Parameters reloadable without restart (`work_mem`, `effective_cache_size`, `maintenance_work_mem`):
sql
ALTER SYSTEM SET effective_cache_size = '24GB'; ALTER SYSTEM SET work_mem = '32MB'; ALTER SYSTEM SET maintenance_work_mem = '1GB'; SELECT pg_reload_conf();

Protecting the Instance from Linux OOM Killer

Ensure Linux does not over-commit memory indiscriminately:

bash
# /etc/sysctl.conf vm.overcommit_memory = 2 vm.overcommit_ratio = 80

Setting vm.overcommit_memory = 2 prevents the kernel from granting more memory than physically exists, eliminating spontaneous OOM crashes.


Operational Checklist

  • Total host RAM, CPU cores, and connection limits recorded
  • Current shared_buffers, work_mem, and effective_cache_size documented
  • Database cache hit ratio measured
  • Temporary file disk volume and frequencies audited
  • shared_buffers set according to the 25% RAM formula
  • effective_cache_size set to 75% of total RAM
  • work_mem calculated conservatively factoring concurrency multipliers
  • work_mem tested at session level for analytical reports
  • maintenance_work_mem configured for vacuum and index operations
  • Settings requiring restart scheduled during maintenance window
  • Cache hit ratio re-measured 1 hour post-restart
  • Top expensive queries audited 24 hours post-change
  • OOM killer events and swap space usage verified
  • Unproductive configuration changes reverted safely

Related Guides in Series

  • •Pillar: Performance & Query Optimization
  • •Cluster: Finding Top 20 Expensive Queries with pg_stat_statements
  • •Cluster: The N+1 Query Problem and Connection Pool Saturation
  • •Cluster: Reading and Deconstructing EXPLAIN ANALYZE
  • •Cluster: Vacuum, Analyze, and Autovacuum Tuning
  • •Cluster: 5-Minute Lock Diagnostics via pg_locks and pg_stat_activity
Operational Checklist

Verify each operational safety check before completing the task: