Project: ClickHouse (App Definition and Development / Database)
File: merge-tree-settings.md

slug: /en/operations/settings/merge-tree-settings title: "MergeTree tables settings" The values of `mergetree` settings (for all MergeTree tables) can be viewed in the table `system.mergetreesettings`, they can be overridden in `config.xml` in the `mergetree` section, or set in the `SETTINGS` section of each table. These are example overrides for `maxsuspiciousbroken_parts`: If the number of broken parts in a single partition exceeds the `maxsuspiciousbroken_parts` value, automatic deletion is denied. Possible values: Any positive integer. Default value: 100. Override example in `config.xml`: ``` text <merge_tree> <maxsuspiciousbrokenparts>5</maxsuspiciousbrokenparts> </merge_tree> ``` An example to set in `SETTINGS` for a particular table: ``` sql CREATE TABLE foo ( `A` Int64 ) ENGINE = MergeTree ORDER BY tuple() SETTINGS maxsuspiciousbroken_parts = 500; ``` An example of changing the settings for a specific table with the `ALTER TABLE ... MODIFY SETTING` command: ``` sql ALTER TABLE foo MODIFY SETTING maxsuspiciousbroken_parts = 100; -- reset to default (use value from system.mergetreesettings) ALTER TABLE foo RESET SETTING maxsuspiciousbroken_parts; ``` If the number of active parts in a single partition exceeds the `partstothrow_insert` value, `INSERT` is interrupted with the `Too many parts (N). Merges are processing significantly slower than inserts` exception. Possible values: Any positive integer. Default value: 3000. To achieve maximum performance of `SELECT` queries, it is necessary to minimize the number of parts processed, see . Prior to 23.6 this setting was set to 300. You can set a higher different value, it will reduce the probability of the `Too many parts` error, but at the same time `SELECT` performance might degrade. Also in case of a merge issue (for example, due to insufficient disk space) you will notice it later than it could be with the original 300. If the number of active parts in a single partition exceeds the `partstodelay_insert` value, an `INSERT` artificially slows down. Possible values: Any positive integer. Default value: 1000. ClickHouse artificially executes `INSERT` longer (adds sleep) so that the background merge process can merge parts faster than they are added. If the number of inactive parts in a single partition more than the `inactivepartstothrowinsert` value, `INSERT` is interrupted with the "Too many inactive parts (N). Parts cleaning are processing significantly slower than inserts" exception. Possible values: Any positive integer. Default value: 0 (unlimited). If the number of inactive parts in a single partition in the table at least that many the `inactivepartstodelayinsert` value, an `INSERT` artificially slows down. It is useful when a server fails to clean up parts quickly enough. Possible values: Any positive integer. Default value: 0 (unlimited). The value in seconds, which is used to calculate the `INSERT` delay, if the number of active parts in a single partition exceeds the value. Possible values: Any positive integer. Default value: 1. The delay (in milliseconds) for `INSERT` is calculated by the formula: ```code maxk = partstothrowinsert - partstodelay_insert k = 1 + partscountinpartition - partstodelayinsert delaymilliseconds = pow(maxdelaytoinsert * 1000, k / max_k) ``` For example, if a partition has 299 active parts and partstothrowinsert = 300, partstodelayinsert = 150, maxdelayto_insert = 1, `INSERT` is delayed for `pow( 1 * 1000, (1 + 299 - 150) / (300 - 150) ) = 1000` milliseconds. Starting from version

