ClickHouse memory limit exceeded: causes and fixes

Which query shapes blow through max_memory_usage, how to find them in system.query_log, and the setting or rewrite that fixes each, tested on ClickHouse 26.9.

The ClickHouse “Memory limit exceeded” error (code 241, MEMORY_LIMIT_EXCEEDED) means a query tried to allocate memory past one of three budgets: its own max_memory_usage, its user’s max_memory_usage_for_user, or the server-wide max_server_memory_usage. Which one fired is printed in the message, and it decides the fix. The query shapes behind it are few. ClickHouse’s knowledge-base article names “large joins or aggregations on high cardinality fields”, and in practice a big ORDER BY with no LIMIT is the third. Each holds state in RAM that grows with the data rather than with the result. Every query in this guide ran on ClickHouse 26.9 against a 40-million-row test table (3.8 GiB uncompressed, a random UUID session_id per row) under a 1 GB per-query cap. Each failing shape failed there and then succeeded after a rewrite or a settings change, in some cases with under a tenth of the memory. Below: how to read the error, how to find the query, and the fix for each shape.

What does “Memory limit exceeded” mean in ClickHouse?

ClickHouse tracks memory at three levels, and each has its own setting and its own wording in the error:

LevelSettingDefault (self-managed 26.9)Message on 25.1 and laterMessage on older releases (24.8)
Querymax_memory_usage0 (unlimited)Query memory limit exceededMemory limit (for query) exceeded
Usermax_memory_usage_for_user0 (unlimited)User memory limit exceededMemory limit (for user) exceeded
Servermax_server_memory_usage0, which means 90% of RAM via max_server_memory_usage_to_ram_ratio(total) memory limit exceededMemory limit (total) exceeded

Here is the per-query version as 26.9 prints it, from a GROUP BY session_id on the test table:

Code: 241. DB::Exception: Query memory limit exceeded: would use 958.08 MiB
(attempt to allocate chunk of 7.63 MiB), maximum: 953.67 MiB:
While executing AggregatingTransform. (MEMORY_LIMIT_EXCEEDED)

Three parts of that message matter. The level (query, user or total) tells you which budget to look at. “maximum” is the limit in effect, and 953.67 MiB is what max_memory_usage = 1000000000 looks like in binary units. “While executing” names the operator that made the failing allocation: AggregatingTransform for GROUP BY, FillingRightJoinSide or JoiningTransform for a join build. Treat that last clue with care, because it is where the allocation failed, not necessarily the operator holding the memory. In our tests, sorts that ran out of memory reported MergeTreeSelect, the reading stage, because the sort had already filled the budget and the next block read tipped it over.

On self-managed ClickHouse the per-query and per-user limits are off by default, so a self-managed server usually only shows (total) errors until somebody sets a profile limit. ClickHouse Cloud sets max_memory_usage according to the replica’s RAM. A (total) error is different in kind: the server as a whole is near its cap, and ClickHouse picks a query to stop. The memory overcommit docs describe the choice: the query with the highest ratio of allocated bytes to its memory_overcommit_ratio_denominator, which with the default 1 GiB denominator on every query is the biggest one. That may be a victim rather than the cause, since the server might have been filled by twenty medium queries. Messages from this path include OvercommitTracker decision: Query was selected to stop.

How to find the queries that hit the memory limit

Every failed query lands in system.query_log with exception_code = 241. Group by normalized_query_hash so runs that differ only in literals collapse into one row, and pull the limit level and the operator out of the message:

SELECT
    normalized_query_hash,
    count()                                             AS failures,
    multiIf(exception ILIKE '%(total)%', 'server',
            exception ILIKE '%user memory%'
              OR exception ILIKE '%(for user)%', 'user',
            'query')                                    AS limit_hit,
    extract(exception, 'While executing (\\w+)')        AS operator,
    formatReadableSize(max(memory_usage))               AS peak_memory,
    any(user)                                           AS user,
    substring(any(query), 1, 120)                       AS sample_query
FROM system.query_log
WHERE event_time > now() - INTERVAL 1 DAY
  AND type = 'ExceptionWhileProcessing'
  AND exception_code = 241
GROUP BY normalized_query_hash, limit_hit, operator
ORDER BY failures DESC
LIMIT 20;

The failures are only half the picture. Queries that succeed at 80 or 90 percent of the limit are tomorrow’s errors, and ranking successful queries by peak memory finds them:

SELECT
    normalized_query_hash,
    count()                                    AS runs,
    formatReadableSize(max(memory_usage))      AS peak_memory,
    formatReadableSize(quantile(0.5)(memory_usage)) AS median_memory,
    substring(any(query), 1, 120)              AS sample_query
