PostgreSQL out-of-memory errors and the Linux OOM killer

PostgreSQL processes get killed when memory demand from work_mem, concurrency, overcommit or container limits exceeds what the host or cgroup allows. This page explains the causes, the settings that prevent the restart cycle and what to confirm before changing them.

On this page

Why PostgreSQL out-of-memory errors happen and when teams need to act

A PostgreSQL out-of-memory event usually means the operating system ended a process because the server ran out of memory or hit a strict limit, not that PostgreSQL itself failed. Either the Linux OOM killer selects a backend and sends it a kill signal, or the kernel refuses an allocation under strict overcommit and the backend fails. Clients see dropped connections, the postmaster logs that a child process terminated abnormally, and the database goes through crash recovery. The short answer for most teams is that the cause sits in memory settings combined with how many sessions run at once, so the fix starts with configuration review rather than with the query that happened to be running when the kill occurred.

PostgreSQL responds to an abnormal backend exit by assuming shared memory may be inconsistent. It terminates all other backends, replays WAL from the last checkpoint, and then accepts connections again. Applications see a burst of resets, in-flight transactions roll back, and any connection pool in front of the database must reconnect. A single kill can therefore produce a full restart of every session, which is why one event is worth investigating even when the database comes back on its own. Confirm in your own logs which process was terminated and whether the kernel or PostgreSQL reported it, because the remedy differs between the two.

Teams should review memory settings when kills or allocation failures recur, when they add connections or application workers, when they move the server into a container with a memory limit, or before a planned change to work_mem or max_connections. The review should confirm the overcommit mode, the memory available to the host or container, and the total memory a busy hour could claim, which is work_mem multiplied by the number of sort and hash operations running at once across all sessions. Confirm the exact behavior of your kernel version and container runtime with their own documentation, and treat any restart with unexplained memory pressure as a trigger for that review.

Memory settings and when each fits

This table compares the five settings that most affect PostgreSQL peak memory: work_mem, shared_buffers, maintenance_work_mem, max_connections and the connection pooler. Read each row as a lever, its effect on memory use, and the condition under which it is worth changing. The main takeaway is that per-operation settings multiply with concurrency, so the number of simultaneous sessions matters as much as the value you set.

SettingWhat it controlsEffect on peak memoryWhen to change it
work_memMemory each sort, hash or similar operation may use before spilling to diskApplies per operation, and one query can run several at once, so peak use is roughly this value multiplied by concurrent operations across all sessionsRaise it only for specific sessions or roles running known heavy reports, after confirming spills in query plans; avoid raising the global value on a busy server
shared_buffersPostgreSQL's own shared cache for table and index pagesAllocated once at startup as a fixed block that every backend shares, so it adds a stable baseline rather than growing with connectionsAdjust when measured cache hit ratios and workload justify it, and leave enough RAM for the operating system page cache and per-session memory
maintenance_work_memMemory for VACUUM, CREATE INDEX and similar maintenance commandsEach maintenance process can use this amount, and autovacuum workers may run several at once, so the total depends on autovacuum settingsIncrease for large index builds or vacuums run in a maintenance window; confirm how many autovacuum workers can run together before raising it
max_connectionsMaximum number of client sessions the server acceptsEach backend holds its own memory, and every session can use work_mem, so this is the multiplier behind most OOM incidentsLower it to match what the database can serve, and use a pooler to serve more application clients with fewer backends rather than raising the limit
Connection pooler (PgBouncer)Multiplexes many client connections onto a smaller set of server connectionsCaps the number of active backends, which bounds the concurrency that work_mem and per-session memory can reachAdd it when many application connections drive memory use, and size the pool with the database's available memory in mind; confirm pooling mode fits your application's session features
Operating system and containersPage cache, other processes and the memory limit enforced on the host or containerMemory limits here decide when the kernel or runtime kills processes, which can happen before PostgreSQL's own settings would limit useReview after any setting change, and confirm the limit leaves headroom for the sum of PostgreSQL's allocations and the operating system

How a killed backend leads to a postmaster restart cycle

The diagram starts with concurrent client queries allocating work_mem and other memory in separate backend processes. When the kernel OOM killer or a failed allocation selects one backend, that process dies abnormally. The postmaster then tells the other backends to terminate, so their client sessions drop, and it reinitializes shared memory before accepting connections again. Check the kernel log for the killed PID, then confirm which backends were interrupted before you blame the restart on the database itself.

Path from memory pressure to the postmaster restart cycle and client reconnects.

How to diagnose and stop OOM kills on a PostgreSQL host