formula has been changed to: ```code allowedpartsoverthreshold = partstothrowinsert - partstodelay_insert partsoverthreshold = partscountinpartition - partstodelayinsert + 1 delaymilliseconds = max(mindelaytoinsertms, (maxdelaytoinsert 1000) partsoverthreshold / allowedpartsover_threshold) ``` For example, if a partition has 224 active parts and partstothrowinsert = 300, partstodelayinsert = 150, maxdelaytoinsert = 1, mindelaytoinsert_ms = 10, `INSERT` is delayed for `max( 10, 1 1000 (224 - 150 + 1) / (300 - 150) ) = 500` milliseconds. If the total number of active parts in all partitions of a table exceeds the `maxpartsin_total` value `INSERT` is interrupted with the `Too many parts (N)` exception. Possible values: Any positive integer. Default value: 100000. A large number of parts in a table reduces performance of ClickHouse queries and increases ClickHouse boot time. Most often this is a consequence of an incorrect design (mistakes when choosing a partitioning strategy - too small partitions). If there are a lot of outdated parts cleanup thread will try to delete up to `simultaneouspartsremoval_limit` parts during one iteration. `simultaneouspartsremoval_limit` set to `0` means unlimited. Default value: 0. The number of most recently inserted blocks for which ClickHouse Keeper stores hash sums to check for duplicates. Possible values: Any positive integer. 0 (disable deduplication) Default value: 1000. The `Insert` command creates one or more blocks (parts). For , when writing into replicated tables, ClickHouse writes the hash sums of the created parts into ClickHouse Keeper. Hash sums are stored only for the most recent `replicateddeduplicationwindow` blocks. The oldest hash sums are removed from ClickHouse Keeper. A large number of `replicateddeduplicationwindow` slows down `Inserts` because it needs to compare more entries. The hash sum is calculated from the composition of the field names and types and the data of the inserted part (stream of bytes). The number of the most recently inserted blocks in the non-replicated table for which hash sums are stored to check for duplicates. Possible values: Any positive integer. 0 (disable deduplication). Default value: 0. A deduplication mechanism is used, similar to replicated tables (see setting). The hash sums of the created parts are written to a local file on a disk. The number of seconds after which the hash sums of the inserted blocks are removed from ClickHouse Keeper. Possible values: Any positive integer. Default value: 604800 (1 week). Similar to , `replicateddeduplicationwindowseconds` specifies how long to store hash sums of blocks for insert deduplication. Hash sums older than `replicateddeduplicationwindowseconds` are removed from ClickHouse Keeper, even if they are less than ` replicateddeduplicationwindow`. The time is relative to the time of the most recent record, not to the wall time. If it's the only record it will be stored forever. The number of most recently async inserted blocks for which ClickHouse Keeper stores hash sums to check for duplicates. Possible values: Any positive integer. 0 (disable deduplication for async_inserts) Default value: 10000. The command will be cached in one or more blocks (parts). For , when writing into replicated tables, ClickHouse writes the hash sums of each insert into ClickHouse Keeper. Hash sums are stored only for the most recent `replicateddeduplicationwindowforasync_inserts` blocks. The oldest hash sums are removed from ClickHouse Keeper. A large number of `replicateddeduplicationwindowforasync_inserts` slows down `Async Inserts` because it needs to compare more entries. The hash sum is calculated from the composition of the field names and types and the data of the insert (stream of bytes). The number of seconds after which the hash sums of the async inserts are removed from ClickHouse Keeper. Possible values: Any positive integer. Default value: 604800 (1 week). Similar to , `replicateddeduplicationwindowsecondsforasyncinserts` specifies how long to store hash sums of blocks for async insert deduplication. Hash sums older than `replicateddeduplicationwindowsecondsforasyncinserts` are removed from ClickHouse Keeper, even if they are less than ` replicateddeduplicationwindowforasync_inserts`. The time is relative to the time of the most recent record, not to the wall

If it's the only record it will be stored forever. If true, we cache the hash sums of the async inserts. Possible values: true, false Default value: false. A block bearing multiple async inserts will generate multiple hash sums. When some of the inserts are duplicated, keeper will only return one duplicated hash sum in one RPC, which will cause unnecessary RPC retries. This cache will watch the hash sums path in Keeper. If updates are watched in the Keeper, the cache will update as soon as possible, so that we are able to filter the duplicated inserts in the memory. The minimum interval (in milliseconds) to update the `useasyncblockidscache` Possible values: Any positive integer. Default value: 100. Normally, the `useasyncblockidscache` updates as soon as there are updates in the watching keeper path. However, the cache updates might be too frequent and become a heavy burden. This minimum interval prevents the cache from updating too fast. Note that if we set this value too long, the block with duplicated inserts will have a longer retry time. How many records may be in the ClickHouse Keeper log if there is inactive replica. An inactive replica becomes lost when when this number exceed. Possible values: Any positive integer. Default value: 1000 Keep about this number of last records in ZooKeeper log, even if they are obsolete. It doesn't affect work of tables: used only to diagnose ZooKeeper log before cleaning. Possible values: Any positive integer. Default value: 10 If the time passed since a replication log (ClickHouse Keeper or ZooKeeper) entry creation exceeds this threshold, and the sum of the size of parts is greater than `preferfetchmergedpartsize_threshold`, then prefer fetching merged part from a replica instead of doing merge locally. This is to speed up very long merges. Possible values: Any positive integer. Default value: 3600 If the sum of the size of parts exceeds this threshold and the time since a replication log entry creation is greater than `preferfetchmergedparttime_threshold`, then prefer fetching merged part from a replica instead of doing merge locally. This is to speed up very long merges. Possible values: Any positive integer. Default value: 10,737,418,240 When this setting has a value greater than zero, only a single replica starts the merge immediately, and other replicas wait up to that amount of time to download the result instead of doing merges locally. If the chosen replica doesn't finish the merge during that amount of time, fallback to standard behavior happens. Possible values: Any positive integer. Default value: 0 (seconds) When this setting has a value greater than zero only a single replica starts the merge immediately if merged part on shared storage and `allowremotefszerocopy_replication` is enabled. :::note Zero-copy replication is not ready for production Zero-copy replication is disabled by default in ClickHouse version 22.8 and higher. This feature is not recommended for production use. ::: Possible values: Any positive integer. Default value: 10800 Recompression works slow in most cases, so we don't start merge with recompression until this timeout and trying to fetch recompressed part from replica which assigned this merge with recompression. Possible values: Any positive integer. Default value: 7200 If true, this replica never merges parts and always downloads merged parts from other replicas. Possible values: true, false Default value: false Max broken parts, if more - deny automatic deletion. Possible values: Any positive integer. Default value: 100 Max size of all broken parts, if more - deny automatic deletion. Possible values: Any positive

