Fix PostgreSQL HV001: FDW Out of Memory Error
In this article
HV001 means the PostgreSQL server ran out of memory while executing a query through a foreign data wrapper (FDW). Most often the culprit is postgres_fdw or a similar wrapper trying to pull an entire remote result set onto the local node, or joining large remote tables with no pushdown, so the working set blows past what the server can hold. The fix is not a single switch: you usually need to free memory quickly, find the query that triggered it, then shrink the fetch and reduce how much the server keeps in memory at once. If a single query already killed the connection, start at Step 1 and work down in order.
What You'll Need
- A PostgreSQL account with at least read access to
pg_stat_activityandpg_settings, plus rights to editpostgresql.conforALTER SYSTEM(a superuser or a role granted those privileges). - A client tool such as
psql, pgAdmin, or any GUI that can run SQL and show server error logs. - Access to the server log file, which is where the full HV001 message with the failing SQL statement lands.
- Knowledge of which foreign server the query touches, so you can find the FDW's options and the foreign tables involved.
Step-by-Step
Get the full error text from the log. The client often shows only "out of memory". Open the server log and search for
HV001orforeign data wrapper. You want theDETAIL,CONTEXT, and the failing statement. That statement is the one to fix, and the log line shows whether the failure was in the local backend or in the remote connection.Confirm it is not ordinary server exhaustion. Run
SELECT version();and checkSELECT name, setting, unit FROM pg_settings WHERE name IN ('work_mem','shared_buffers','max_connections','maintenance_work_mem');. Ifwork_memis tiny ormax_connectionsis very high relative to RAM, you may simply be running out of memory across all backends, not through the FDW specifically. Note the values before changing anything.Free memory immediately. Look at
SELECT pid, usename, state, query FROM pg_stat_activity WHERE state <> 'idle';and cancel the runaway statement withSELECT pg_cancel_backend(pid);. Only usepg_terminate_backend(pid)if cancel does not take. Cancelling is safe; terminating rolls back the session's work. If memory is still pinned by idle-in-transaction sessions, terminate those specifically, since an open transaction can hold a large result.Update the PostgreSQL minor version. FDW memory handling has had real bugs over the years. Make sure you are on the latest minor release of your major version. Minor upgrades are safe and do not require a data dump, but they do need a server restart. Check the release notes for your version and follow the upgrade procedure for your install method.
Make the FDW push work down. The single biggest cause of HV001 is a remote join or filter that runs locally. Check the plan with
EXPLAIN (VERBOSE) SELECT ...;and look for aForeign Scanthat has no pushed-downWHEREclause and returns millions of rows. Rewrite so filters and joins can be sent to the remote server: keep the query simple enough thatpostgres_fdwcan push it, and make sure the FDW version supports the constructs you use.Shrink
fetch_size. Forpostgres_fdw, reduce how many rows are fetched per round trip. Set it for the session first:SET fetch_size = 1000;then rerun the query. If that helps, persist it on the server or table:ALTER SERVER my_remote OPTIONS (ADD fetch_size '1000');orALTER FOREIGN TABLE my_table OPTIONS (ADD fetch_size '1000');. Smaller fetches use less transient memory but take longer, so tune down until HV001 stops and stay above a few hundred if speed matters.Raise
work_memonly where it is safe. If the plan shows a sort or hash spilling and failing, a largerwork_memfor that session can help:SET work_mem = '64MB';Do not raise it globally to a big number, because it is per operation per backend and can push the whole server into swap. Prefer a session-level or role-level setting.Break the query into pieces. If a single FDW query will always be too large, split it. Create a temporary table from the filtered remote subset, analyze it, then join locally. Or move the aggregation to the remote server so the local side receives only summarized rows. This is often the most reliable permanent fix.
Check for an FDW that is not
postgres_fdw. Other wrappers (for example CSV, file-based, or API wrappers) may buffer entire results in memory and may not supportfetch_size. Read that extension's documentation for its own memory or batch options, and upgrade it to a current version.Monitor and retest under load. After changes, rerun the query, then repeat with a few concurrent sessions if that matches production. Watch
pg_stat_activityand the operating system's memory during the run. If it still fails, capture the new log entry and go back to step 5.
Common Mistakes
- Raising
work_memglobally. It multiplies across every active query and can make the server worse, not better. - Using
pg_terminate_backendfirst. Cancelling is gentler and preserves more context for diagnosis. - Assuming the error is a bug. HV001 is a resource condition; most reports are a plan that pulls far too much data locally.
- Forgetting that
fetch_sizecan be set at server, table, and session level, with the more specific setting winning. - Overlooking idle-in-transaction sessions, which keep old snapshots and memory alive long after a query finished.
- Changing settings only in the current session and expecting them to survive a reconnect. Use
ALTER SYSTEMorALTER SERVERto persist, then reload.
Tips
- Test tuning changes in a session with
SETbefore persisting them; it is instantly reversible. - Add narrow filters to remote queries so the network transfer shrinks along with memory use.
- Match pushdown to what the wrapper can actually do in your version; a build without the right capability silently runs work locally.
- Keep foreign tables' column statistics current so the planner chooses a smaller plan; run
ANALYZEon the foreign table if your setup supports it. - Log slow statements so the next HV001 is caught before a user hits it.
- When you change
postgresql.conf, remember most memory settings need a reload or restart depending on the parameter.
Troubleshooting
If the error returns even after reducing fetch_size, look at the query plan again: a remote scan returning a large fraction of an unindexed table points at missing indexes on the remote side. Confirm the remote database has usable indexes for your filter and join columns.
If memory still climbs during the run and the operating system starts swapping, the server is genuinely short of RAM for the current concurrency. Lower max_connections or put a connection pooler in front, then retune. A pooling layer also stops idle sessions from holding memory.
If only some sessions fail, compare their role settings: a role-level work_mem or fetch_size override may be the difference. Query pg_settings and the role inheritance to see the effective values.
If the failure happens right after a restart or a minor upgrade, confirm the extension is loaded from the expected version with SELECT * FROM pg_extension WHERE extname = 'postgres_fdw'; and reload configuration. A stale extension binary mismatched to the server is a real cause of odd wrapper failures.
Frequently Asked Questions
Is HV001 a PostgreSQL crash?
No. It is a query-level error raised when the foreign data wrapper or its surrounding query exceeds available memory. The server keeps running unless the operating system's out-of-memory killer intervenes.
Will increasing work_mem always fix HV001?
No. If the query is fetching an enormous remote result, more per-operation memory just delays the failure or worsens total memory pressure. Reduce the data first, then tune memory.
Does fetch_size work with every FDW?
No. It is a postgres_fdw setting. Other wrappers use their own options or buffer everything, so check the specific extension's documentation.
Can I fix HV001 without restarting the server?
Often yes. Session-level SET fetch_size and SET work_mem take effect immediately. Persistent settings need a reload, and some need a restart.
Where do I find the statement that failed?
In the server log, under the HV001 entry's context or statement field. The client-side message alone usually omits it.