This sequence finds out whether the Linux kernel or a container limit killed PostgreSQL, identifies which memory settings drove the demand, and produces a configuration that stays within the host's memory under a tested load.

  1. Confirm the kill in kernel and PostgreSQL logs

    The on-call engineer or DBA searches the kernel log (for example with journalctl -k or dmesg) for OOM killer entries and notes the victim process ID, its name and the memory figures recorded at the time. They then match that timestamp against the PostgreSQL server log, where a backend killed by SIGKILL typically shows the postmaster reporting that another server process exited abnormally and that the cluster is restarting. The step is complete when one kernel event and one PostgreSQL event line up in time and name the same process. If only PostgreSQL shows a crash with no kernel entry, treat the cause as something else, such as a segmentation fault, until proven otherwise.

  2. Check the overcommit mode and memory limits

    The sysadmin reads the kernel setting vm.overcommit_memory and the swap configuration on the host, then compares them with the total RAM available to PostgreSQL. In strict mode (value 2), the kernel refuses allocations beyond the commit limit, so failures appear as allocation errors instead of kills, which changes the symptoms the team should expect. In the default heuristic mode, the kernel allows more memory to be promised than physically exists and kills processes when the promise cannot be honored. The step is done when the team has written down the mode, the commit limit and the swap size, and knows which of the two behaviors the host shows. Confirm the intended mode with your platform owner before changing it, since other services on the same host share the setting.

  3. Review the postmaster OOM score adjustment

    The engineer inspects the OOM score adjustment on the postmaster process (the /proc entry for oom_score_adj) and on its child processes, and reviews how the service unit or init script starts PostgreSQL. A lower value makes the kernel less likely to pick a process, but applying it only to the postmaster does not protect the backends it forks, which inherit the setting at fork time and can still be chosen. Lowering the value on the postmaster also tends to shift the kill onto the largest backend, which is usually the query using the most work_mem. The step is complete when the team knows the current score for the postmaster and a backend, and has decided whether a protective setting is appropriate. Record the decision, because it changes which process the next kill will target.

  4. Measure work_mem use under concurrency

    The DBA estimates peak memory demand by multiplying work_mem by the number of sort and hash operations a single query can run, then by the number of sessions that might run such queries at once, and adds shared_buffers, maintenance_work_mem and per-connection overhead. Peak usage in the server log and in EXPLAIN ANALYZE output (look for sort or hash batches and disk spills) shows how often a query actually uses large amounts of memory. Connection counts from pg_stat_activity show how many sessions were active at the time of the kill. The step is done when the team has a worst-case figure for the host and can say which parameter contributes most. Because work_mem applies per operation, not per connection, the multiplication is the number to check first.

  5. Set container and cgroup limits to match

    If PostgreSQL runs in a container, a systemd slice or a Kubernetes pod, the platform engineer confirms the memory limit the runtime enforces and compares it with the worst-case figure from the previous step. A limit below that figure causes the cgroup to kill processes even when the host has free memory, and the kernel log entry names the cgroup rather than the host. The engineer then sets the limit with headroom for shared memory, the operating system and monitoring agents, and sets work_mem, max_connections and connection pooling so that the worst case fits inside that limit. The step is done when the limit, the configuration values and the calculated peak agree, and the change is recorded in version control or the deployment tool. Confirm with the vendor or distribution how the runtime reports the OOM event.

  6. Verify the fix with a controlled load test

    The team runs a load test in a staging environment that matches production memory settings, limits and data size. The test drives the concurrency level observed in production plus a documented margin, and includes the heaviest sort and hash queries identified earlier. The engineer watches kernel logs, the cgroup memory peak, the PostgreSQL log for temporary file messages and backend exits, and the restart count for the service. The step is complete when the test finishes without any OOM entries, without unexpected backend terminations, and with peak memory below the limit. Keep the test scripts and results so that the same check can run after each PostgreSQL minor upgrade or configuration change.

Bare metal, virtual machines and containers compared

On a dedicated host, the Linux kernel is the only memory authority. When physical memory and swap are exhausted, the kernel's out-of-memory killer chooses a victim using each process's badness score, which depends largely on its resident memory and its oom_score_adj value. The vm.overcommit_memory and vm.overcommit_ratio settings control how much memory the kernel promises to processes before they use it, so the host's commit policy determines whether allocations fail early or the kernel overcommits and kills later.

  • Overcommit mode: Mode 2 (strict accounting) refuses allocations beyond the commit limit, so PostgreSQL sees failed allocations instead of a later kill. Confirm the mode with sysctl vm.overcommit_memory before changing anything.
  • Score adjustment: The postmaster's oom_score_adj is inherited by its children, which is why the postmaster is usually protected and individual backends are the expected victims.
  • Swap policy: Decide whether swap exists and how much. Swap delays kills but can make latency worse, and it changes what a memory spike looks like in monitoring.
  • Other tenants: Check whether anything else runs on the host, such as backup agents, monitoring or application servers, since they compete for the same memory.
  • Kernel logs: Kill events appear in the kernel log, so confirm your team can read dmesg or the journal on the host.

