Sub topic 6
Giving hash operations more memory with hash_mem_multiplier
This chapter assumes you know what work_mem does, that you can read Sort Method lines in EXPLAIN (ANALYZE) output, and that you can change a setting at the session, role, or server level. The previous chapter covered work_mem and temporary-file spills. This one covers the setting that lets hash-based operations use more memory than sorts do.
Why a separate limit for hashes
work_mem is the memory budget for one sort or hash node in a query plan. A sort and a hash table respond differently when that budget is too small.
- A sort that does not fit spills to disk and finishes with an external merge. The cost rises gradually as the data grows past the limit.
- A hash table that does not fit is split into batches. Rows are written to temporary files and processed in several passes. A hash join that falls from one batch to many can slow down sharply, because both sides of the join may be written out and read back.
Raising work_mem to rescue hash operations also raises the limit for every sort in every session. hash_mem_multiplier fixes this by scaling only the hash limit. The effective limit for a hash-based node is:
hash memory limit = work_mem * hash_mem_multiplierWith work_mem = 64MB and hash_mem_multiplier = 2.0, a sort can use 64 MB and a hash table can use 128 MB.
What counts as a hash operation
The multiplier applies to nodes that build an in-memory hash table:
- Hash joins (the
Hashnode under aHash Join) - Hash aggregation (
HashAggregate, used forGROUP BYandDISTINCT) - Hashed
INorNOT INsubplans Memoizenodes (PostgreSQL 14 and later), which cache the results of parameterized inner scans
Sorts, GroupAggregate, merge joins, and index builds ignore the multiplier. Index builds use maintenance_work_mem.
Version history and defaults
The default depends on your server version, so check it before reasoning about your own system.
| Version | Behavior |
|---|---|
| 12 and earlier | The setting does not exist. Hash joins are limited by `work_mem`. A hash aggregate can exceed `work_mem` because it cannot spill. |
| 13 and 14 | The setting exists with a default of `1.0`. Hash aggregation can spill to disk. |
| 15 and later | The default is `2.0`. |
Hash aggregation spilling in version 13 matters here. Before that, the planner avoided hash aggregation when it expected the table to be larger than memory, partly because the executor could not stay within the limit. Since version 13, the planner can choose a hash aggregate and spill. The multiplier lets such a plan stay in memory.
Checking the current value
The setting can be changed in a session, so context is user. No restart or reload is needed for a session-level change.
SELECT name, setting, unit, context, min_val, max_val
FROM pg_settings
WHERE name IN ('work_mem', 'hash_mem_multiplier');The allowed range is 1.0 to 1000.0. A value of 1.0 makes hash and sort limits equal.
Recognizing a hash that needs more memory
A hash join in EXPLAIN (ANALYZE) reports batches on its Hash node. A hash aggregate reports batches and, if it spilled, disk usage. The following example builds a test table and runs both kinds of query. The plan the planner chooses depends on your version and statistics, so read the plan you get rather than expecting a specific one.
CREATE TABLE sales AS
SELECT g AS id,
(random() * 500000)::int AS customer_id,
(random() * 100)::numeric(8,2) AS amount
FROM generate_series(1, 2000000) AS g;
CREATE TABLE customers AS
SELECT g AS customer_id, md5(g::text) AS name
FROM generate_series(0, 500000) AS g;
ANALYZE sales;
ANALYZE customers;
SET work_mem = '4MB';
SET hash_mem_multiplier = 1.0;
EXPLAIN (ANALYZE, BUFFERS)
SELECT c.name, sum(s.amount)
FROM sales AS s
JOIN customers AS c USING (customer_id)
GROUP BY c.name;In the output, look for lines like these:
Hash (... ) Buckets: 131072 Batches: 8 Memory Usage: 3900kBon a hash join.Batchesgreater than 1 means the hash table was split and spilled.HashAggregate ... Batches: 5 Memory Usage: 4145kB Disk Usage: 20000kBon a hash aggregate.Disk Usageappears only when it spilled.Temp readandwrittenin theBuffers:line, which show temporary file I/O.
Now repeat the query with a larger multiplier and compare:
SET hash_mem_multiplier = 8.0;
EXPLAIN (ANALYZE, BUFFERS)
SELECT c.name, sum(s.amount)
FROM sales AS s
JOIN customers AS c USING (customer_id)
GROUP BY c.name;With a hash limit of 32 MB, the Batches count on the join should drop, possibly to 1, and temporary reads and writes should shrink or disappear. The planner may also change the plan, because its cost estimates take the hash limit into account. Check both the plan shape and the timing.
Applying the setting
Choose the narrowest scope that fixes the problem. For one heavy report, change the setting inside a transaction:
BEGIN;
SET LOCAL hash_mem_multiplier = 4.0;
-- run the heavy query here
COMMIT;For a role that always runs analytical queries:
ALTER ROLE reporting SET hash_mem_multiplier = 4.0;For the whole server, use ALTER SYSTEM and reload. No restart is needed:
ALTER SYSTEM SET hash_mem_multiplier = 2.0;
SELECT pg_reload_conf();
SHOW hash_mem_multiplier;Role-level settings apply to new sessions only. An existing session keeps the value it started with.
Effect on your memory budget
The multiplier increases the worst case, so the budget from the earlier chapter changes. A plan with h hash nodes and s sort nodes can use up to:
h * (work_mem * hash_mem_multiplier) + s * work_memper process, and parallel query multiplies this again. For example, with work_mem = 64MB and hash_mem_multiplier = 4.0, a query with three hash nodes can use about 768 MB in one backend. With 50 concurrent sessions running such queries, that comes to about 38 GB.
Parallel queries need extra care. Each parallel worker is a separate process with its own allowance. With Parallel Hash, the workers share one hash table, which can grow to the combined allowance of the participating processes. In either case, a plan with several workers can use several times the memory of the same plan without parallelism.
Choosing a value
A practical order of operations:
- Find queries that spill. Set
log_temp_files = 0and checktemp_filesandtemp_bytesinpg_stat_database. - In
EXPLAIN (ANALYZE, BUFFERS), confirm that the spill is on aHashorHashAggregatenode and not on aSort. - If the spill is on a hash, raise
hash_mem_multiplierfor that session first. If the spill is on a sort, raisework_meminstead. - Increase in steps (2, 4, 8) until
Batches: 1or until the speedup stops. A hash table that is only slightly over the limit gains the most. - Move the working value to the narrowest persistent scope, such as a role.
The multiplier is not a fix for every slow hash join. If the estimated row count for the hash side is far too low, the planner may choose a poor plan regardless of the memory limit. Check the estimates with ANALYZE first.
Common mistakes
- Treating
work_memand the multiplier as separate budgets. The hash limit is derived fromwork_mem, so loweringwork_memalso lowers the hash limit. - Setting a very high value such as 100 on a shared server because a single query benefited. One query with several large hash nodes can then exhaust memory.
- Expecting any effect on sorts,
CREATE INDEX, orVACUUM. They ignore the multiplier. - Reading
Batches: 1on theHashnode as proof that the whole query avoided temporary files. A different node in the same plan may still spill, so check theBuffersline and the other nodes. - Comparing timings from a single run. The first run may read from disk and the second from cache, so repeat each run and compare
Buffersas well as time.
Exercise
A server runs PostgreSQL 16 with workmem = 16MB and the default hashmem_multiplier. A report query shows a HashAggregate with "Batches: 6" and a Sort with "Sort Method: quicksort Memory: 9000kB". You want to stop the spill without increasing memory for sorts. What do you change, to what, and at which scope? How much memory can each hash node now use?
Show answer
The default in version 15 and later is 2.0, so the hash limit is already 32MB and still spills. Raise hashmemmultiplier, for example to 4.0 (a 64MB hash limit), and leave work_mem alone because the sort fits in memory. Apply it with SET LOCAL inside the report's transaction, or with ALTER ROLE for the reporting role, instead of server-wide. Then rerun EXPLAIN (ANALYZE, BUFFERS) and check that Batches drops to 1 and the Disk Usage line disappears. Each hash node can now use up to 16MB x 4.0 = 64MB, while the sort limit stays at 16MB.