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..4392466d5b --- /dev/null +++ b/content/en/altinity-kb-setup-and-maintenance/altinity-kb-merges-memory-limit-loop.md @@ -0,0 +1,108 @@ +--- +title: "Repeated MEMORY_LIMIT_EXCEEDED during replicated merges" +linkTitle: "Repeated merge memory failures" +description: > + 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® `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 + +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. + +Daily merge outcomes (includes failures other than code 241 and the peak across all recorded merges): + +```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 +``` + +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 +FROM system.replication_queue +WHERE type = 'MERGE_PARTS' AND num_tries > 10 AND last_exception LIKE '%MEMORY_LIMIT_EXCEEDED%' +``` + +Check whether the same entries remain queued, their attempt counts increase, and code 241 continues to appear in the part log. + +## 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. 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)). + +## 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)). + +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}' + MODIFY SETTING number_of_free_entries_in_pool_to_lower_max_size_of_merge = 31; +``` + +On each affected replica, stop merges: + +```sql +SYSTEM STOP MERGES db.table; +``` + +Wait for the running merges to disappear from `system.merges` before restarting them: + +```sql +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. 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 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. + +## 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. + +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. + +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](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)