Introduction

A query works perfectly on a small date range but fails when you run it against several months of production data. ClickHouse® reports MEMORY_LIMIT_EXCEEDED, or the query stops before returning results.

Large GROUP BY and ORDER BY operations are common causes of this problem. They can require substantial memory to hold aggregation states or sort intermediate data.

For example, consider the following query:

SELECT customer_id, event_type, count() AS event_count FROM events GROUP BY customer_id, event_type ORDER BY event_count DESC LIMIT 100; 

This query groups events by customer and event type. If the table contains millions of rows and many distinct combinations, ClickHouse must maintain aggregation states for those groups before it can produce the final results.

Sorting the aggregated results also requires resources. The LIMIT 100 clause does not guarantee that ClickHouse can avoid processing a large intermediate result.

The problem is not always a lack of server RAM. A query can exceed its configured memory limit even when the server still has free memory.

One way to address this is to let ClickHouse spill intermediate data to disk before memory pressure becomes critical. However, you must also manage temporary disk consumption and understand the performance trade-offs.

In this article, we will explore the relevant settings, how to diagnose memory issues, how to configure external aggregation and sorting, and how to verify that the changes work as expected.

1. Why Large GROUP BY and ORDER BY Operations Consume Memory

ClickHouse normally performs aggregation and sorting in memory whenever possible.

During aggregation, it builds and updates data structures for each group. High-cardinality grouping keys can create a large number of groups, while complex aggregate functions can require substantial memory for their aggregation states.

During sorting, ClickHouse must organize rows according to the requested sort keys. Large intermediate results can consume significant memory before the query finishes.

Two settings control when these operations can move intermediate data to disk:

  • max_bytes_before_external_group_by controls external aggregation.
  • max_bytes_before_external_sort controls external sorting.

This process is known as spilling to disk.

When an operation reaches its configured spill threshold, ClickHouse writes intermediate data to temporary files. It later reads and merges that data to complete the operation.

Spilling can reduce the memory required for certain processing stages, but it does not eliminate every memory requirement. ClickHouse still needs memory for processing, buffers, and merging intermediate results.

Byte thresholds versus ratio thresholds

ClickHouse provides two approaches for configuring spill thresholds.

Byte thresholds use fixed memory sizes. They can be useful when you know the memory budget for a workload.

Ratio thresholds use a fraction of available memory. They can adapt to available memory instead of relying exclusively on a fixed byte value.

The relevant ratio settings are:

  • max_bytes_ratio_before_external_group_by
  • max_bytes_ratio_before_external_sort

These settings are particularly useful when configured alongside max_memory_usage. However, the ratio is not simply a percentage of the query's memory limit. Its calculation relates to available memory and can depend on the operation and ClickHouse version.

Always verify the behavior on your deployed build.

2. How to Confirm the Problem

Before changing settings, inspect the current configuration. Do not assume that the defaults match another server or the documentation for a different version.

Step 1: Inspect session settings

Use system.settings to check the relevant values:

SELECT name, value, changed FROM system.settings WHERE name IN ( 'max_memory_usage', 'max_bytes_before_external_group_by', 'max_bytes_before_external_sort', 'max_bytes_ratio_before_external_group_by', 'max_bytes_ratio_before_external_sort', 'max_temporary_data_on_disk_size_for_query', 'max_temporary_data_on_disk_size_for_user' ) ORDER BY name; 

This helps you understand the active session settings and whether they have been changed from their defaults.

Step 2: Inspect server-level settings

Where applicable, inspect server-level settings as well:

SELECT name, value, default FROM system.server_settings WHERE name = 'max_temporary_data_on_disk_size'; 

The available system tables and columns can vary by ClickHouse version.

Step 3: Inspect the query log

The system.query_log table records information about query execution. Its ProfileEvents field can help identify external aggregation and sorting activity.

Run the following query after the relevant query has completed and its log entry is available:

SELECT event_time, query_id, type, query_duration_ms, memory_usage, ProfileEvents['ExternalAggregationWritePart'] AS aggregation_write_parts, ProfileEvents['ExternalSortWritePart'] AS sort_write_parts, exception_code, exception FROM system.query_log WHERE type IN ('QueryFinish', 'ExceptionWhileProcessing') AND event_time >= now() - INTERVAL 1 HOUR ORDER BY event_time DESC LIMIT 100; 

The ExternalAggregationWritePart and ExternalSortWritePart events can indicate that ClickHouse wrote external aggregation or sort data.

A positive write-part count is evidence of external processing. A value of zero does not prove that no spill occurred, because the event may be unavailable, unrecorded, or inapplicable to a particular query path.

Also inspect exception_code and exception. A query can spill data successfully and still fail later because merging the intermediate results requires more memory.

For a controlled test, run the query with a low spill threshold and compare the resulting profile events and memory usage with the original execution.

3. Understanding the Relevant Settings

