PostgreSQL memory settings: shared_buffers, work_mem and effective_cache_size

Memory settings decide how PostgreSQL uses RAM for caching, sorts, hashes and maintenance, and the wrong values cause either slow queries or out-of-memory failures under concurrency. This page explains how to set them for your hardware and workload.

On this page

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.

SettingWhat it controlsWhen to raise itMain risk of raising itWhat to confirm
shared_buffersPostgreSQL's own cache of table and index pages, allocated once at server startHot working set is larger than cache and reads keep hitting the operating system or diskMemory competes with the OS page cache and with every other process on the hostCurrent value, host RAM, and whether cache hit ratios are low under real load
work_memMemory per sort or hash operation inside one query node, not per connectionSorts or hashes spill to temporary files, visible in EXPLAIN ANALYZE as external sort or batchesMultiplied by concurrent sessions and by nodes per query, so total use can exceed RAM under loadPeak concurrent queries, typical spill size, and whether high values are set only for specific roles or sessions
hash_mem_multiplierScales the memory hash-based nodes may use relative to work_memHash joins or hash aggregates spill while sorts do not, and you want hashes to get more memoryRaises memory use for hash nodes only, so concurrency risk rises with the multiplierWhich plan nodes spill in EXPLAIN output and whether the change helps those specific queries
maintenance_work_memMemory for VACUUM, CREATE INDEX, ALTER TABLE and similar maintenance operationsIndex builds or vacuum on large tables run slowly or repeatedly rescanMaintenance jobs can run in parallel with busy workloads and consume RAM at the same timeHow many maintenance operations can overlap and when autovacuum workers run
effective_cache_sizeA planner estimate of memory available for caching, including the OS cache; it does not allocate memoryThe planner picks sequential scans or poor join orders although indexes would be cheaperOverstating it can favor index scans that miss the cache, so plans look cheap but run slowlyActual free and cached memory on the host, excluding other services that share it
Total memory budgetThe combined demand of all settings across connections, workers and the OSBefore any individual setting is raised, to confirm headroomIgnoring the budget is the usual route to out-of-memory events under concurrencyConnection 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_mem for 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_mem modest: 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_buffers is 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.",

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.

  1. 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(); and SHOW 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.

  2. 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 for Sort Method: external merge or Batches greater than 1 in hash nodes, which show work spilling to temporary files. Also note the temp_files and temp_bytes counters in pg_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.

  3. Set shared_buffers and effective_cache_size first

    Set shared_buffers as a fixed share of the memory budget from step one, then set effective_cache_size to an estimate of memory available for disk cache across the database and the operating system. effective_cache_size allocates nothing; it only informs the planner. Changing shared_buffers requires a restart, so batch it with other restart-bound changes. The step is done when SHOW shared_buffers; and SHOW effective_cache_size; return the new values after restart and pg_settings shows the source as the configuration file.

  4. Raise work_mem only where plans spill

    Do not raise work_mem globally. 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 with ALTER ROLE reporting_user SET work_mem = '...'; or SET work_mem inside the session. Consider hash_mem_multiplier for 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.

  5. Set maintenance_work_mem for index builds and vacuum

    Set maintenance_work_mem for maintenance operations such as CREATE INDEX, REINDEX, ALTER TABLE adding foreign keys and VACUUM. These run less often than queries, so a larger value is usually safer than a larger work_mem, but autovacuum workers can each use it, so multiply by autovacuum_max_workers in your budget. Set autovacuum_work_mem separately if autovacuum needs its own cap. The step is done when SHOW maintenance_work_mem; reflects the change and a test CREATE INDEX on a copy of a large table completes without a temporary file warning in the logs.

  6. Reload or restart according to each parameter

    Check each parameter's context in pg_settings. work_mem, maintenance_work_mem and effective_cache_size can be applied with a configuration reload using SELECT pg_reload_conf();, while shared_buffers needs 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 when pg_settings shows pending_restart false for every changed parameter and the server has come back healthy with the expected values.

  7. 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 that temp_files growth has slowed in pg_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 docs

Complex 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 site

The 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

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.