Before changing any setting, confirm the current overcommit mode, swap size and the other workloads on the host with the team that administers it.

Operational risks to manage while changing memory settings

Tuning memory is a change to a production database, so the risks come from the change itself as much as from the original fault. The cards below cover restarts, crash recovery, monitoring gaps and the access controls on the logs and configuration you use to diagnose the problem.

Restarts needed to apply settings

Some memory settings, such as shared_buffers, only take effect after a server restart, while work_mem can usually be changed with a reload. Before editing any value, check its context in pg_settings and plan the restart window with the application owners. Confirm whether your connection pooler or application pools reconnect cleanly after a restart, because a restart that looks safe on the database can still produce a storm of failed requests upstream.

High availability docs

Crash recovery after a backend kill

When the kernel kills a backend, PostgreSQL assumes shared memory may be corrupted and restarts all backends, which rolls every active transaction back and replays WAL. Recovery time depends on how much WAL must be replayed since the last checkpoint, so a busy server can take noticeably longer to come back than a quiet one. Confirm that your WAL archive and backups are current before you test a memory change, since a failed restart is the moment you need them.

Monitoring gaps during tuning

Memory problems often appear as short gaps in logs rather than as clear errors, so a change can look successful when the kill has only moved elsewhere. Track the server log for lines about backends terminated by signal 9, record memory use per process and host, and watch swap activity during peak load. Set alerts on these signals before the change, not after, so that a regression is visible within the first busy period.

Access to logs and configuration

Diagnosing memory problems means reading server logs, postgresql.conf, systemd or container unit files and sometimes query text, all of which can expose sensitive data or credentials. Limit read access to the database host and logging pipeline, redact connection strings and bound parameter values where your logging setup allows, and record who changed each setting. Changes to these files should go through the same review and version control path as other production configuration.

Rollback path for each change

Each memory setting should have a documented previous value and a way to revert it without guessing. Change one parameter at a time, with the expected effect written down, so that a rollback removes one variable rather than several. Keep the rollback procedure in the same runbook as the change, and confirm who has permission to execute it outside business hours.

Questions buyers ask about PostgreSQL OOM problems

What drives the cost of fixing PostgreSQL out-of-memory kills?

The cost depends on how many environments share the problem, how many hosts and containers run PostgreSQL, and whether the fix stays limited to configuration or reaches application code and capacity planning. Diagnosis takes most of the effort: someone has to correlate kernel logs, PostgreSQL logs, query plans and connection counts over a period that includes peak load. A fixed-scope quote should list the environments covered, the number of database servers, whether application connection pools are in scope, whether container limits are changed, and whether a retest under load is included. Configuration changes are a small share of the work. Ask for each cost item to be listed separately so you can see what is one-time work and what recurs, such as a retainer for ongoing review after capacity changes.

How long does it take to diagnose a PostgreSQL OOM problem?

Diagnosis length depends mainly on how much evidence is available and how often the kills happen. A team with kernel log retention, PostgreSQL logs with connection and memory context, and monitoring of memory use can usually narrow the cause faster than a team that only sees a restart in the application log. Bare-metal or virtual machine hosts are often simpler to inspect than container platforms, where the memory limit, the cgroup accounting and the orchestrator restart policy all need to be read together. Intermittent kills that only occur during batch jobs or reporting peaks take longer, because the reproduction window is narrow. Ask any provider to state which evidence they need before starting and what they will do if the kills cannot be reproduced in a test environment.

What does the work need from our team?

The work needs access and context more than long hours from your engineers. Expect to provide read access to PostgreSQL and host logs, the kernel log for the period of the kills, the current values of work_mem, max_connections and shared_buffers, the application connection pool settings, and the deployment definitions for any container or orchestrator memory limits. Someone who knows the workload needs to explain the peak periods, the batch jobs and the queries that run at the same time. Your team also needs to approve changes to production settings and schedule a window for restarts, since many memory settings take effect only after a restart. Name one owner on each side so questions about evidence and approvals do not stall the work.

Can our own engineers fix PostgreSQL OOM problems without outside help?

Yes, many teams can, provided they have someone who can read kernel memory logs, PostgreSQL configuration and the application's connection behavior, and who can test changes before production. The main risk is not the configuration edit itself but changing one setting without accounting for its multiplier. A value of work_mem applies per sort or hash operation, so one query can use several multiples of it, and many concurrent sessions multiply that again. Strict overcommit settings and container memory limits can also change which process the kernel chooses to kill. If your team has no one with this experience, or if the same problem returns after a change, an outside review of the configuration and workload is a reasonable step. Ask the provider to show which parts they would hand over to your engineers for ongoing operation.