The following defaults are from the ClickHouse master commit dated October 30, 2026. They are not guaranteed to match every ClickHouse 26.9 build.

Setting Default Purpose
max_bytes_before_external_group_by 0 (off) Fixed memory threshold for external aggregation
max_bytes_before_external_sort 0 (off) Fixed memory threshold for external sorting
max_bytes_ratio_before_external_group_by 0.5 Ratio threshold for external aggregation
max_bytes_ratio_before_external_sort 0.5 Ratio threshold for external sorting
max_temporary_data_on_disk_size_for_query 0 (no limit) Temporary disk data limit per query
max_temporary_data_on_disk_size_for_user 0 (no limit) Temporary disk data limit for a user's queries

Fixed byte thresholds

A byte threshold defines a fixed trigger for external processing.

For example:

SET max_bytes_before_external_group_by = 2000000000; 

This configures a threshold of approximately 2 GB for external aggregation.

Ratio thresholds

A ratio threshold uses a fraction of available memory.

For example:

SET max_bytes_ratio_before_external_group_by = 0.5; 

The ratio is not necessarily half of max_memory_usage. ClickHouse calculates the threshold based on available memory for the operation, which can account for server, user, and other memory limits.

The byte and ratio settings can interact. Do not assume that setting a ratio makes the byte threshold irrelevant. In particular, ClickHouse documentation specifies that max_bytes_before_external_sort remains respected when the sort ratio is configured.

For production workloads, configure ratio settings alongside max_memory_usage and test their behavior under realistic concurrency.

Temporary disk limits

Spilling shifts some resource pressure from RAM to storage. This can introduce another production problem if temporary files consume too much disk space.

Two settings help control this:

  • max_temporary_data_on_disk_size_for_query limits temporary disk data for an individual query.
  • max_temporary_data_on_disk_size_for_user limits temporary disk data for a user's queries.

A value of 0 means no limit.

These limits provide an additional layer of resource control. However, their enforcement should be verified on the exact ClickHouse build you operate. A reported issue describes temporary disk limits not stopping external sort spills in ClickHouse 26.2.4.

Do not treat configuration alone as proof that your disk is protected.

4. How to Fix the Problem

Start with per-query settings rather than changing every workload immediately. This makes it easier to test the configuration and compare results.

The following examples use:

  • A 20 GB query memory limit
  • A ratio of 0.5 for external aggregation
  • A ratio of 0.5 for external sorting
  • A 10 GB temporary disk limit per query
  • A 20 GB temporary disk limit per user

These are example starting values, not universal recommendations. Adjust them according to available RAM, storage capacity, query concurrency, and workload requirements.

Change 1: Configure memory and spill thresholds

For a single query, use the SETTINGS clause:

SELECT customer_id, event_type, count() AS event_count FROM events GROUP BY customer_id, event_type ORDER BY event_count DESC LIMIT 100 SETTINGS max_memory_usage = 20000000000, max_bytes_ratio_before_external_group_by = 0.5, max_bytes_ratio_before_external_sort = 0.5, max_bytes_before_external_group_by = 0, max_bytes_before_external_sort = 0; 

This example sets the query memory limit to 20 GB and configures ratio-based thresholds for external aggregation and sorting.

The fixed byte thresholds are set to zero to avoid relying on fixed thresholds alongside the ratio settings. Verify that this combination behaves as expected on your deployed version before using it in production.

The 20 GB memory limit defines a budget for the query. The ratios allow ClickHouse to trigger external processing based on available memory.

Do not copy the same memory limit into every workload without checking concurrency. Several concurrent queries can compete for the same server memory.

Change 2: Apply settings to a session

If you need several queries to use the same settings in one session, use SET statements:

SET max_memory_usage = 20000000000; SET max_bytes_ratio_before_external_group_by = 0.5; SET max_bytes_ratio_before_external_sort = 0.5; SET max_bytes_before_external_group_by = 0; SET max_bytes_before_external_sort = 0; 

These settings apply to subsequent queries in the session and do not require a server restart.

Before using this approach, confirm that your client preserves the same session between statements.

Change 3: Configure a settings profile

For production environments, a settings profile provides a central way to manage resource limits for the appropriate users.

For example, you can define a profile in users.xml or the relevant configuration file included by your installation:

<clickhouse> <profiles> <analytics_profile> <max_memory_usage>20000000000</max_memory_usage> <max_bytes_ratio_before_external_group_by> 0.5 </max_bytes_ratio_before_external_group_by> <max_bytes_ratio_before_external_sort> 0.5 </max_bytes_ratio_before_external_sort> <max_bytes_before_external_group_by> 0 </max_bytes_before_external_group_by> <max_bytes_before_external_sort> 0 </max_bytes_before_external_sort> <max_temporary_data_on_disk_size_for_query> 10000000000 </max_temporary_data_on_disk_size_for_query> <max_temporary_data_on_disk_size_for_user> 20000000000 </max_temporary_data_on_disk_size_for_user> </analytics_profile> </profiles> </clickhouse> 

