Why PostgreSQL memory settings decide both speed and stability
Memory settings decide whether a self-hosted PostgreSQL server is fast and stable, and they should be checked after the workload is measured, not guessed from a template. When a server is slow or running out of memory, the first question is which operations are using memory and how many run at once. The main controls are shared_buffers, which sets the server's own cache of table and index pages, work_mem, which sets memory for each sort or hash step inside a query, maintenance_work_mem, which covers maintenance jobs such as VACUUM and index builds, hash_mem_multiplier, which scales the memory a hash operation may use relative to work_mem, and effective_cache_size, which tells the planner how much memory the operating system is likely to use for caching. Each one does a different job, so changing one without the others often moves the problem rather than solving it.
These settings matter most in three situations: new hardware, a new or changed workload, and a major version upgrade. Hardware changes alter the memory available to the database and to the operating system cache. A new workload, such as a reporting query or a batch job, can introduce sorts and hashes that the previous configuration never had to handle. An upgrade is a good point to review settings against the release notes for the version you are moving to, and to confirm the defaults that the new version ships with. Before changing anything, record the current values, the host's total memory, the number of concurrent connections and the queries that spill to disk. Confirm the exact behavior for your version in the PostgreSQL documentation and in your own benchmarks.
PostgreSQL is released under the PostgreSQL License, a liberal open source license similar to the BSD or MIT licenses, so the memory settings described here are available to any team without license cost. They are configuration, not a feature that changes the storage format. Adjusting them does not require a dump and restore, and a change to most of them needs only a configuration reload or, for shared_buffers, a server restart. Because the total memory used by a server is the sum of many per-operation allocations, the risk of an out-of-memory event grows with the number of concurrent sessions. Plan these values against your connection limits and pooling design, and confirm the risk with a load test before production use.
Which memory setting fits which symptom
This table maps common memory symptoms to the PostgreSQL setting that addresses each one, what raising it costs, and what to confirm before changing it. Read each row against your own measurements, because a symptom can have more than one cause and the fix is often a different setting than the one that looks closest.
| Setting | What it controls | When to raise it | Main risk of raising it | What to confirm |
|---|---|---|---|---|
| shared_buffers | PostgreSQL's own cache of table and index pages, allocated once at server start | Hot working set is larger than cache and reads keep hitting the operating system or disk | Memory competes with the OS page cache and with every other process on the host | Current value, host RAM, and whether cache hit ratios are low under real load |
| work_mem | Memory per sort or hash operation inside one query node, not per connection | Sorts or hashes spill to temporary files, visible in EXPLAIN ANALYZE as external sort or batches | Multiplied by concurrent sessions and by nodes per query, so total use can exceed RAM under load | Peak concurrent queries, typical spill size, and whether high values are set only for specific roles or sessions |
| hash_mem_multiplier | Scales the memory hash-based nodes may use relative to work_mem | Hash joins or hash aggregates spill while sorts do not, and you want hashes to get more memory | Raises memory use for hash nodes only, so concurrency risk rises with the multiplier | Which plan nodes spill in EXPLAIN output and whether the change helps those specific queries |
| maintenance_work_mem | Memory for VACUUM, CREATE INDEX, ALTER TABLE and similar maintenance operations | Index builds or vacuum on large tables run slowly or repeatedly rescan | Maintenance jobs can run in parallel with busy workloads and consume RAM at the same time | How many maintenance operations can overlap and when autovacuum workers run |
| effective_cache_size | A planner estimate of memory available for caching, including the OS cache; it does not allocate memory | The planner picks sequential scans or poor join orders although indexes would be cheaper | Overstating it can favor index scans that miss the cache, so plans look cheap but run slowly | Actual free and cached memory on the host, excluding other services that share it |
| Total memory budget | The combined demand of all settings across connections, workers and the OS | Before any individual setting is raised, to confirm headroom | Ignoring the budget is the usual route to out-of-memory events under concurrency | Connection count, pooler settings, other services on the host, and container memory limits |
How the right values differ for OLTP, reporting and mixed workloads
Transactional workloads run many short queries, often through an application pool, with each query touching a few rows through indexes. Memory pressure comes mainly from the number of connections rather than from any single large operation, so the settings that matter most are max_connections, work_mem and the cache-related values. Because most sorts and hashes are small, a generous work_mem multiplied by many concurrent sessions is the usual route to memory exhaustion.
- Connection count sets the ceiling: Each active session can use
work_memfor each sort or hash node in its plan, so the worst case grows with the number of busy sessions, not with the setting alone. - Keep
work_memmodest: Many OLTP teams leave the global default in place and raise it only for specific roles or sessions that run heavier queries. - Pool connections before raising limits: A pooler such as PgBouncer keeps the number of server backends low, which protects memory more reliably than raising
max_connections. shared_buffersis shared: It is allocated once and serves all sessions, so it is the setting least affected by concurrency.- Watch temporary file use: Spills to disk in OLTP usually point to a plan problem, not a memory shortage, so check the query before increasing memory.
Before changing values, measure peak active connections, per-query temporary file counts and the memory use of the server under the busiest hour of load.",
Reporting workloads run fewer queries that scan large tables, aggregate, join and sort big result sets. Each of these operations can use a large share of work_mem, and the time spent spilling to disk can dominate the query. The settings that matter most are work_mem for the session that runs the report, hash_mem_multiplier for hash-based joins and aggregates, and maintenance_work_mem for index builds and vacuum.
- Raise memory per session, not globally: Setting a larger
work_memfor the reporting role or a specific job limits the risk to the sessions that need it. - Account for hash multipliers:
hash_mem_multiplierlets hash operations use more memory than sorts, which can change plan behavior and should be tested against real queries. - Plan for parallel workers: Parallel query can multiply memory use, since each worker may hold its own sort or hash space, so a report that runs in parallel needs a different budget from one that runs serially.
- Size
maintenance_work_memfor index builds: Index creation and vacuum benefit from more memory, and reporting teams often schedule them alongside loads. - Scheduling matters: Running several large reports at once can exhaust memory even when each one fits on its own.
Before changing values, run representative reports with EXPLAIN (ANALYZE, BUFFERS) and note which nodes report temporary file use, then confirm that the server's total memory holds at the expected number of concurrent reports.",
Many servers run transactions and reports on the same instance, which is common in smaller organizations and in systems where a reporting job shares the production database. The difficulty is that one set of global values must serve both patterns. Settings that suit a report can starve a transactional spike, and settings tuned for many connections can leave reports spilling to disk. The main decision is how much to isolate the two workloads, either by role, by schedule or by moving reports to a replica.
- Set global defaults conservatively: Use modest defaults so that the transactional side stays within a safe memory budget at peak connections.
- Override per role or job: Apply higher
work_memonly to reporting roles or to the sessions that run reports, using role-level settings. - Separate by schedule or host: Running reports at off-peak hours or on a streaming replica reduces the interaction, though replicas need their own sizing.
- Model the worst overlap: Calculate the memory need when the busiest transactional hour and a heavy report run together, not each workload alone.
- Track contention in both directions: Look for both lock waits and temporary file spills, since an oversized report can slow transactions through shared memory and I/O.
Before changing values, record peak concurrent sessions, the longest reporting jobs and their temporary file use, and test the combined load with a benchmark that mirrors both patterns.
How to set memory parameters without causing out-of-memory failures
This sequence sets PostgreSQL memory from the host's actual headroom outward, so each change is justified by measured spills or cache behavior and the server stays within RAM under concurrent load.
Confirm version, host memory and neighbors
Record the PostgreSQL major and minor version, total and available RAM, swap configuration, and every other service on the same host, such as application servers, connection poolers, monitoring agents or a container runtime. Run
SELECT version();andSHOW shared_buffers;, then check the host with your usual memory tools. The step is done when you have a written memory budget: RAM minus the operating system and co-located services is the pool PostgreSQL may use. Confirm the figures with your platform team if the host is shared.Capture a baseline of spills and slow queries
Before changing any memory setting, collect the evidence. Enable pg_stat_statements if it is not already loaded, then rank statements by total time. Run the slowest statements under
EXPLAIN (ANALYZE, BUFFERS)and look forSort Method: external mergeorBatchesgreater than 1 in hash nodes, which show work spilling to temporary files. Also note thetemp_filesandtemp_bytescounters inpg_stat_database. The step is done when you have a saved list of queries, their plans and the spill counters, so you can compare after the change.Set shared_buffers and effective_cache_size first
Set
shared_buffersas a fixed share of the memory budget from step one, then seteffective_cache_sizeto an estimate of memory available for disk cache across the database and the operating system.effective_cache_sizeallocates nothing; it only informs the planner. Changingshared_buffersrequires a restart, so batch it with other restart-bound changes. The step is done whenSHOW shared_buffers;andSHOW effective_cache_size;return the new values after restart andpg_settingsshows the source as the configuration file.Raise work_mem only where plans spill
Do not raise
work_memglobally. It applies per sort or hash node in each query, and one query can use several multiples of it, so concurrent sessions multiply the cost. Instead, set a higher value for the specific role, database or session that runs the spilling query, for example withALTER ROLE reporting_user SET work_mem = '...';orSET work_meminside the session. Considerhash_mem_multiplierfor hash-heavy workloads, since it scales hash memory without raising sort memory. The step is done when the baseline plans no longer show external sorts or multi-batch hashes, and the change is scoped to named roles.Set maintenance_work_mem for index builds and vacuum
Set
maintenance_work_memfor maintenance operations such asCREATE INDEX,REINDEX,ALTER TABLEadding foreign keys andVACUUM. These run less often than queries, so a larger value is usually safer than a largerwork_mem, but autovacuum workers can each use it, so multiply byautovacuum_max_workersin your budget. Setautovacuum_work_memseparately if autovacuum needs its own cap. The step is done whenSHOW maintenance_work_mem;reflects the change and a testCREATE INDEXon a copy of a large table completes without a temporary file warning in the logs.Reload or restart according to each parameter
Check each parameter's context in
pg_settings.work_mem,maintenance_work_memandeffective_cache_sizecan be applied with a configuration reload usingSELECT pg_reload_conf();, whileshared_buffersneeds a restart. Apply the restart in a planned window on a standby or after a failover test if you run replication. The step is done whenpg_settingsshowspending_restartfalse for every changed parameter and the server has come back healthy with the expected values.Verify with the same queries and monitoring
Rerun the baseline queries under
EXPLAIN (ANALYZE, BUFFERS)and compare plans, timings and spill counters with the saved baseline. Watch host memory and swap under peak concurrency, and check the PostgreSQL logs for out-of-memory messages or killed backends. Confirm thattemp_filesgrowth has slowed inpg_stat_database. The step is done when the target queries no longer spill, host memory stays within the budget from step one at peak load, and you have written the final values and the reason for each into your configuration record.
A query's memory comes from a shared pool and from per-operation allowances
The diagram follows one query from the client connection into the backend process. The planner chooses a sort and a hash join, and each of those operations draws its own work_mem allowance from the backend's private memory. Data pages are read through the shared_buffers pool and the operating system page cache. When a sort or hash exceeds its allowance, it spills to temporary files on disk. The planner setting effective_cache_size appears only as an estimate, because it allocates no memory.
Per-operation work_mem allowances, shared buffers, and temporary file spill paths.
Why concurrency turns a safe work_mem value into an out-of-memory risk
A work_mem value that looks safe for one session can exhaust host memory once many sessions run complex queries at the same time. The cards below cover how PostgreSQL multiplies that setting, how pooling and the operating system limit the damage, and how to watch for spills before they become failures.
work_mem applies per operation
The work_mem setting is a limit for each sort or hash operation, not for each session or each query. A single connection running a query with a sort, a hash join and an aggregate can use several multiples of that value. Multiply that by the number of active connections and the worst case can exceed the memory the host has. Before raising work_mem, calculate the worst case from your connection count and the number of memory-hungry operations in your heaviest queries.
Continuous archiving docsComplex queries run several operations at once
A query plan can contain more than one sort or hash node, and each one can allocate up to work_mem. Nested subqueries, large joins and window functions make this more likely. Parallel query workers each get their own allocation as well. Use EXPLAIN ANALYZE on your top queries to count the sort and hash nodes, then size work_mem for the plan with the most of them, not for the simplest query.
Pooling limits concurrency
The number of active connections is the multiplier that matters most, so a connection pooler such as PgBouncer is one of the main controls. Limiting the number of server connections caps how many operations can hold memory at the same moment. Confirm your pool sizes against the memory budget, and check whether your application opens more connections than it needs during traffic spikes.
PgBouncer siteThe OS OOM killer is a host risk
When Linux runs out of memory, the kernel's out-of-memory killer may terminate a PostgreSQL backend or the postmaster itself. The result is a crash-recovery cycle that affects every connection, not only the query that caused the spike. Account for shared_buffers, the work_mem worst case, maintenance operations and other services on the same host. Discuss with your platform team how the host reports and handles memory pressure before you go live.
Spilling to disk or failing
When an operation needs more memory than work_mem allows, PostgreSQL writes intermediate data to temporary files on disk instead of failing. That protects the host but slows the query, and heavy spilling adds disk I/O under load. Lowering work_mem trades memory safety for more spills, while raising it trades disk pressure for memory risk. Decide which failure mode you prefer for each workload and set limits to match, rather than assuming one setting fits every role.
Monitor temporary file growth
Temporary file activity is visible in the statistics views and the log, and sustained growth is an early sign that work_mem is too low for a query pattern. Track the number and size of temporary files per database over time and log the statements that create them using log_temp_files. Compare these figures with memory usage on the host before changing any value, so each change is backed by evidence from your own workload.
Questions teams ask before tuning PostgreSQL memory
How much work is it to tune PostgreSQL memory settings?
The effort depends less on the number of settings and more on how many workloads, hosts and environments the tuning has to cover. Changing shared_buffers, work_mem and effective_cache_size on one host with a steady workload is a small job. The effort grows when the database serves mixed reporting and transactional traffic, runs on several hosts, or has a history of out-of-memory events that must be traced. Each change also needs a measurement before and after, so the work includes reading plans, watching memory use under concurrency and repeating tests. Ask any partner to split the work into analysis, changes and verification so you can see where the time goes.
Can our own team tune PostgreSQL memory without a partner?
Yes, if your team has someone who can read EXPLAIN output, interpret host memory metrics and test changes in a controlled environment. The settings themselves are documented in the PostgreSQL manual, so the harder part is the evidence: knowing which queries spill to disk, how many sessions run at once and how the operating system is using memory. Teams without that skill often change a value, see a short improvement and then hit an out-of-memory condition under peak load. A partner can cover the analysis and test plan, or review yours, while your staff keep ownership of production changes.
What do we need to provide before tuning starts?
Plan to provide four things: representative workload samples, host details, a test environment and access to monitoring. Workload samples mean the queries and their frequency, including batch jobs, reports and connection patterns at peak times. Host details cover total RAM, other services sharing the machine, the operating system version and the storage type. A test environment that resembles production lets you change settings without risking live data. Monitoring history, such as memory use, swap activity and temporary file volume, shows how the server behaves over time. Confirm the exact list with the partner against your own environment before work starts.
How long does one memory tuning cycle take?
No duration can be given in general because it depends on the workload, the number of environments and how change control works in your organization. A cycle has a baseline measurement, a set of changes, a test run and a review. A stable workload with a test environment moves quickly through these steps. A workload with batch windows, peak traffic that only appears at month end, or a change process that requires approval for each restart will take longer, because some tests can only run during a particular window. Ask for the expected number of cycles, the test windows needed and the approvals required, then build the calendar from those.
What drives the cost of a memory tuning engagement?
Cost follows the scope agreed in writing. The main components are the analysis of your workload and hosts, the number of changes and test cycles, the number of database servers and environments, and the work to set up or repeat tests. Costs recur when workloads grow or when the settings must be reviewed after a major upgrade. Ask whether the quote covers a one-time tuning pass, a documented baseline you can maintain, or ongoing review. DeployOpen does not publish a price list, so the quote comes from the written scope.
What should a quote for PostgreSQL memory tuning include?
A useful quote names the systems in scope, the workloads to be analyzed, the hosts and environments where changes are made, and the test method. It should list the deliverables, such as a settings record with reasons for each value, a before-and-after measurement report, and a runbook for changing settings later. It should state what the client must provide, the test environment and the change window assumptions. Check whether the quote covers retesting after a PostgreSQL minor or major upgrade, and whether it includes support if a memory setting causes an incident. Ask how changes are approved and who holds the production change.
Which memory settings can cause out-of-memory errors under concurrency?
The main risk is that work_mem applies per sort or hash operation, not per connection, so a query with several such operations across many sessions can multiply the memory it uses. Raising shared_buffers or work_mem without checking the concurrent session count can push the host into swapping or the kernel's out-of-memory handling. effective_cache_size does not allocate memory, but a wrong value can lead the planner to choose plans that perform badly. Check the connection limit, the number of active sessions at peak, and the memory left for the operating system and other services before raising any value. Confirm the behavior of your PostgreSQL version against the PostgreSQL documentation for upgrade-related changes.
Should we tune memory before or after a PostgreSQL upgrade?
Tune the settings on the version you will run in production, because planner behavior and some defaults can change between major releases. If an upgrade is planned, measure before the upgrade so you have a baseline, then repeat the measurements on the target version in a test environment. This avoids attributing a plan change to a memory setting when it came from the new release. Plan the tuning cycle as part of the upgrade calendar, and confirm the supported version dates in the PostgreSQL versioning policy before you choose a target.
How DeployOpen works on this
DeployOpen treats PostgreSQL memory settings as part of the wider server build, not a one-off edit to postgresql.conf. We scope the work against your hardware, workload and concurrency targets, then build, test and document the settings so your own team can review and operate them.
How we scope
- Written scope covers host memory, PostgreSQL version, workload profile and current pain points before any setting changes
- Inventory of shared_buffers, work_mem, hash_mem_multiplier, maintenance_work_mem and effective_cache_size against your host and connection counts
- Fixed-scope engagements agree deliverables and timelines in writing before work starts, with a quote following from that scope
How we build
- Baseline measurements of memory use, temporary file activity and query plans taken before any value is changed
- Candidate settings applied in a staging environment and load tested against a workload that mirrors production traffic
- Per-role and per-session overrides designed for reporting or batch jobs so global work_mem stays conservative
How we hand over
- Documented rationale for each memory setting, with the formula, the measured inputs and the limits that were tested
- Monitoring checks and alert thresholds for memory pressure, temporary file spills and out-of-memory events
- Runbook covering how to change values safely, validate them after a restart and roll back if concurrency rises
How we support
- Ongoing support, upgrades and continuous testing are available as retainers after handover
- Re-review of memory settings after PostgreSQL minor or major upgrades, hardware changes or new workloads
- Retesting of settings when connection counts or query patterns change, with a written summary of each change