FROM system.query_log
WHERE event_time > now() - INTERVAL 7 DAY
  AND type = 'QueryFinish'
GROUP BY normalized_query_hash
ORDER BY max(memory_usage) DESC
LIMIT 20;

For an incident in progress, system.processes shows live memory_usage and peak_memory_usage per running query, and KILL QUERY WHERE query_id = '...' stops one. For trends, system.events keeps the running counters QueryMemoryLimitExceeded and GlobalMemoryLimitExceeded since server start. A rising global count is a sizing signal, which ClickHouse sizing for a data team of 20 covers.

Which query shapes run out of memory?

These are the shapes we reproduced, what each did on the test table with no cap, and what worked under the 1 GB cap. Peaks are memory_usage from system.query_log.

Query shapePeak with no capUnder a 1 GB capChange that workedPeak after
GROUP BY session_id (40M distinct keys)2.74 GiBFailedmax_bytes_before_external_group_by = 400 MB723 MiB
count(DISTINCT session_id)3.02 GiBFaileduniq(session_id)10.3 MiB
GROUP BY on the table’s full sort key2.69 GiBFailedoptimize_aggregation_in_order = 184.6 MiB
SELECT * ... ORDER BY revenue, no LIMIT3.88 GiBFailedLIMIT 100646 KiB
Same sort, full result needed3.88 GiBFailedExternal sort at 300 MB, ratio 0, fewer columnsdepends on row width, see below
JOIN with a 40M-row right sidenot measuredFailedjoin_algorithm = 'grace_hash', 64 buckets776 MiB
Same filter written as IN (subquery) with a selective subqueryn/aSucceededn/a74.5 MiB

The pattern is the same in every row: the default operator keeps one entry per distinct key, row or right-side row in memory, so its footprint follows the input. Each fix either shrinks what is held, holds it in a smarter order, or moves part of it to disk.

Fix high-cardinality GROUP BY

A hash aggregation keeps one state per distinct key. Grouping 40 million rows by a column with 40 million values means 40 million states, plus the keys themselves if they are strings. Four fixes, cheapest first.

Ask whether you need exact distinct counts. count(DISTINCT x) stores every value. uniq keeps a bounded-size sketch. On the test table the exact count failed under the cap, while uniq returned 39,991,740 against the true 40,000,000 (0.02% off) using 10.3 MiB, and uniqCombined returned 40,039,916 (0.1% off) in 5 MiB. For dashboards and trend lines that error is invisible. For billing it is not, so keep the exact form there and spill instead.

Aggregate in sort-key order. If the GROUP BY keys are the table’s ORDER BY key or a prefix of it, ClickHouse can finish each group as it reads instead of holding all of them. The GROUP BY reference documents this under optimize_aggregation_in_order, which is off by default and can sometimes make a query slower:

SELECT event_type, event_time, count(), sum(revenue)
FROM events                     -- ORDER BY (event_type, event_time)
GROUP BY event_type, event_time
SETTINGS optimize_aggregation_in_order = 1;

On the test table that took the query from a failure to an 84.6 MiB peak. If a heavy aggregation keeps hitting the limit and its keys are not a sort-key prefix, a projection or a materialized view with a matching sort key moves the work to insert time.

Group by fewer, narrower keys. Every column in GROUP BY multiplies cardinality and adds key bytes. A column that only depends on the key (a user’s country when grouping by user) belongs in any(country), not in the key list. Grouping by a UInt64 id instead of a 36-byte string also helps.

Let the aggregation spill to disk. When the result really has tens of millions of groups, max_bytes_before_external_group_by writes partial aggregation states to temporary files once the threshold is crossed:

SELECT session_id, count()
FROM events
GROUP BY session_id
ORDER BY count() DESC
LIMIT 10
SETTINGS max_memory_usage = 1000000000,
         max_bytes_before_external_group_by = 400000000;

The docs recommend setting max_memory_usage about twice as high as the spill threshold, because only the first stage of aggregation can spill and the merge stage still needs room. In our run that query wrote 1.68 GiB of temporary data and peaked at 723 MiB. Expect it to be slower: the docs estimate around three times slower when data is spilled.

A version detail that changes older advice: since 25.1, max_bytes_ratio_before_external_group_by defaults to 0.5, so GROUP BY spills automatically once it reaches half the memory available to the user or server. We confirmed this works against a max_memory_usage_for_user limit. It did not help against a per-query max_memory_usage cap: with only the ratio default in place, the same GROUP BY under a 1 GB query cap still failed. If your users run under a per-query cap, set the byte threshold explicitly.

Fix ORDER BY without LIMIT