This example sets a 10 GB temporary data limit per query and a 20 GB limit per user.

These limits aim to reduce the risk of a single query or user consuming all available temporary storage.

Next, configure the relevant user to use analytics_profile through your existing user configuration or access-control management. Avoid creating a second conflicting profile for the same workload.

Apply the configuration through your normal ClickHouse configuration process. Settings profiles generally do not require a full server restart, but configuration reload behavior depends on the setting and deployment method.

After applying the changes, verify that the active profile contains the expected values.

Important: Treat temporary disk limits as an additional safety control, not a substitute for monitoring free disk space. Test their enforcement with representative queries before relying on them to prevent disk exhaustion.

5. How to Verify the Fix

After applying the settings, repeat the workload using representative production data.

Compare the results with a baseline execution and check the following:

  • The query completes without MEMORY_LIMIT_EXCEEDED.
  • The query's ProfileEvents show external aggregation or sorting when spilling occurs.
  • Peak memory remains within the intended budget.
  • Query duration remains acceptable for the workload.
  • Temporary disk consumption stays within the limits you intended to enforce.

Use system.query_log to inspect completed queries:

SELECT event_time, query_id, query_duration_ms, memory_usage, ProfileEvents['ExternalAggregationWritePart'] AS aggregation_write_parts, ProfileEvents['ExternalSortWritePart'] AS sort_write_parts, exception_code, exception FROM system.query_log WHERE type IN ('QueryFinish', 'ExceptionWhileProcessing') AND event_time >= now() - INTERVAL 1 HOUR ORDER BY event_time DESC LIMIT 50; 

A query that completes successfully with external write events provides evidence that spilling occurred.

However, a successful query does not prove that every memory or disk limit worked as intended. Test the limits separately in a controlled environment.

For example, run a workload known to generate large temporary files. Check whether it stops when it reaches the configured disk limit, and monitor free disk space during execution.

What if the query still fails?

If the query continues to fail, inspect its exception and memory usage.

The failure may occur during the merge stage, even after the initial aggregation or sorting stage successfully spills data to disk.

If memory consumption remains too high, consider:

  • Reducing the amount of input data processed.
  • Simplifying aggregation states where possible.
  • Reviewing the query plan.
  • Checking whether the grouping keys create an excessive number of distinct groups.
  • Reviewing memory limits in the context of concurrent workloads.

Increasing memory limits without evaluating concurrent queries can simply move the problem from an individual query to the server as a whole.

6. Risks and Trade-Offs

Spilling intermediate data to disk can help manage memory pressure, but it introduces trade-offs.

Increased query latency

Disk-based processing is generally slower than keeping intermediate data in memory. ClickHouse must write temporary files, read them back, and merge intermediate results.

This additional disk I/O can increase query execution time.

Storage pressure

Concurrent queries that spill data can compete for disk bandwidth and temporary storage.

They can also affect normal reads, writes, background merges, and other workloads.

Memory is still required

Spilling does not guarantee that every query will complete successfully. The merge stage still requires memory, and other stages of query execution may consume substantial resources.

Limits must match the workload

A temporary disk limit that is too low can terminate legitimate analytical queries. A limit that is too high may allow temporary data to consume valuable storage.

Similarly, memory limits must account for query concurrency rather than treating every query as an isolated workload.

After deployment, monitor query latency, memory usage, temporary disk consumption, and failure rates. Test with realistic query concurrency rather than relying on a single isolated execution.

7. Summary

Large GROUP BY and ORDER BY operations can cause memory pressure in ClickHouse®, particularly when queries process large datasets or generate many intermediate results.

External aggregation and external sorting allow ClickHouse to spill intermediate data to disk when configured thresholds are reached.

To manage these workloads effectively:

  1. Enable and configure external aggregation and sorting appropriately.
  2. Use ratio settings alongside max_memory_usage to manage memory pressure.
  3. Configure temporary disk limits for queries and users.
  4. Use system.query_log and relevant ProfileEvents to investigate query execution.
  5. Verify that memory and disk limits behave as expected on your deployed version.
  6. Test query latency, memory consumption, disk usage, and failure rates under realistic production workloads.

The goal is not simply to make a query complete. It is to make sure that it completes within a resource budget that is sustainable for your production environment.

References

  • ClickHouse documentation: Memory limit exceeded for query — external aggregation, external sorting, and their performance trade-offs.
  • ClickHouse source: Settings.cpp — definitions and descriptions of external sorting and ratio thresholds.
  • ClickHouse documentation: ORDER BY implementation details — external sorting and memory behavior.
  • ClickHouse 26.9 release information.
  • ClickHouse documentation: system.query_log — query-log fields and profile-event inspection.