Default value: 1,073,741,824 Do not apply ALTER if number of files for modification(deletion, addition) is greater than this setting. Possible values: Any positive integer. Default value: 75 Do not apply ALTER, if the number of files for deletion is greater than this setting. Possible values: Any positive integer. Default value: 50 If the ratio of wrong parts to total number of parts is less than this - allow to start. Possible values: Float, 0.0 - 1.0 Default value: 0.5 Limit parallel fetches from endpoint (actually pool size). Possible values: Any positive integer. Default value: 15 HTTP connection timeout for part fetch requests. Inherited from default profile `httpconnectiontimeout` if not set explicitly. Possible values: Any positive integer. Default value: Inherited from default profile `httpconnectiontimeout` if not set explicitly. If true, replicated tables replicas on this node will try to acquire leadership. Possible values: true, false Default value: true ZooKeeper session expiration check period, in seconds. Possible values: Any positive integer. Default value: 60 Do not remove old local parts when repairing lost replica. Possible values: true, false Default value: true HTTP connection timeout (in seconds) for part fetch requests. Inherited from default profile if not set explicitly. Possible values: Any positive integer. 0 - Use value of `httpconnectiontimeout`. Default value: 0. HTTP send timeout (in seconds) for part fetch requests. Inherited from default profile if not set explicitly. Possible values: Any positive integer. 0 - Use value of `httpsendtimeout`. Default value: 0. HTTP receive timeout (in seconds) for fetch part requests. Inherited from default profile if not set explicitly. Possible values: Any positive integer. 0 - Use value of `httpreceivetimeout`. Default value: 0. Limits the maximum speed of data exchange over the network in bytes per second for fetches. This setting is applied to a particular table, unlike the setting, which is applied to the server. You can limit both server network and network for a particular table, but for this the value of the table-level setting should be less than server-level one. Otherwise the server considers only the `maxreplicatedfetchesnetworkbandwidthforserver` setting. The setting isn't followed perfectly accurately. Possible values: Positive integer. 0 Unlimited. Default value: `0`. Usage Could be used for throttling speed when replicating data to add or replace new nodes. Limits the maximum speed of data exchange over the network in bytes per second for sends. This setting is applied to a particular table, unlike the setting, which is applied to the server. You can limit both server network and network for a particular table, but for this the value of the table-level setting should be less than server-level one. Otherwise the server considers only the `maxreplicatedsendsnetworkbandwidthforserver` setting. The setting isn't followed perfectly accurately. Possible values: Positive integer. 0 Unlimited. Default value: `0`. Usage Could be used for throttling speed when replicating data to add or replace new nodes. The time (in seconds) of storing inactive parts to protect against data loss during spontaneous server reboots. Possible values: Any positive integer. Default value: 480. After merging several parts into a new part, ClickHouse marks the original parts as inactive and deletes them only after `oldpartslifetime` seconds. Inactive parts are removed if they are not used by current queries, i.e. if the `refcount` of the part is 1. `fsync` is not called for new parts, so for some time new parts exist only in the server's RAM (OS cache). If the server is rebooted spontaneously, new parts can be lost or damaged. To protect data inactive parts are not deleted