A full sort holds every row of every selected column until it can emit the first one. On the test table, SELECT * FROM events ORDER BY revenue DESC peaked at 3.88 GiB. Adding LIMIT 100 dropped that to 646 KiB, because ClickHouse keeps only the top rows per stream instead of the whole input. Most BI queries that sort millions of rows are feeding a table widget that shows 50, so the first fix is to make sure the LIMIT reaches the warehouse rather than being applied in the client.

Two cheaper changes help when you do need the whole result. Select only the columns you need, because SELECT * sorts every column, including wide strings. And sort by the table’s sort key where you can, since ClickHouse can then read in order without a full sort.

When the full sorted output is the point, for an export for example, spill the sort with max_bytes_before_external_sort. Here we hit a trap on 26.9. With the default max_bytes_ratio_before_external_sort = 0.5 left in place, setting max_bytes_before_external_sort alone did not spill under a per-query cap: thresholds from 50 MB to 300 MB all failed and wrote no sort files. The ratio setting’s own description notes that max_bytes_before_external_sort is still respected while it is in use, but only as the size a sorting block must reach before it is spilled. The ratio decides when spilling starts, and it is measured against the memory available to the server or user, not the per-query cap. Setting the ratio to 0 handed control back to the byte threshold:

SELECT *
FROM events
ORDER BY revenue DESC
SETTINGS max_memory_usage = 1000000000,
         max_bytes_before_external_sort = 300000000,
         max_bytes_ratio_before_external_sort = 0;

With the ratio at 0 the sort phase spills as expected, and ProfileEvents['ExternalSortWritePart'] in system.query_log shows the runs written. Zero there means it never spilled. Whether the whole query then finishes under the cap depends on row width and thread count: the final merge still holds one block per spilled run per thread in memory, and with SELECT * on wide rows that merge can exceed a 1 GB cap on its own. We saw both outcomes on two test machines with different fixtures. If the merge stage is what fails (MergeSorterSource or MergingSortedTransform in the error), select fewer columns, lower the threshold so each run is smaller, or lower max_threads for that query.

Fix JOINs with a large right side

The default hash join builds the right-hand side into an in-memory hash table, with every right-side column the query uses. That makes the right side the memory budget for the whole join. Two recent defaults soften it: since 24.12 the planner can swap the sides when it estimates the right one is larger (query_plan_join_swap_table = 'auto'), and since 26.5 max_bytes_ratio_before_external_join defaults to 0.5, so a hash join that grows toward the available memory converts itself to grace hash (the smaller of the ratio and the max_bytes_before_external_join byte threshold applies). ClickHouse JOIN performance covers join tuning in depth. The memory-specific steps, in order:

  1. Shrink the right side. Put the smaller input on the right (since 24.12, query_plan_join_swap_table = 'auto' lets the planner swap sides when it estimates the right is larger; confirm with EXPLAIN). Filter it and select only the columns you use, inside a subquery.
  2. Use IN when you only need to filter. A semi-join through IN (subquery) builds a set of keys, not a table of rows. On the test table, filtering purchases by sessions with a high-value event through IN peaked at 74.5 MiB.
  3. Switch to a memory-bounded algorithm. grace_hash partitions both sides into buckets and keeps most of them on disk. full_sorting_merge and partial_merge sort instead of hashing. They are slower, and they need their own spill settings to stay inside the cap.

The third step needs care in practice. With our 40-million-row right side under a 1 GB cap, the default algorithm went both ways on two test machines: on one the planner swapped the sides, built the hash table from the filtered 8-million-row input and finished at 651 MiB; on the other the swap did not kick in and it failed within a second. Check EXPLAIN before relying on the swap. Of the explicit settings, grace_hash with its default single initial bucket, partial_merge, full_sorting_merge with no sort spill, and the hash-to-grace conversion through the max_bytes_before_external_join byte threshold all failed under the cap. Two configurations succeeded on both machines:

-- grace hash join, more buckets from the start
SELECT count()
FROM events AS a
INNER JOIN (SELECT session_id, url, revenue FROM events) AS b
    ON a.session_id = b.session_id
WHERE a.event_type = 'purchase'
SETTINGS max_memory_usage = 1000000000,
         join_algorithm = 'grace_hash',
         grace_hash_join_initial_buckets = 64;

-- or a sort-merge join with an external sort
SELECT count()
FROM events AS a
INNER JOIN (SELECT session_id, url, revenue FROM events) AS b
    ON a.session_id = b.session_id
WHERE a.event_type = 'purchase'
SETTINGS max_memory_usage = 1000000000,
         join_algorithm = 'full_sorting_merge',
         max_bytes_before_external_sort = 200000000,
         max_bytes_ratio_before_external_sort = 0;