Will a fixed-scope OOM engagement include the application changes that cause the memory spikes?

Only if the written scope says so. Many OOM kills come from applications that open too many connections, run unbounded queries or hold transactions open, so the fix sometimes sits in application code or pool configuration rather than in PostgreSQL. A fixed-scope agreement should name which application components are in scope, which changes your team will make, and which ones are recommended but outside the work. DeployOpen plans and implements self-hosted open-source platforms in your infrastructure, so the scope can cover the database and its deployment configuration. Application code owned by your developers should be listed as a dependency with an owner and a date agreed before work starts.

What should we ask for in a quote for an OOM investigation?

Ask for a written scope that lists the environments, the PostgreSQL servers and host or container platforms covered, the logs and metrics you will review, and the changes that may be recommended or applied. Request a list of deliverables, such as a findings report, the revised configuration, the restart plan and a verification step under load. Ask how the work will confirm that the kills stopped, what evidence you will receive, and what happens if the cause is outside the agreed scope. Ask whether the quote includes a retest after the next peak period and whether ongoing monitoring of memory use is recurring work. Compare quotes on these items rather than on headline effort alone.

How do we know the fix will hold after the investigation ends?

Confidence comes from evidence collected under realistic load, not from a single configuration change. Ask for memory and connection metrics recorded before and after the change, for the period that includes your heaviest batch or reporting work. Ask how the fix handles future growth, including new reports, more application instances and larger data volumes, and which alerts will warn your team before memory use reaches a limit. Ask whether the restart cycle after a killed backend was tested, since a database that restarts cleanly under load is a different result from one that recovers only after manual steps. No provider can guarantee future workloads, so ask what the handover covers and what monitoring you will own.

What a DeployOpen memory review covers

A DeployOpen PostgreSQL memory review is scoped in writing before work starts, and it runs entirely inside infrastructure the client controls, including its cloud accounts, data centers or air-gapped networks. The first phase collects evidence: the kernel and PostgreSQL logs covering the killed backends, the postmaster and systemd unit definitions, the values of shared_buffers, work_mem, maintenance_work_mem, max_connections and vm.overcommit_memory on each host, and any container memory limits. The written scope should name which hosts, databases and time windows are covered, who grants access to logs, and whether the review includes connection pooler settings such as those in PgBouncer.

The second phase measures the workload rather than relying on configured limits. The review compares how many sessions run sorts, hashes and parallel workers at peak with the memory each one can claim, since work_mem applies per operation and not per connection. It also checks whether the OOM score of the postmaster is protected from the kernel and whether the restart cycle after a killed backend triggers crash recovery and a reconnect storm from the application. Client decisions at this stage include which peak period to measure, whether a staging copy with production-sized data is available, and who approves a temporary change to production settings.

The final phase is a written set of recommended changes, each with the expected effect, a rollback step and a test to confirm the result, followed by verification under a representative load. Expect the deliverable to list configuration changes, any container or host sizing adjustments, and alerting for memory pressure, with the open items the client must confirm in its own environment, such as the memory budget for each host and the change window. Ask any provider for the scope, deliverables and retest approach in writing, and for the assumptions about your hardware and workload that the quote depends on.

How DeployOpen scopes and supports PostgreSQL memory fixes

DeployOpen approaches PostgreSQL out-of-memory errors as a platform problem, covering the database settings, the host or container limits and the application connection patterns together. Work is scoped in writing, built inside your own infrastructure and handed over with documentation your operations team can run.

How we scope

  • Review current memory settings, host or container limits and kernel overcommit policy before proposing any change.
  • Map work_mem, max_connections and connection pool sizing against peak concurrency to show where memory can run out.
  • Agree the scope, deliverables and timeline in writing before work starts, since most engagements are fixed-scope.

How we build

  • Adjust memory settings and container limits in a staging copy of your cluster, then reproduce the load pattern that triggered the kill.
  • Set oom_score_adj and cgroup memory limits so the postmaster is protected and the failing backend is the one that stops.
  • Test the restart path after a backend is killed, confirming that shared memory recovery and client reconnects behave as expected.

How we hand over

  • Deliver a written configuration record with each memory setting, its reason and the workload it was sized for.
  • Provide alert thresholds and runbook steps for checking the kernel log and PostgreSQL log after an unexpected termination.
  • Walk your platform and database teams through the change set so they can review it against their own standards.

How we support

  • Offer ongoing support, upgrades and continuous testing as a retainer when your workload or PostgreSQL version changes.
  • Re-check memory sizing after major application releases, new reporting jobs or a move to a newer supported PostgreSQL version.
  • Confirm the support terms, response expectations and included retesting with your account lead before signing.

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.