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 = 128MBOut 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, andALTER TABLE ADD FOREIGN KEY.
Step 0: Baseline Audit
Before altering any configuration files, record current host metrics and PostgreSQL parameters:
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:
free -h
nproc
cat /proc/sys/vm/overcommit_memoryDocument 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
| Total Host RAM | Recommended shared_buffers |
|---|---|
| 8 GB | 2 GB |
| 16 GB | 4 GB |
| 32 GB | 8 GB |
| 64 GB | 16 GB |
| 128 GB | 32 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
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
- •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:
▸Safe OLTP Sizing Formula
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:
-- 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:
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:
- •
VACUUMand Autovacuum worker processes - •
CREATE INDEXandREINDEX - •Adding foreign key constraints
▸Sizing Formula
- •On a 32 GB server: 1 GB to 2 GB.
- •Setting
maintenance_work_mem = 2GBdramatically accelerates index creation and allowsVACUUMto hold larger lists of dead tuple pointers before flushing.
Step 5: Applying Changes Safely
- 1Parameters requiring database restart (`shared_buffers`):
Update postgresql.conf or use ALTER SYSTEM:
ALTER SYSTEM SET shared_buffers = '8GB';Restart during an approved maintenance window.
- 1Parameters reloadable without restart (`work_mem`, `effective_cache_size`, `maintenance_work_mem`):
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:
# /etc/sysctl.conf
vm.overcommit_memory = 2
vm.overcommit_ratio = 80Setting 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, andeffective_cache_sizedocumented - Database cache hit ratio measured
- Temporary file disk volume and frequencies audited
shared_buffersset according to the 25% RAM formulaeffective_cache_sizeset to 75% of total RAMwork_memcalculated conservatively factoring concurrency multiplierswork_memtested at session level for analytical reportsmaintenance_work_memconfigured 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