PostgreSQL Error 53200: Fix Out of Memory Fast
In this article
Error 53200 means PostgreSQL could not allocate memory for a backend process, and the fix is to free memory pressure first — find what is consuming shared memory, temp files or per-connection work memory — then tune the settings that govern it. The message usually reads ERROR: out of memory with a detail line such as Failed on request of size ... bytes, and the server keeps running; only the failing query dies. This guide walks through diagnosis and the concrete configuration changes that resolve it.
Most occurrences fall into three buckets: a single query asking for an enormous allocation (huge sort, hash join or array build), many concurrent sessions each holding work memory, or the host genuinely running out of RAM or swap. You need to identify which before changing anything, because raising work_mem blindly often makes things worse.
What You'll Need
- Superuser or a role with permission to read server logs and change configuration (
ALTER SYSTEMor edit access topostgresql.conf). - Access to the PostgreSQL log file, and ideally the full error line with the request size and the query text.
- A shell on the database host (or the container) to check RAM, swap and OS limits.
- The output of
SHOW work_mem;,SHOW maintenance_work_mem;,SHOW shared_buffers;andSHOW max_connections;. - Connection details for a monitoring view, since
pg_stat_activityandpg_stat_statementsare how you find the culprit query.
Step-by-Step
- Capture the full error. Find the exact log line. PostgreSQL logs the request size, for example
Failed on request of size 1048576 in memory context "TupleSort main". The memory context name is the single most useful clue: TupleSort points at sorting, Hash at hash joins or aggregates, ExecutorState at the plan itself, dynahash at hash tables. Note it before you change anything. - Check the host is not actually out of memory. Run
free -manddmesg | grep -i oom. If the kernel OOM killer has been terminating postgres processes, this is a host sizing problem, not a PostgreSQL tuning problem. Also checkulimit -afor the postgres user: a lowmax locked memoryor address space limit can produce 53200 even when free RAM exists. - Look at concurrency first. Run
SELECT count(*), state FROM pg_stat_activity GROUP BY state;. Each active session can consume several timeswork_membecause a query may have multiple sort or hash nodes, each allowed its own allocation. Twenty active sessions on a 4 GB box withwork_mem = 64MBcan therefore exhaust memory without any single query being unreasonable. - Find the expensive query. Enable
pg_stat_statements(it loads viashared_preload_librariesand requires a restart) and sort bytemp_blks_writtenor by mean execution time. A query spilling gigabytes to temp files is a prime 53200 candidate. Also checkpg_stat_activityfor long-running queries and theirquerytext while the error is happening. - Reproduce with EXPLAIN. Run
EXPLAIN (ANALYZE, BUFFERS)on the suspect query in a session where you have set a lowwork_mem(for exampleSET work_mem = '4MB';) so it spills instead of crashing. Look for sort or hash nodes estimating far more rows than actual, which signals stale statistics. RunANALYZEon the involved tables and re-check. - Reduce the allocation the query asks for. Common fixes: add a supporting index so a sort disappears, add a
LIMIT, remove unnecessaryDISTINCTorORDER BY, break a giantINlist into a join against a temp table, or replacearray_aggover millions of rows with pagination. This is almost always better than raising memory limits. - Set memory limits sensibly. If tuning is needed, calculate a budget: total RAM minus OS and other services, then divide by expected concurrent active sessions and the number of nodes per query. Set
work_memaccordingly (globally modest, larger per-session for known heavy reports). Lowermaintenance_work_memif the error happens duringCREATE INDEXorVACUUM. Keepshared_buffersat a fraction of RAM rather than the majority. - Cap connections. If
max_connectionsis high and clients use connection pools badly, insert a pooler such as PgBouncer in transaction mode and reducemax_connections. Fewer simultaneous backends means each gets more headroom. - Apply changes and reload. Use
ALTER SYSTEM SET work_mem = '8MB';followed bySELECT pg_reload_conf();for settings that do not need a restart. Verify withSHOW work_mem;in a fresh session. Settings changed viaALTER SYSTEMpersist across restarts. - Confirm the fix. Re-run the failing operation, watch the log for new 53200 entries, and monitor
pg_stat_activityunder normal load. If temp file usage drops, the pressure is resolved.
Common Mistakes
Raising work_mem globally to fix one query. It multiplies by session count and by nodes per query, so the server can crash harder. Prefer a per-role or per-database override for the reporting workload.
Ignoring the request size. A request of several gigabytes usually means a query pattern change is needed, not a bigger limit.
Blaming PostgreSQL for a host problem. If the kernel OOM killer fired or the container has a low memory cgroup limit, no postgres setting will help until the host or limit is fixed.
Assuming the error is a permissions issue. 53200 is a resource error, not an access error, even though it appears next to the admin-shutdown codes.
Forgetting ulimits. A restrictive ulimit -v can cause 53200 on a machine with plenty of free RAM.
Skipping ANALYZE after bulk loads. Stale statistics push the planner into oversized hash tables.
Tips
Name the workload in the log using application_name so you can tell which service triggered the error. Turn on log_temp_files to record any query spilling temp files above a threshold — those queries are your early warning system. For analytics workloads, consider a separate read replica with generous memory rather than inflating settings on the transactional primary. Keep a small swap file as a safety net on Linux, but do not treat swap as capacity. Wrap heavy reports in a transaction that sets SET LOCAL work_mem, so the setting disappears when the transaction ends.
Troubleshooting
The error returns immediately after the fix. Check whether the client reconnects with the same query. Confirm SHOW work_mem; in the actual session — a pooler or role-level setting may override your global change.
The error happens only at peak hours. That points to concurrency. Count active sessions during the spike and lower max_connections or add pooling.
Errors during index rebuilds or VACUUM. Lower maintenance_work_mem and run the operation during quiet hours; large builds need memory per operation, not per connection.
Container deployments. Check the cgroup memory limit; PostgreSQL inside a container sees host RAM but is killed at the container limit. Set shared_buffers and work_mem against the container limit, not the host total.
A specific function or extension fails. Some extensions allocate large blocks internally. Check the extension documentation for its own memory settings rather than only tuning core parameters.
Frequently Asked Questions
Does error 53200 mean my database is corrupted?
No. It is a failed memory allocation for one backend. Data integrity is not affected, and the server continues serving other sessions.
Should I just reboot the server?
A restart clears memory pressure temporarily, but the error recurs unless the query pattern or configuration is fixed. Use it only to recover service, then diagnose.
Is 53200 the same as an out-of-shared-memory error?
The class covers memory allocation failures generally. Check the detail line: it names the memory context and the size requested, which tells you whether it is shared memory, work memory or an OS limit.
Why does it appear right after a restore or bulk import?
Restores often run large sorts and index builds with stale statistics. Run ANALYZE after the import and lower maintenance_work_mem if the build phase failed.
Can I set different memory limits per user?
Yes. ALTER ROLE reporting SET work_mem = '64MB'; applies only to that role's sessions, which keeps interactive traffic on a modest global default.
Which setting is most often responsible?
work_mem combined with high concurrency, followed by maintenance_work_mem during index maintenance and shared_buffers sized too close to total RAM.