During startup ClickHouse checks the integrity of the parts. If the merged part is damaged ClickHouse returns the inactive parts to the active list, and later merges them again. Then the damaged part is renamed (the `broken_` prefix is added) and moved to the `detached` folder. If the merged part is not damaged, then the original inactive parts are renamed (the `ignored_` prefix is added) and moved to the `detached` folder. The default `dirtyexpirecentisecs` value (a Linux kernel setting) is 30 seconds (the maximum time that written data is stored only in RAM), but under heavy loads on the disk system data can be written much later. Experimentally, a value of 480 seconds was chosen for `oldpartslifetime`, during which a new part is guaranteed to be written to disk. The maximum total parts size (in bytes) to be merged into one part, if there are enough resources available. `maxbytestomergeatmaxspaceinpool` -- roughly corresponds to the maximum possible part size created by an automatic background merge. Possible values: Any positive integer. Default value: 161061273600 (150 GB). The merge scheduler periodically analyzes the sizes and number of parts in partitions, and if there is enough free resources in the pool, it starts background merges. Merges occur until the total size of the source parts is larger than `maxbytestomergeatmaxspaceinpool`. Merges initiated by ignore `maxbytestomergeatmaxspaceinpool` and merge parts only taking into account available resources (free disk's space) until one part remains in the partition. The maximum total part size (in bytes) to be merged into one part, with the minimum available resources in the background pool. Possible values: Any positive integer. Default value: 1048576 (1 MB) `maxbytestomergeatminspaceinpool` defines the maximum total size of parts which can be merged despite the lack of available disk space (in pool). This is necessary to reduce the number of small parts and the chance of `Too many parts` errors. Merges book disk space by doubling the total merged parts sizes. Thus, with a small amount of free disk space, a situation may happen that there is free space, but this space is already booked by ongoing large merges, so other merges unable to start, and the number of small parts grows with every insert. The number of rows that are read from the merged parts into memory. Possible values: Any positive integer. Default value: 8192 Merge reads rows from parts in blocks of `mergemaxblocksize` rows, then merges and writes the result into a new part. The read block is placed in RAM, so `mergemaxblocksize` affects the size of the RAM required for the merge. Thus, merges can consume a large amount of RAM for tables with very wide rows (if the average row size is 100kb, then when merging 10 parts, (100kb 10 8192) = ~ 8GB of RAM). By decreasing `mergemaxblock_size`, you can reduce the amount of RAM required for a merge but slow down a merge. When there is less than specified number of free entries in pool (or replicated queue), start to lower maximum size of merge to process (or to put in queue). This is to allow small merges to process - not filling the pool with long running merges. Possible values: Any positive integer. Default value: 8 When there is less than specified number of free entries in pool, do not execute part mutations. This is to leave free threads for regular merges and avoid "Too many parts". Possible values: Any positive

Default value: 20 Usage The value of the `numberoffreeentriesinpooltoexecutemutation` setting should be less than the value of the * . Otherwise, ClickHouse throws an exception. The maximum number of threads that read parts when ClickHouse starts. Possible values: Any positive integer. Default value: auto (number of CPU cores). During startup ClickHouse reads all parts of all tables (reads files with metadata of parts) to build a list of all parts in memory. In some systems with a large number of parts this process can take a long time, and this time might be shortened by increasing `maxpartloading_threads` (if this process is not CPU and disk I/O bound). Limits the maximum number of partitions that can be accessed in one query. The setting value specified when the table is created can be overridden via query-level setting. Possible values: Any positive integer. Default value: -1 (unlimited). Merge parts if every part in the range is older than the value of `minagetoforcemerge_seconds`. Possible values: Positive integer. Default value: 0 Disabled. Whether `minagetoforcemerge_seconds` should be applied only on the entire partition and not on subset. Possible values: true, false Default value: false When there is less than specified number of free entries in pool, do not execute optimizing entire partition in the background (this task generated when set `minagetoforcemergeseconds` and enable `minagetoforcemergeonpartitiononly`). This is to leave free threads for regular merges and avoid "Too many parts". Possible values: Positive integer. Default value: 25 The value of the `numberoffreeentriesinpooltoexecuteoptimizeentirepartition` setting should be less than the value of the * . Otherwise, ClickHouse throws an exception. Enables to allow floating-point number as a partition key. Possible values: 0 Floating-point partition key not allowed. 1 Floating-point partition key allowed. Default value: `0`. Enables the check at table creation, that the data type of a column for sampling or sampling expression is correct. The data type must be one of unsigned : `UInt8`, `UInt16`, `UInt32`, `UInt64`. Possible values: true The check is enabled. false The check is disabled at table creation. Default value: `true`. By default, the ClickHouse server checks at table creation the data type of a column for sampling or sampling expression. If you already have tables with incorrect sampling expression and do not want the server to raise an exception during startup, set `checksamplecolumniscorrect` to `false`. Sets minimal amount of bytes to enable balancing when distributing new big parts over volume disks . Possible values: Positive integer. 0 Balancing is disabled. Default value: `0`. Usage The value of the `minbytestorebalancepartitionoverjbod` setting should not be less than the value of the / 1024. Otherwise, ClickHouse throws an exception. Enables or disables detaching a data part on a replica after a merge or a mutation, if it is not byte-identical to data parts on other replicas. If disabled, the data part is removed. Activate this setting if you want to analyze such parts later. The setting is applicable to `MergeTree` tables with enabled . Possible values: 0 Parts are removed. 1 Parts are detached. Default value: `0`. Sets the interval in seconds for ClickHouse to execute the cleanup of old temporary directories. Possible values: Any positive integer. Default value: `60` seconds. Sets the interval in seconds for ClickHouse to execute the cleanup of old parts, WALs, and mutations. Possible values: Any positive integer. Default value: `1` second. Max number of concurrently executed queries related to the MergeTree table. Queries will still be limited by other `maxconcurrentqueries` settings. Possible values: Positive integer. 0 No limit. Default value: `0` (no

Example ``` xml <maxconcurrentqueries>50</maxconcurrentqueries> ``` The minimal number of marks read by the query for applying the setting. Note that queries will still be limited by other `maxconcurrentqueries` settings. Possible values: Positive integer. 0 Disabled (`maxconcurrentqueries` limit applied to no queries). Default value: `0` (limit never applied). Example ``` xml <minmarkstohonormaxconcurrentqueries>10</minmarkstohonormaxconcurrentqueries> ``` Minimal ratio of the number of default values to the number of all values in a column. Setting this value causes the column to be stored using sparse serializations. If a column is sparse (contains mostly zeros), ClickHouse can encode it in a sparse format and automatically optimize calculations - the data does not require full decompression during queries. To enable this sparse serialization, define the `ratioofdefaultsforsparse_serialization` setting to be less than 1.0. If the value is greater than or equal to 1.0, then the columns will be always written using the normal full serialization. Possible values: Float between 0 and 1 to enable sparse serialization 1.0 (or greater) if you do not want to use sparse serialization Default value: `0.9375` Example Notice the `s` column in the following table is an empty string for 95% of the rows. In `myregulartable` we do not use sparse serialization, and in `mysparsetable` we set `ratioofdefaultsforsparse_serialization` to 0.95: ```sql CREATE TABLE myregulartable ( `id` UInt64, `s` String ) ENGINE = MergeTree ORDER BY id; INSERT INTO myregulartable SELECT number AS id, number % 20 = 0 ? toString(number): '' AS s FROM numbers(10000000); CREATE TABLE mysparsetable ( `id` UInt64, `s` String ) ENGINE = MergeTree ORDER BY id SETTINGS ratioofdefaultsforsparse_serialization = 0.95; INSERT INTO mysparsetable SELECT number, number % 20 = 0 ? toString(number): '' FROM numbers(10000000); ``` Notice the `s` column in `mysparsetable` uses less storage space on disk: ```sql SELECT table, name, datacompressedbytes, datauncompressedbytes FROM system.columns WHERE table LIKE 'my%table'; ``` ```response tablenamedatacompressedbytesdatauncompressedbytes myregulartable id 37790741 75488328 myregulartable s 2451377 12683106 mysparsetable id 37790741 75488328 mysparsetable s 2283454 9855751 ``` You can verify if a column is using the sparse encoding by viewing the `serializationkind` column of the `system.partscolumns` table: ```sql SELECT column, serializationkind FROM system.partscolumns WHERE table LIKE 'mysparsetable'; ``` You can see which parts of `s` were stored using the sparse serialization: ```response columnserialization_kind id Default s Default id Default s Default id Default s Sparse id Default s Sparse id Default s Sparse id Default s Sparse id Default s Sparse id Default s Sparse id Default s Sparse id Default s Sparse id Default s Sparse ``` If the file name for column is too long (more than `maxfilename_length` bytes) replace it to SipHash128. Default value: `false`. The maximal length of the file name to keep it as is without hashing. Takes effect only if setting `replacelongfilenameto_hash` is enabled. The value of this setting does not include the length of file extension. So, it is recommended to set it below the maximum filename length (usually 255 bytes) with some gap to avoid filesystem errors. Default value: 127. Persists virtual column `blocknumber` on merges. Default value: false. If enabled, estimated actual size of data parts (i.e., excluding those rows that have been deleted through `DELETE FROM`) will be used when selecting parts to merge. Note that this behavior is only triggered for data parts affected by `DELETE FROM` executed after this setting is enabled. Possible values: true, false Default value: false See Also setting If enabled along with , deleted rows count for existing data parts will be calculated during table starting up. Note that it may slow down start up table loading. Possible values: true, false Default value: false See Also setting