They peaked at 776 MiB and 614 MiB. Both took 15 to 20 seconds on our small test machines, against a few seconds for the default hash join when the swap made it fit, so these are tools for joins that must finish. They are no substitute for a smaller right side, and for repeated lookups against a dimension a dictionary avoids the build entirely.

Set limits so one query cannot take down the server

With nothing configured, a self-managed server has no per-query or per-user cap, and one analyst’s runaway join is a (total) error for everyone. Give interactive users a settings profile that caps each query, caps each user, and spills before the cap:

CREATE SETTINGS PROFILE bi_queries SETTINGS
    max_memory_usage = 8000000000,                  -- 8 GB per query
    max_bytes_before_external_group_by = 4000000000,
    max_bytes_before_external_sort = 4000000000,
    max_bytes_ratio_before_external_sort = 0,
    max_memory_usage_for_user = 20000000000;        -- 20 GB across one user's queries

ALTER USER bi_reader SETTINGS PROFILE 'bi_queries';

Size the numbers to the machine. The per-query cap should leave room for several concurrent queries, merges and caches under max_server_memory_usage. Spill thresholds of about half the query cap follow the GROUP BY guidance above. Many BI tools send every dashboard query as one service user, so make the per-user limit large enough for a full dashboard refresh, or you will move the error rather than fix it.

Two related knobs are worth knowing. memory_usage_overcommit_max_wait_microseconds (5 seconds by default for the user-level tracker) is how long a query that hits a limit waits for memory to be freed before it fails. Setting a query’s memory_overcommit_ratio_denominator to 0 means the overcommit tracker never selects that query to stop, which is useful for a scheduled job you never want sacrificed. Both are part of the overcommit mechanism, which the docs label experimental.

Should you just raise max_memory_usage?

Sometimes. If a query is legitimately large, runs rarely, and the server has headroom, raising the limit for that one query (SETTINGS max_memory_usage = ...) is the honest fix. ClickHouse’s knowledge base also says that scaling up is the answer when performance is critical. But raising the cap for everyone turns a contained per-query failure into a server-wide one, because the next runaway query has more room to crowd out others before anything stops it. Fix the shape first, spill second, and raise limits last.

Watching memory continuously

Most memory errors are found after the fact, from a dashboard tile that went blank. It helps when someone can see heavy queries while they run. In Goni, the Pulse page lists the top 20 currently executing queries by memory and shows a live process list with memory_usage per query and a kill action. The query log surfaces the last hour of exceptions attributed to the user and the artifact, such as a chart, that ran them, and Doctor produces a root-cause report for a query that ran out of memory, as this look at LLM query root-cause analysis describes. Goni only works with ClickHouse, so this helps only if that is your warehouse. Every query above runs on any ClickHouse deployment with no extra tooling.

FAQ

What is error code 241 in ClickHouse?

Code 241 is MEMORY_LIMIT_EXCEEDED: an allocation would have pushed a query past max_memory_usage, a user past max_memory_usage_for_user, or the server past max_server_memory_usage. The message says which one, as “Query”, “User” or “(total)” on 26.x, or “(for query)”, “(for user)” or “(total)” on older releases. Find occurrences with exception_code = 241 in system.query_log.

What is the default max_memory_usage in ClickHouse?

On self-managed ClickHouse the default is 0, meaning no per-query limit. The server cap still applies: max_server_memory_usage defaults to 90% of available RAM through max_server_memory_usage_to_ram_ratio = 0.9. ClickHouse Cloud sets max_memory_usage based on the replica’s RAM. Check yours with SELECT value FROM system.settings WHERE name = 'max_memory_usage'.

How do I make ClickHouse spill to disk instead of failing?

Set max_bytes_before_external_group_by for aggregations and max_bytes_before_external_sort for sorts, at about half of max_memory_usage. On 25.1 and later, also set max_bytes_ratio_before_external_sort = 0, or the ratio decides when sorts spill. For joins, use join_algorithm = 'grace_hash' or a sort-merge algorithm. Spilled queries are slower but finish.

Why does ClickHouse run out of memory on GROUP BY?

Hash aggregation keeps one state per distinct key, so memory grows with the number of groups, not with the result you display. Grouping by a near-unique column such as a session id or URL is the usual cause. Use uniq instead of exact distinct counts, aggregate in sort-key order, drop dependent columns from the key, or enable external aggregation.

What does “(total) memory limit exceeded” mean?

The server as a whole reached max_server_memory_usage, so ClickHouse stopped a query, usually the one using the most memory, which is not always the cause. It points at concurrency or a server that is too small, not at one query. Add per-query and per-user limits, find the heavy queries in system.query_log, and size RAM to the workload.