Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

PostgreSQL Error 53200: Fix Out of Memory Fast

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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 SYSTEM or edit access to postgresql.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; and SHOW max_connections;.
  • Connection details for a monitoring view, since pg_stat_activity and pg_stat_statements are how you find the culprit query.

Step-by-Step

  1. 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.
  2. Check the host is not actually out of memory. Run free -m and dmesg | 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 check ulimit -a for the postgres user: a low max locked memory or address space limit can produce 53200 even when free RAM exists.
  3. Look at concurrency first. Run SELECT count(*), state FROM pg_stat_activity GROUP BY state;. Each active session can consume several times work_mem because a query may have multiple sort or hash nodes, each allowed its own allocation. Twenty active sessions on a 4 GB box with work_mem = 64MB can therefore exhaust memory without any single query being unreasonable.
  4. Find the expensive query. Enable pg_stat_statements (it loads via shared_preload_libraries and requires a restart) and sort by temp_blks_written or by mean execution time. A query spilling gigabytes to temp files is a prime 53200 candidate. Also check pg_stat_activity for long-running queries and their query text while the error is happening.
  5. Reproduce with EXPLAIN. Run EXPLAIN (ANALYZE, BUFFERS) on the suspect query in a session where you have set a low work_mem (for example SET 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. Run ANALYZE on the involved tables and re-check.
  6. Reduce the allocation the query asks for. Common fixes: add a supporting index so a sort disappears, add a LIMIT, remove unnecessary DISTINCT or ORDER BY, break a giant IN list into a join against a temp table, or replace array_agg over millions of rows with pagination. This is almost always better than raising memory limits.
  7. 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_mem accordingly (globally modest, larger per-session for known heavy reports). Lower maintenance_work_mem if the error happens during CREATE INDEX or VACUUM. Keep shared_buffers at a fraction of RAM rather than the majority.
  8. Cap connections. If max_connections is high and clients use connection pools badly, insert a pooler such as PgBouncer in transaction mode and reduce max_connections. Fewer simultaneous backends means each gets more headroom.
  9. Apply changes and reload. Use ALTER SYSTEM SET work_mem = '8MB'; followed by SELECT pg_reload_conf(); for settings that do not need a restart. Verify with SHOW work_mem; in a fresh session. Settings changed via ALTER SYSTEM persist across restarts.
  10. Confirm the fix. Re-run the failing operation, watch the log for new 53200 entries, and monitor pg_stat_activity under 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.