From 7ab4a236ac8ceb294130bc0115a803b1bec2677a Mon Sep 17 00:00:00 2001 From: BorisTyshkevich <125603338+BorisTyshkevich@users.noreply.github.com> Date: Tue, 1 Dec 2026 16:36:34 +0100 Subject: [PATCH 1/5] Add article: merges that fail with MEMORY_LIMIT_EXCEEDED in a loop Co-Authored-By: Claude Opus 5.5 --- .../altinity-kb-merges-memory-limit-loop.md | 124 ++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 content/en/altinity-kb-setup-and-maintenance/altinity-kb-merges-memory-limit-loop.md diff --git a/content/en/altinity-kb-setup-and-maintenance/altinity-kb-merges-memory-limit-loop.md b/content/en/altinity-kb-setup-and-maintenance/altinity-kb-merges-memory-limit-loop.md new file mode 100644 index 0000000000..345e117f26 --- /dev/null +++ b/content/en/altinity-kb-setup-and-maintenance/altinity-kb-merges-memory-limit-loop.md @@ -0,0 +1,124 @@ +--- +title: "Merges that fail with MEMORY_LIMIT_EXCEEDED again and again" +linkTitle: "Merges failing on memory in a loop" +description: > + Why a big ClickHouse® merge can fail on memory forever, how to stop the loop, and how to make merges of wide rows use less memory. +keywords: + - MEMORY_LIMIT_EXCEEDED merge + - vertical merge memory + - index_granularity +--- + +A ClickHouse® merge that fails with `MEMORY_LIMIT_EXCEEDED` can run again and again for days, with high CPU and I/O while queries are almost idle. This page applies to `ReplicatedMergeTree` tables and was checked on 25.8. + +## Symptoms + +- CPU is high, but `system.processes` shows few queries. +- `system.merges` shows the same big merges again and again. +- `system.part_log` shows `MergeParts` rows with `error = 241` and `size_in_bytes = 0`. + +Failed merges per day and table: + +```sql +SELECT + event_date, + database, + table, + merge_algorithm, + countIf(error = 0) AS ok, + countIf(error != 0) AS failed, + formatReadableSize(max(peak_memory_usage)) AS max_peak +FROM system.part_log +WHERE event_type = 'MergeParts' AND event_date >= today() - 7 +GROUP BY event_date, database, table, merge_algorithm +HAVING failed > 0 +ORDER BY event_date, failed DESC +``` + +Merge entries that keep failing in the replication queue (use this for alerting): + +```sql +SELECT database, table, new_part_name, num_tries, num_postponed, last_exception +FROM system.replication_queue +WHERE type = 'MERGE_PARTS' AND num_tries > 10 AND last_exception LIKE '%MEMORY_LIMIT_EXCEEDED%' +``` + +## Why the merge repeats + +- A replicated merge is a fixed entry in the replication log. It names its exact source parts, and every replica must run it as it is or fetch the result. ClickHouse does not replace it with a smaller merge. +- After a failure, the entry waits at most `max_postpone_time_for_failed_replicated_merges_ms` (60 s by default in 25.8) and runs again. +- `max_bytes_to_merge_at_max_space_in_pool` does not stop an entry that is already in the log. When at least `number_of_free_entries_in_pool_to_lower_max_size_of_merge` pool slots are free, ClickHouse runs a logged merge of any size ([source](https://github.com/ClickHouse/ClickHouse/blob/v25.8.16.34-lts/src/Storages/MergeTree/ReplicatedMergeTreeQueue.cpp)). +- The memory limit covers the whole server. When several big merges run at the same time, they push each other over the limit. + +## Stop the loop + +Let only one or two big merges run at a time. Set the threshold to the number of pool slots minus 1. The pool has `background_pool_size` × `background_merges_mutations_concurrency_ratio` slots, 16 × 2 = 32 by default: + +```sql +ALTER TABLE db.table ON CLUSTER '{cluster}' + MODIFY SETTING number_of_free_entries_in_pool_to_lower_max_size_of_merge = 31; +``` + +The setting applies when a merge starts. To cancel the merges that run now, run this on each replica: + +```sql +SYSTEM STOP MERGES db.table; +SYSTEM START MERGES db.table; +``` + +The cancelled merges end with error 236 (`ABORTED`) in `system.part_log`. Merges that start in the same scheduling pass all go through, so you can still see 2–3 big merges right after `START MERGES`. + +If one merge alone fits in memory, the entries finish one by one. After the backlog clears, remove the setting: + +```sql +ALTER TABLE db.table ON CLUSTER '{cluster}' + RESET SETTING number_of_free_entries_in_pool_to_lower_max_size_of_merge; +``` + +If a merge cannot fit in memory even alone, you must add memory for a short time or remove its source data. + +{{% alert title="Warning" color="warning" %}} +`DROP PARTITION` deletes data on all replicas. Use it only when the data is not needed, for example when the partition is already older than the table TTL. Parts that a stuck merge holds are not removed by `ttl_only_drop_parts`, so expired partitions can stay on disk until the merge is gone. +{{% /alert %}} + +## Why a merge needs so much memory + +Merge memory depends on the size of one granule, not on the size of the result part. A merge reads one granule from each source part at a time: one column of it in a vertical merge, all columns in a horizontal merge. + +Granules can be much larger than `index_granularity_bytes` (10 MB): + +- At insert, adaptive granularity uses the average row size of the insert block. When most rows are small and a few are large, every granule gets up to `index_granularity` (8192) rows. +- The `ORDER BY` key can put the large rows next to each other, for example all spans of one service with big attributes. Then some granules hold 8192 large rows. +- Large granules can survive later merges. In the test below, they stayed when source parts did not overlap in key order, as with time-ordered data inside one service. + +Test on 25.8.16: a table with a `Map` column, every 33rd row about 25 KB, and 6 parts of 300,000 rows. All merges were vertical. + +| Table settings | First merge peak | Later merges peak | +|---|---|---| +| defaults | 1.49 GiB | 844 MiB | +| `merge_max_block_size_bytes = 1048576` | 1.49 GiB | 844 MiB | +| `merge_max_block_size = 1024` set at `CREATE` | 1.49 GiB | 120 MiB | +| `merge_max_block_size = 1024` set with `ALTER` | 1.49 GiB | 844 MiB | +| `index_granularity = 1024` | 397 MiB | 120 MiB | +| `index_granularity_bytes = 1048576` | 450 MiB | 132 MiB | + +The result part was 13 MiB compressed in every case. + +## Fix the table + +Make granules smaller for tables with wide rows of very different sizes, for example OpenTelemetry tables with `Map` attributes: + +- `index_granularity = 1024`, or `index_granularity_bytes = 1048576`. These limits apply at insert and at merge. Both settings are read-only after `CREATE`, so you must create a new table. With a TTL table, you can send new data to the new table and let the old table expire. +- `merge_max_block_size` helps only where rows of different source parts overlap in key order. It does not split granules of existing parts. +- `merge_max_block_size_bytes` did not reduce the memory of vertical merges in the test. + +Smaller granules give more marks and a bigger primary index in memory. Measure query speed after the change. Also check the source of the large rows: a limit on attribute value length in the OpenTelemetry SDK or collector removes the problem at the source. + +## Related resources + +- [Aggressive merges](/altinity-kb-setup-and-maintenance/altinity-kb-aggressive_merges/) +- [Replication problems](/altinity-kb-setup-and-maintenance/altinity-kb-check-replication-ddl-queue/) +- [Merge performance and OPTIMIZE FINAL](/engines/mergetree-table-engine-family/merge-performance-final-optimize-by/) +- [MergeTree settings: `merge_max_block_size`](https://clickhouse.com/docs/operations/settings/merge-tree-settings#merge_max_block_size) +- [MergeTree data storage and granules](https://clickhouse.com/docs/engines/table-engines/mergetree-family/mergetree#mergetree-data-storage) +- [ClickHouse issue #135911: merge-storm control](https://github.com/ClickHouse/ClickHouse/issues/135911) From 84cbdc6170bac77edd3c78d9b675ae2b3fda9afe Mon Sep 17 00:00:00 2001 From: BorisTyshkevich <125603338+BorisTyshkevich@users.noreply.github.com> Date: Tue, 1 Dec 2026 16:46:03 +0100 Subject: [PATCH 2/5] Clarify replicated merge memory troubleshooting and recovery Describe the pool threshold as a size-based mitigation, not a concurrency cap. Clarify retry backoff, cancellation, rollback and data deletion risks. Preserve the tested diagnostic SQL, summarize benchmark findings and remove unsupported generalizations. Revised recovery sequence still needs runtime validation. --- .../altinity-kb-merges-memory-limit-loop.md | 88 +++++++------------ 1 file changed, 33 insertions(+), 55 deletions(-) diff --git a/content/en/altinity-kb-setup-and-maintenance/altinity-kb-merges-memory-limit-loop.md b/content/en/altinity-kb-setup-and-maintenance/altinity-kb-merges-memory-limit-loop.md index 345e117f26..386115e388 100644 --- a/content/en/altinity-kb-setup-and-maintenance/altinity-kb-merges-memory-limit-loop.md +++ b/content/en/altinity-kb-setup-and-maintenance/altinity-kb-merges-memory-limit-loop.md @@ -1,23 +1,21 @@ --- -title: "Merges that fail with MEMORY_LIMIT_EXCEEDED again and again" -linkTitle: "Merges failing on memory in a loop" +title: "Repeated MEMORY_LIMIT_EXCEEDED during replicated merges" +linkTitle: "Repeated merge memory failures" description: > - Why a big ClickHouse® merge can fail on memory forever, how to stop the loop, and how to make merges of wide rows use less memory. + Diagnose repeated merge memory failures in ClickHouse® and reduce memory pressure during replicated merges. keywords: - MEMORY_LIMIT_EXCEEDED merge - vertical merge memory - index_granularity --- -A ClickHouse® merge that fails with `MEMORY_LIMIT_EXCEEDED` can run again and again for days, with high CPU and I/O while queries are almost idle. This page applies to `ReplicatedMergeTree` tables and was checked on 25.8. +A ClickHouse® `ReplicatedMergeTree` merge can repeatedly fail with `MEMORY_LIMIT_EXCEEDED`, consuming CPU and I/O even when query load is low. This article was checked on 25.8.16.34. -## Symptoms +## Diagnose the problem -- CPU is high, but `system.processes` shows few queries. -- `system.merges` shows the same big merges again and again. -- `system.part_log` shows `MergeParts` rows with `error = 241` and `size_in_bytes = 0`. +Look for recurring large merges in `system.merges` and `MergeParts` events with `error = 241` in `system.part_log`. Run the following queries on each affected replica. -Failed merges per day and table: +Daily merge outcomes (includes failures other than code 241 and the peak across all recorded merges): ```sql SELECT @@ -35,7 +33,7 @@ HAVING failed > 0 ORDER BY event_date, failed DESC ``` -Merge entries that keep failing in the replication queue (use this for alerting): +Find queued merge entries with many attempts and a memory-limit exception: ```sql SELECT database, table, new_part_name, num_tries, num_postponed, last_exception @@ -43,82 +41,62 @@ FROM system.replication_queue WHERE type = 'MERGE_PARTS' AND num_tries > 10 AND last_exception LIKE '%MEMORY_LIMIT_EXCEEDED%' ``` -## Why the merge repeats +Check whether the same entries remain queued, their attempt counts increase, and code 241 continues to appear in the part log. -- A replicated merge is a fixed entry in the replication log. It names its exact source parts, and every replica must run it as it is or fetch the result. ClickHouse does not replace it with a smaller merge. -- After a failure, the entry waits at most `max_postpone_time_for_failed_replicated_merges_ms` (60 s by default in 25.8) and runs again. -- `max_bytes_to_merge_at_max_space_in_pool` does not stop an entry that is already in the log. When at least `number_of_free_entries_in_pool_to_lower_max_size_of_merge` pool slots are free, ClickHouse runs a logged merge of any size ([source](https://github.com/ClickHouse/ClickHouse/blob/v25.8.16.34-lts/src/Storages/MergeTree/ReplicatedMergeTreeQueue.cpp)). -- The memory limit covers the whole server. When several big merges run at the same time, they push each other over the limit. +## Why merges retry -## Stop the loop +Replicated merge entries specify their source parts. A failed merge is retried rather than automatically replaced with smaller merges. In 25.8, the retry backoff is capped by `max_postpone_time_for_failed_replicated_merges_ms` (60 seconds by default); actual scheduling can take longer. -Let only one or two big merges run at a time. Set the threshold to the number of pool slots minus 1. The pool has `background_pool_size` × `background_merges_mutations_concurrency_ratio` slots, 16 × 2 = 32 by default: +Reducing `max_bytes_to_merge_at_max_space_in_pool` alone may not stop an already queued merge: when the scheduler permits the maximum merge size, it can bypass the size restriction for logged merges ([source](https://github.com/ClickHouse/ClickHouse/blob/v25.8.16.34-lts/src/Storages/MergeTree/ReplicatedMergeTreeQueue.cpp#L1675-L1718)). + +## Reduce memory pressure + +Check the memory-limit exception and available server memory. Concurrent merges can compete for memory with each other and with queries. + +Increasing `number_of_free_entries_in_pool_to_lower_max_size_of_merge` makes the scheduler lower the eligible merge size earlier as the shared merge/mutation pool fills. This is not a concurrency limit: eligibility also depends on the configured minimum and maximum merge sizes ([source](https://github.com/ClickHouse/ClickHouse/blob/v25.8.16.34-lts/src/Storages/MergeTree/Compaction/CompactionStatistics.cpp#L92-L133)). + +The following temporary setting was used on a 25.8.16 deployment with 32 pool slots. Check your actual `background_pool_size` and `background_merges_mutations_concurrency_ratio`, and record the original table setting before changing it. ```sql ALTER TABLE db.table ON CLUSTER '{cluster}' MODIFY SETTING number_of_free_entries_in_pool_to_lower_max_size_of_merge = 31; ``` -The setting applies when a merge starts. To cancel the merges that run now, run this on each replica: +On each affected replica, stop merges: ```sql SYSTEM STOP MERGES db.table; -SYSTEM START MERGES db.table; ``` -The cancelled merges end with error 236 (`ABORTED`) in `system.part_log`. Merges that start in the same scheduling pass all go through, so you can still see 2–3 big merges right after `START MERGES`. - -If one merge alone fits in memory, the entries finish one by one. After the backlog clears, remove the setting: +Wait for the running merges to disappear from `system.merges` before restarting them: ```sql -ALTER TABLE db.table ON CLUSTER '{cluster}' - RESET SETTING number_of_free_entries_in_pool_to_lower_max_size_of_merge; +SYSTEM START MERGES db.table; ``` -If a merge cannot fit in memory even alone, you must add memory for a short time or remove its source data. +Cancelled merges can log error 236 (`ABORTED`). Several large merges may still run concurrently. Monitor memory, queued merge attempts and active part counts; stopping or restricting merges for too long can cause insert failures. Restore the original setting after recovery (use `RESET SETTING` only if no table-specific value was configured before). + +If a single merge still exceeds available memory, increase memory headroom or consider whether a healthy replica can complete the merge and provide the resulting part for fetching. {{% alert title="Warning" color="warning" %}} -`DROP PARTITION` deletes data on all replicas. Use it only when the data is not needed, for example when the partition is already older than the table TTL. Parts that a stuck merge holds are not removed by `ttl_only_drop_parts`, so expired partitions can stay on disk until the merge is gone. +As a last resort, `DROP PARTITION` deletes data across replicas. Use it only after confirming that all data in the partition is disposable and that retention and backup requirements are satisfied. Partition age alone does not prove that every row has expired. {{% /alert %}} -## Why a merge needs so much memory - -Merge memory depends on the size of one granule, not on the size of the result part. A merge reads one granule from each source part at a time: one column of it in a vertical merge, all columns in a horizontal merge. - -Granules can be much larger than `index_granularity_bytes` (10 MB): - -- At insert, adaptive granularity uses the average row size of the insert block. When most rows are small and a few are large, every granule gets up to `index_granularity` (8192) rows. -- The `ORDER BY` key can put the large rows next to each other, for example all spans of one service with big attributes. Then some granules hold 8192 large rows. -- Large granules can survive later merges. In the test below, they stayed when source parts did not overlap in key order, as with time-ordered data inside one service. - -Test on 25.8.16: a table with a `Map` column, every 33rd row about 25 KB, and 6 parts of 300,000 rows. All merges were vertical. - -| Table settings | First merge peak | Later merges peak | -|---|---|---| -| defaults | 1.49 GiB | 844 MiB | -| `merge_max_block_size_bytes = 1048576` | 1.49 GiB | 844 MiB | -| `merge_max_block_size = 1024` set at `CREATE` | 1.49 GiB | 120 MiB | -| `merge_max_block_size = 1024` set with `ALTER` | 1.49 GiB | 844 MiB | -| `index_granularity = 1024` | 397 MiB | 120 MiB | -| `index_granularity_bytes = 1048576` | 450 MiB | 132 MiB | - -The result part was 13 MiB compressed in every case. +## Reduce merge memory for wide rows -## Fix the table +Granules may contain much more data than expected when row sizes vary widely and sorting groups large rows together. Vertical merges can still require substantial memory when reading wide non-key columns such as `Map` attributes. Compressed part size alone is not a reliable memory estimate. -Make granules smaller for tables with wide rows of very different sizes, for example OpenTelemetry tables with `Map` attributes: +For new tables with this workload, test `index_granularity = 1024` or `index_granularity_bytes = 1048576`. In the author's 25.8.16.34 vertical-merge test, these settings reduced the first merge peak from 1.49 GiB to 397 MiB and 450 MiB, respectively. Both settings are [read-only after table creation in 25.8](https://github.com/ClickHouse/ClickHouse/blob/v25.8.16.34-lts/src/Storages/MergeTree/MergeTreeSettings.cpp#L2479-L2487), so create a new table and migrate data as needed. -- `index_granularity = 1024`, or `index_granularity_bytes = 1048576`. These limits apply at insert and at merge. Both settings are read-only after `CREATE`, so you must create a new table. With a TTL table, you can send new data to the new table and let the old table expire. -- `merge_max_block_size` helps only where rows of different source parts overlap in key order. It does not split granules of existing parts. -- `merge_max_block_size_bytes` did not reduce the memory of vertical merges in the test. +Reducing `merge_max_block_size` helped subsequent merges in the test when set at creation, but did not reduce peak memory after an `ALTER` on the existing table. Reducing `merge_max_block_size_bytes` alone did not help in this test. -Smaller granules give more marks and a bigger primary index in memory. Measure query speed after the change. Also check the source of the large rows: a limit on attribute value length in the OpenTelemetry SDK or collector removes the problem at the source. +Smaller granules increase the number of marks and primary index entries. Benchmark query performance and consider limiting oversized attributes at ingestion. ## Related resources - [Aggressive merges](/altinity-kb-setup-and-maintenance/altinity-kb-aggressive_merges/) - [Replication problems](/altinity-kb-setup-and-maintenance/altinity-kb-check-replication-ddl-queue/) - [Merge performance and OPTIMIZE FINAL](/engines/mergetree-table-engine-family/merge-performance-final-optimize-by/) -- [MergeTree settings: `merge_max_block_size`](https://clickhouse.com/docs/operations/settings/merge-tree-settings#merge_max_block_size) +- [MergeTree settings](https://clickhouse.com/docs/operations/settings/merge-tree-settings) - [MergeTree data storage and granules](https://clickhouse.com/docs/engines/table-engines/mergetree-family/mergetree#mergetree-data-storage) - [ClickHouse issue #135911: merge-storm control](https://github.com/ClickHouse/ClickHouse/issues/135911) From 8f85d792d74977a86bd79020b2d41d1f8fe58838 Mon Sep 17 00:00:00 2001 From: BorisTyshkevich <125603338+BorisTyshkevich@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:00:08 +0100 Subject: [PATCH 3/5] Generalize merge memory troubleshooting across ClickHouse releases Distinguish source-verified behavior from tests performed on 25.8. Document the 25.4 introduction of configurable merge retry backoff and qualify immutable granularity settings for ReplicatedMergeTree. --- .../altinity-kb-merges-memory-limit-loop.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/content/en/altinity-kb-setup-and-maintenance/altinity-kb-merges-memory-limit-loop.md b/content/en/altinity-kb-setup-and-maintenance/altinity-kb-merges-memory-limit-loop.md index 386115e388..c9e2e75cd4 100644 --- a/content/en/altinity-kb-setup-and-maintenance/altinity-kb-merges-memory-limit-loop.md +++ b/content/en/altinity-kb-setup-and-maintenance/altinity-kb-merges-memory-limit-loop.md @@ -9,7 +9,7 @@ keywords: - index_granularity --- -A ClickHouse® `ReplicatedMergeTree` merge can repeatedly fail with `MEMORY_LIMIT_EXCEEDED`, consuming CPU and I/O even when query load is low. This article was checked on 25.8.16.34. +A ClickHouse® `ReplicatedMergeTree` merge can repeatedly fail with `MEMORY_LIMIT_EXCEEDED`, consuming CPU and I/O even when query load is low. The behavior described here was checked against the 24.8, 25.3, 25.8, 26.3 and 26.8 source branches. The SQL examples and workload tests were run on 25.8.16.34. ## Diagnose the problem @@ -45,7 +45,7 @@ Check whether the same entries remain queued, their attempt counts increase, and ## Why merges retry -Replicated merge entries specify their source parts. A failed merge is retried rather than automatically replaced with smaller merges. In 25.8, the retry backoff is capped by `max_postpone_time_for_failed_replicated_merges_ms` (60 seconds by default); actual scheduling can take longer. +Replicated merge entries specify their source parts. A failed merge is retried rather than automatically replaced with smaller merges. Since 25.4, the retry backoff is capped by [`max_postpone_time_for_failed_replicated_merges_ms`](https://github.com/ClickHouse/ClickHouse/blob/25.4/src/Storages/MergeTree/ReplicatedMergeTreeQueue.cpp#L1393-L1420) (60 seconds by default); actual scheduling can take longer. This setting is absent in 24.8 and 25.3. Reducing `max_bytes_to_merge_at_max_space_in_pool` alone may not stop an already queued merge: when the scheduler permits the maximum merge size, it can bypass the size restriction for logged merges ([source](https://github.com/ClickHouse/ClickHouse/blob/v25.8.16.34-lts/src/Storages/MergeTree/ReplicatedMergeTreeQueue.cpp#L1675-L1718)). @@ -55,7 +55,7 @@ Check the memory-limit exception and available server memory. Concurrent merges Increasing `number_of_free_entries_in_pool_to_lower_max_size_of_merge` makes the scheduler lower the eligible merge size earlier as the shared merge/mutation pool fills. This is not a concurrency limit: eligibility also depends on the configured minimum and maximum merge sizes ([source](https://github.com/ClickHouse/ClickHouse/blob/v25.8.16.34-lts/src/Storages/MergeTree/Compaction/CompactionStatistics.cpp#L92-L133)). -The following temporary setting was used on a 25.8.16 deployment with 32 pool slots. Check your actual `background_pool_size` and `background_merges_mutations_concurrency_ratio`, and record the original table setting before changing it. +As a temporary mitigation, consider a threshold close to the pool capacity (`background_pool_size` × `background_merges_mutations_concurrency_ratio`). For example, 31 was used on a 25.8 deployment with 32 slots. Check the capacity on each replica and record the original table setting before changing it. ```sql ALTER TABLE db.table ON CLUSTER '{cluster}' @@ -86,7 +86,7 @@ As a last resort, `DROP PARTITION` deletes data across replicas. Use it only aft Granules may contain much more data than expected when row sizes vary widely and sorting groups large rows together. Vertical merges can still require substantial memory when reading wide non-key columns such as `Map` attributes. Compressed part size alone is not a reliable memory estimate. -For new tables with this workload, test `index_granularity = 1024` or `index_granularity_bytes = 1048576`. In the author's 25.8.16.34 vertical-merge test, these settings reduced the first merge peak from 1.49 GiB to 397 MiB and 450 MiB, respectively. Both settings are [read-only after table creation in 25.8](https://github.com/ClickHouse/ClickHouse/blob/v25.8.16.34-lts/src/Storages/MergeTree/MergeTreeSettings.cpp#L2479-L2487), so create a new table and migrate data as needed. +For new tables with this workload, test `index_granularity = 1024` or `index_granularity_bytes = 1048576`. In the author's 25.8.16.34 vertical-merge test, these settings reduced the first merge peak from 1.49 GiB to 397 MiB and 450 MiB, respectively. Both settings are read-only after table creation for `ReplicatedMergeTree` in the checked versions ([24.8 source](https://github.com/ClickHouse/ClickHouse/blob/24.8/src/Storages/MergeTree/MergeTreeSettings.cpp#L122-L125), [26.8 source](https://github.com/ClickHouse/ClickHouse/blob/26.8/src/Storages/MergeTree/MergeTreeSettings.cpp#L3166-L3181)), so create a new table and migrate data as needed. Reducing `merge_max_block_size` helped subsequent merges in the test when set at creation, but did not reduce peak memory after an `ALTER` on the existing table. Reducing `merge_max_block_size_bytes` alone did not help in this test. From 88b8b6b92dcf99af0c91d40767f1f797633a6b9e Mon Sep 17 00:00:00 2001 From: BorisTyshkevich <125603338+BorisTyshkevich@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:02:14 +0100 Subject: [PATCH 4/5] Document detach/attach as a data-preserving alternative to dropping a partition Explain the replicated DROP_RANGE mechanism, empty detached-part precondition, completeness and duplicate-data risks, and the need to reduce subsequent merge sizes. Mark the approach as source-verified but not runtime-tested for this failure scenario; do not add an untested executable recovery recipe. --- .../altinity-kb-merges-memory-limit-loop.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/content/en/altinity-kb-setup-and-maintenance/altinity-kb-merges-memory-limit-loop.md b/content/en/altinity-kb-setup-and-maintenance/altinity-kb-merges-memory-limit-loop.md index c9e2e75cd4..b2de807a41 100644 --- a/content/en/altinity-kb-setup-and-maintenance/altinity-kb-merges-memory-limit-loop.md +++ b/content/en/altinity-kb-setup-and-maintenance/altinity-kb-merges-memory-limit-loop.md @@ -79,9 +79,13 @@ Cancelled merges can log error 236 (`ABORTED`). Several large merges may still r If a single merge still exceeds available memory, increase memory headroom or consider whether a healthy replica can complete the merge and provide the resulting part for fetching. {{% alert title="Warning" color="warning" %}} -As a last resort, `DROP PARTITION` deletes data across replicas. Use it only after confirming that all data in the partition is disposable and that retention and backup requirements are satisfied. Partition age alone does not prove that every row has expired. +Partition operations affect all replicas. `DETACH PARTITION` makes the data temporarily unavailable; attaching incomplete or unrelated detached parts can cause data loss or duplication. Have a verified backup, pause writes to the partition, resolve pending fetches and mutations affecting its data, and verify that the replica used for recovery has the complete partition. Check that `system.detached_parts` contains no existing parts for the target partition on any replica. Do not delete existing detached parts just to satisfy this condition. {{% /alert %}} +If the data must be retained, consider `DETACH PARTITION` followed by `ATTACH PARTITION` instead of dropping it. Detaching cancels covered merges and removes their queue entries while preserving local active parts ([source](https://github.com/ClickHouse/ClickHouse/blob/v25.8.16.34-lts/src/Storages/StorageReplicatedMergeTree.cpp#L2722-L2792)). Reattach from one verified complete replica per shard, not independently on every replica. Reduce the size of newly selected merges before reattaching; otherwise the same memory failure may recur. This recovery approach is source-verified but has not been tested for this failure scenario. See [partition operations](https://clickhouse.com/docs/sql-reference/statements/alter/partition). + +Use `DROP PARTITION` only if all data in the partition is disposable. Partition age alone does not prove that every row has expired. + ## Reduce merge memory for wide rows Granules may contain much more data than expected when row sizes vary widely and sorting groups large rows together. Vertical merges can still require substantial memory when reading wide non-key columns such as `Map` attributes. Compressed part size alone is not a reliable memory estimate. From a7a47cb1d3fb88f084bca73a2927b2d150edb79d Mon Sep 17 00:00:00 2001 From: BorisTyshkevich <125603338+BorisTyshkevich@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:10:14 +0100 Subject: [PATCH 5/5] Add tested DETACH/ATTACH results, pre-25.4 retry behavior, fetch thresholds Co-Authored-By: Claude Opus 5.5 --- .../altinity-kb-merges-memory-limit-loop.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/content/en/altinity-kb-setup-and-maintenance/altinity-kb-merges-memory-limit-loop.md b/content/en/altinity-kb-setup-and-maintenance/altinity-kb-merges-memory-limit-loop.md index b2de807a41..4392466d5b 100644 --- a/content/en/altinity-kb-setup-and-maintenance/altinity-kb-merges-memory-limit-loop.md +++ b/content/en/altinity-kb-setup-and-maintenance/altinity-kb-merges-memory-limit-loop.md @@ -33,7 +33,7 @@ HAVING failed > 0 ORDER BY event_date, failed DESC ``` -Find queued merge entries with many attempts and a memory-limit exception: +Find queued merge entries with many attempts and a memory-limit exception (also useful as an alert): ```sql SELECT database, table, new_part_name, num_tries, num_postponed, last_exception @@ -45,7 +45,7 @@ Check whether the same entries remain queued, their attempt counts increase, and ## Why merges retry -Replicated merge entries specify their source parts. A failed merge is retried rather than automatically replaced with smaller merges. Since 25.4, the retry backoff is capped by [`max_postpone_time_for_failed_replicated_merges_ms`](https://github.com/ClickHouse/ClickHouse/blob/25.4/src/Storages/MergeTree/ReplicatedMergeTreeQueue.cpp#L1393-L1420) (60 seconds by default); actual scheduling can take longer. This setting is absent in 24.8 and 25.3. +Replicated merge entries specify their source parts. A failed merge is retried rather than automatically replaced with smaller merges. Since 25.4, the retry backoff is capped by [`max_postpone_time_for_failed_replicated_merges_ms`](https://github.com/ClickHouse/ClickHouse/blob/25.4/src/Storages/MergeTree/ReplicatedMergeTreeQueue.cpp#L1393-L1420) (60 seconds by default); actual scheduling can take longer. In 24.8 and 25.3 there is no such backoff: a failed merge is retried at the next scheduling pass. Reducing `max_bytes_to_merge_at_max_space_in_pool` alone may not stop an already queued merge: when the scheduler permits the maximum merge size, it can bypass the size restriction for logged merges ([source](https://github.com/ClickHouse/ClickHouse/blob/v25.8.16.34-lts/src/Storages/MergeTree/ReplicatedMergeTreeQueue.cpp#L1675-L1718)). @@ -76,13 +76,15 @@ SYSTEM START MERGES db.table; Cancelled merges can log error 236 (`ABORTED`). Several large merges may still run concurrently. Monitor memory, queued merge attempts and active part counts; stopping or restricting merges for too long can cause insert failures. Restore the original setting after recovery (use `RESET SETTING` only if no table-specific value was configured before). -If a single merge still exceeds available memory, increase memory headroom or consider whether a healthy replica can complete the merge and provide the resulting part for fetching. +If a single merge still exceeds available memory, increase memory headroom. One replica is enough: when one replica completes the merge, the other replicas fetch the result instead of merging it themselves. By default this happens when the source parts take at least `prefer_fetch_merged_part_size_threshold` (10 GiB) on disk and the entry is older than `prefer_fetch_merged_part_time_threshold` (1 hour) ([source](https://github.com/ClickHouse/ClickHouse/blob/v25.8.16.34-lts/src/Storages/MergeTree/MergeFromLogEntryTask.cpp#L209-L223)). {{% alert title="Warning" color="warning" %}} Partition operations affect all replicas. `DETACH PARTITION` makes the data temporarily unavailable; attaching incomplete or unrelated detached parts can cause data loss or duplication. Have a verified backup, pause writes to the partition, resolve pending fetches and mutations affecting its data, and verify that the replica used for recovery has the complete partition. Check that `system.detached_parts` contains no existing parts for the target partition on any replica. Do not delete existing detached parts just to satisfy this condition. {{% /alert %}} -If the data must be retained, consider `DETACH PARTITION` followed by `ATTACH PARTITION` instead of dropping it. Detaching cancels covered merges and removes their queue entries while preserving local active parts ([source](https://github.com/ClickHouse/ClickHouse/blob/v25.8.16.34-lts/src/Storages/StorageReplicatedMergeTree.cpp#L2722-L2792)). Reattach from one verified complete replica per shard, not independently on every replica. Reduce the size of newly selected merges before reattaching; otherwise the same memory failure may recur. This recovery approach is source-verified but has not been tested for this failure scenario. See [partition operations](https://clickhouse.com/docs/sql-reference/statements/alter/partition). +If the data must be retained, consider `DETACH PARTITION` followed by `ATTACH PARTITION` instead of dropping it. Detaching cancels covered merges and removes their queue entries on all replicas, and moves the parts to `detached/` on each replica ([source](https://github.com/ClickHouse/ClickHouse/blob/v25.8.16.34-lts/src/Storages/StorageReplicatedMergeTree.cpp#L2722-L2792)). Run `ATTACH PARTITION` on one verified complete replica per shard, not on every replica. In a 25.8.16.34 test, this restored all rows on both replicas without duplicates; the other replica attached its own matching detached copies instead of fetching them. The attached parts get new names. + +This removes the failing entry but does not make the next merge smaller. In the same test, the attached parts were selected for merging again and failed with code 241 within a minute. Lowering `max_bytes_to_merge_at_max_space_in_pool` did not prevent it, because that setting limits compressed part size, not merge memory. Attach the parts only after memory per merge is reduced (more memory, or smaller granules as described below). See [partition operations](https://clickhouse.com/docs/sql-reference/statements/alter/partition). Use `DROP PARTITION` only if all data in the partition is disposable. Partition age alone does not prove that every row has expired. @@ -90,7 +92,7 @@ Use `DROP PARTITION` only if all data in the partition is disposable. Partition Granules may contain much more data than expected when row sizes vary widely and sorting groups large rows together. Vertical merges can still require substantial memory when reading wide non-key columns such as `Map` attributes. Compressed part size alone is not a reliable memory estimate. -For new tables with this workload, test `index_granularity = 1024` or `index_granularity_bytes = 1048576`. In the author's 25.8.16.34 vertical-merge test, these settings reduced the first merge peak from 1.49 GiB to 397 MiB and 450 MiB, respectively. Both settings are read-only after table creation for `ReplicatedMergeTree` in the checked versions ([24.8 source](https://github.com/ClickHouse/ClickHouse/blob/24.8/src/Storages/MergeTree/MergeTreeSettings.cpp#L122-L125), [26.8 source](https://github.com/ClickHouse/ClickHouse/blob/26.8/src/Storages/MergeTree/MergeTreeSettings.cpp#L3166-L3181)), so create a new table and migrate data as needed. +For new tables with this workload, test `index_granularity = 1024` or `index_granularity_bytes = 1048576`. In the author's 25.8.16.34 vertical-merge test, these settings reduced the peak of later merges from 844 MiB to 120 MiB and 132 MiB, respectively (first merge: from 1.49 GiB to 397 MiB and 450 MiB). Both settings are read-only after table creation for `ReplicatedMergeTree` in the checked versions ([24.8 source](https://github.com/ClickHouse/ClickHouse/blob/24.8/src/Storages/MergeTree/MergeTreeSettings.cpp#L122-L125), [26.8 source](https://github.com/ClickHouse/ClickHouse/blob/26.8/src/Storages/MergeTree/MergeTreeSettings.cpp#L3166-L3181)), so create a new table and migrate data as needed. Reducing `merge_max_block_size` helped subsequent merges in the test when set at creation, but did not reduce peak memory after an `ALTER` on the existing table. Reducing `merge_max_block_size_bytes` alone did not help in this test.