Skip to content

LowCardinality vs index_granularity #98968

Closed

Description

@bobrik

Company or project name

No response

Question

I have a table that is used for lookups by primary key:

CREATE TABLE stack_map_v2_staging_replica
(
    `id` UInt128 CODEC(NONE),
    `stack` Array(LowCardinality(String)) CODEC(ZSTD(1)),
    `seen` datetime CODEC(ZSTD(1)),
)
ENGINE = ReplacingMergeTree(seen)
PRIMARY KEY (id, stack)

It turned out to be rather slow with the default index granularity when looking up 10000 random ids, so I lowered the granularity down to 32:

CREATE TABLE stack_map_v2_fine_granularity_staging_replica
(
    `id` UInt128 CODEC(NONE),
    `stack` Array(LowCardinality(String)) CODEC(ZSTD(1)),
    `seen` datetime CODEC(ZSTD(1)),
)
ENGINE = ReplacingMergeTree(seen)
PRIMARY KEY (id, stack)
SETTINGS index_granularity = 32

The interesting thing is that the new table is more than 2x bigger than the old one, exclusively due to stack:

SELECT
    `table`,
    column,
    sum(rows) AS rows,
    sum(column_data_uncompressed_bytes) AS uncompressed,
    sum(column_data_compressed_bytes) AS compressed,
    toDecimal64(uncompressed / rows, 2) AS uncompressed_per_row,
    toDecimal64(compressed / rows, 2) AS compressed_per_row,
    toDecimal64(uncompressed / compressed, 2) AS compression_ratio
FROM system.parts_columns
WHERE (`table` IN ('stack_map_v2_staging_replica', 'stack_map_v2_fine_granularity_staging_replica')) AND (database = 'r0') AND active
GROUP BY
    `table`,
    column,
    column_position,
    type
ORDER BY
    `table` ASC,
    column_position ASC
SETTINGS output_format_decimal_trailing_zeros = 1
   ┌─table─────────────────────────────────────────┬─column─┬─────rows─┬─uncompressed─┬──compressed─┬─uncompressed_per_row─┬─compressed_per_row─┬─compression_ratio─┐
1. │ stack_map_v2_fine_granularity_staging_replica │ id     │ 59013307 │    943170144 │   943530044 │                15.98 │              15.98 │              0.99 │
2. │ stack_map_v2_fine_granularity_staging_replica │ stack  │ 59013307 │ 175267577852 │ 22782374373 │              2969.96 │             386.05 │              7.69 │
3. │ stack_map_v2_fine_granularity_staging_replica │ seen   │ 59013307 │    235792536 │    80619729 │                 3.99 │               1.36 │              2.92 │
4. │ stack_map_v2_staging_replica                  │ id     │ 64879009 │   1038064144 │  1038262319 │                16.00 │              16.00 │              0.99 │
5. │ stack_map_v2_staging_replica                  │ stack  │ 64879009 │  77948447028 │ 10678442703 │              1201.44 │             164.59 │              7.29 │
6. │ stack_map_v2_staging_replica                  │ seen   │ 64879009 │    259516036 │    91848672 │                 4.00 │               1.41 │              2.82 │
   └───────────────────────────────────────────────┴────────┴──────────┴──────────────┴─────────────┴──────────────────────┴────────────────────┴───────────────────┘

How come? Are dictionaries maintained per granule and not per part as I expected? Is it something else?

Activity

  1. den-crane commented on Mar 7, 2026

    @den-crane
    Contributor

    Try optimize final for both tables. Each part has its own dictionary.

    In general index_granularity < 256 has a little sense because of compression blocks (64k-1mb).
    With index_granularity=32, there is a high probability that ClickHouse will need to decompress the same amount of data (1 MB) as with index_granularity=256, but will incur a loss due to the bloated primary key size.


    CREATE TABLE stack_map_v2_staging_replica
    (
        `id` UInt128 CODEC(NONE),
        `stack` Array(LowCardinality(String)) CODEC(ZSTD(1)),
        `seen` datetime CODEC(ZSTD(1)),
    )
    ENGINE = ReplacingMergeTree(seen)
    PRIMARY KEY (id, stack)
    settings old_parts_lifetime = 1;
    
    
    insert into stack_map_v2_staging_replica select number, arrayMap(i-> toString(cityHash64((i+1)*number%3333)), range(5)), 1 from numbers(1e7);
    
    optimize table stack_map_v2_staging_replica final;
    
    CREATE TABLE stack_map_v2_fine_granularity_staging_replica
    (
        `id` UInt128 CODEC(NONE),
        `stack` Array(LowCardinality(String)) CODEC(ZSTD(1)),
        `seen` datetime CODEC(ZSTD(1)),
    )
    ENGINE = ReplacingMergeTree(seen)
    PRIMARY KEY (id, stack)
    SETTINGS index_granularity = 32, old_parts_lifetime = 1;
    
    insert into stack_map_v2_fine_granularity_staging_replica select number, arrayMap(i-> toString(cityHash64((i+1)*number%3333)), range(5)), 1 from numbers(1e7);
    
    optimize table stack_map_v2_fine_granularity_staging_replica final;
    
    select table, formatReadableSize(total_bytes), formatReadableSize(total_bytes_uncompressed) from system.tables where name like 'stack_map%';
    ┌─table─────────────────────────────────────────┬─formatReadab⋯otal_bytes)─┬─formatReadab⋯compressed)─┐
    │ stack_map_v2_fine_granularity_staging_replica │ 215.33 MiB               │ 440.03 MiB               │
    │ stack_map_v2_staging_replica                  │ 187.99 MiB               │ 362.76 MiB               │
    └───────────────────────────────────────────────┴──────────────────────────┴──────────────────────────┘
    
  2. bobrik commented on Mar 8, 2026

    @bobrik
    ContributorAuthor

    @den-crane I do see difference between 32 and 128 for the number of rows read:

    • 128:
    executeQuery: Read 2560 rows, 2.21 MiB
    
    • 32:
    executeQuery: Read 1056 rows, 832.83 KiB
    

    If there's a log line that could say that going below 256 is useless, I'd be very interested.


    I have a similar setup at home where I can do DDL at will. I made a snapshot the table and variants with different granule sizes.

    select table,
           count() as parts,
           sum(rows) as rows,
           sum(data_uncompressed_bytes) as uncompressed,
           sum(data_compressed_bytes) as compressed,
           toDecimal64(uncompressed / compressed, 2) AS compression_ratio
      from system.parts
     where table like 'stack_map_v2_snapshot%'
       and active
     group by table
     order by uncompressed
    SETTINGS output_format_decimal_trailing_zeros = 1
    
        ┌─table────────────────────────────────┬─parts─┬────rows─┬─uncompressed─┬─compressed─┬─compression_ratio─┐
     1. │ stack_map_v2_snapshot_131072         │     2 │ 1119552 │    238958876 │   58599299 │              4.07 │
     2. │ stack_map_v2_snapshot_32768          │     2 │ 1124050 │    277094557 │   63885645 │              4.33 │
     3. │ stack_map_v2_snapshot_8192           │     2 │ 1121940 │    461655022 │   87712875 │              5.26 │
     4. │ stack_map_v2_snapshot                │     2 │ 1167417 │    475510076 │   90496839 │              5.25 │ <-- the snapshot I cloned other tables from
     5. │ stack_map_v2_snapshot_4096           │     2 │ 1122633 │    609645279 │  107065844 │              5.69 │
     6. │ stack_map_v2_snapshot_1024_one_dict  │     2 │ 1122615 │    783992170 │  132511058 │              5.91 │ <--low_cardinality_use_single_dictionary_for_part=1
     7. │ stack_map_v2_snapshot_1024           │     2 │ 1125708 │    788438389 │  133058181 │              5.92 │
     8. │ stack_map_v2_snapshot_128            │     2 │ 1122879 │    808644731 │  136353588 │              5.93 │
     9. │ stack_map_v2_snapshot_32_no_stack_pk │     2 │ 1121340 │    816139394 │  137064959 │              5.95 │ <-- no stack column in primary key
    10. │ stack_map_v2_snapshot_32             │     2 │ 1124267 │    817585115 │  137289417 │              5.95 │
        └──────────────────────────────────────┴───────┴─────────┴──────────────┴────────────┴───────────────────┘
    

    Make sure to scroll horizontally for the comments. Note that all have just 2 parts, so not much use doing optimize final.

    There's a 3x difference in uncompressed size between 32 and 128k. There's also sizeable difference even between 4k and 8k.

    We can then compare files on disk to see what drives it for the extreme cases of 32 and 128k:

    root@cube:~# ls -l /mnt/data/clickhouse/data/default/stack_map_v2_snapshot_32/all_1_1_1/
    total 81248
    -rw-r----- 1 101 _ssh      665 Mar  8 03:20 checksums.txt
    -rw-r----- 1 101 _ssh      178 Mar  8 03:20 columns_substreams.txt
    -rw-r----- 1 101 _ssh      104 Mar  8 03:20 columns.txt
    -rw-r----- 1 101 _ssh        6 Mar  8 03:20 count.txt
    -rw-r----- 1 101 _ssh       10 Mar  8 03:20 default_compression_codec.txt
    -rw-r----- 1 101 _ssh  9918312 Mar  8 03:20 id.bin
    -rw-r----- 1 101 _ssh    19639 Mar  8 03:20 id.cmrk2
    -rw-r----- 1 101 _ssh        1 Mar  8 03:20 metadata_version.txt
    -rw-r----- 1 101 _ssh  7574971 Mar  8 03:20 primary.cidx
    -rw-r----- 1 101 _ssh  1676608 Mar  8 03:20 seen.bin
    -rw-r----- 1 101 _ssh    13233 Mar  8 03:20 seen.cmrk2
    -rw-r----- 1 101 _ssh      159 Mar  8 03:20 serialization.json
    -rw-r----- 1 101 _ssh 15403694 Mar  8 03:20 stack.bin
    -rw-r----- 1 101 _ssh    45890 Mar  8 03:20 stack.cmrk2
    -rw-r----- 1 101 _ssh 47808516 Mar  8 03:20 stack.dict.bin
    -rw-r----- 1 101 _ssh     2213 Mar  8 03:20 stack.dict.cmrk2
    -rw-r----- 1 101 _ssh   655477 Mar  8 03:20 stack.size0.bin
    -rw-r----- 1 101 _ssh    20748 Mar  8 03:20 stack.size0.cmrk2
    
    root@cube:~# ls -l /mnt/data/clickhouse/data/default/stack_map_v2_snapshot_131072/all_1_1_1/
    total 31464
    -rw-r----- 1 101 _ssh      649 Mar  8 03:28 checksums.txt
    -rw-r----- 1 101 _ssh      178 Mar  8 03:28 columns_substreams.txt
    -rw-r----- 1 101 _ssh      104 Mar  8 03:28 columns.txt
    -rw-r----- 1 101 _ssh        6 Mar  8 03:28 count.txt
    -rw-r----- 1 101 _ssh       10 Mar  8 03:28 default_compression_codec.txt
    -rw-r----- 1 101 _ssh  9826245 Mar  8 03:28 id.bin
    -rw-r----- 1 101 _ssh      120 Mar  8 03:28 id.cmrk2
    -rw-r----- 1 101 _ssh        1 Mar  8 03:28 metadata_version.txt
    -rw-r----- 1 101 _ssh     5566 Mar  8 03:28 primary.cidx
    -rw-r----- 1 101 _ssh  1614152 Mar  8 03:28 seen.bin
    -rw-r----- 1 101 _ssh      127 Mar  8 03:28 seen.cmrk2
    -rw-r----- 1 101 _ssh      159 Mar  8 03:28 serialization.json
    -rw-r----- 1 101 _ssh 18225487 Mar  8 03:28 stack.bin
    -rw-r----- 1 101 _ssh      141 Mar  8 03:28 stack.cmrk2
    -rw-r----- 1 101 _ssh  1842748 Mar  8 03:28 stack.dict.bin
    -rw-r----- 1 101 _ssh      132 Mar  8 03:28 stack.dict.cmrk2
    -rw-r----- 1 101 _ssh   646628 Mar  8 03:28 stack.size0.bin
    -rw-r----- 1 101 _ssh      124 Mar  8 03:28 stack.size0.cmrk2
    

    To highlight the biggest driver:

    root@cube:~# ls -lSh /mnt/data/clickhouse/data/default/stack_map_v2_snapshot_131072/all_1_1_1/ | head -n3
    total 31M
    -rw-r----- 1 101 _ssh  18M Mar  8 03:28 stack.bin
    -rw-r----- 1 101 _ssh 9.4M Mar  8 03:28 id.bin
    root@cube:~# ls -lSh /mnt/data/clickhouse/data/default/stack_map_v2_snapshot_32/all_1_1_1/ | head -n3
    total 80M
    -rw-r----- 1 101 _ssh  46M Mar  8 03:20 stack.dict.bin
    -rw-r----- 1 101 _ssh  15M Mar  8 03:20 stack.bin
    

    It does look like it is driven by the dictionary size, which increased 10x between granule size of 32 and 128k.

    There are 78k unique frames across all stacks with an average stack depth of 90:

    select uniq(stack)
      from stack_map_v2_snapshot array
      join stack
    
    
       ┌─uniq(stack)─┐
    1. │       78809 │
       └─────────────┘
    
    select avg(length(stack))
      from stack_map_v2_snapshot array
      join stack
    
    
       ┌─avg(length(stack))─┐
    1. │  90.62961543606195 │
       └────────────────────┘
    
  3. bobrik commented on Mar 9, 2026

    @bobrik
    ContributorAuthor

    There's something wrong with setting propagation.

    I create a table with the explicit settings:

    CREATE TABLE stack_map_v2_snapshot_32
    (
        `id` UInt128 CODEC(NONE),
        `stack` Array(LowCardinality(String)) CODEC(ZSTD(1)),
        `seen` datetime CODEC(ZSTD(1))
    )
    ENGINE = ReplacingMergeTree(seen)
    PRIMARY KEY (id, stack)
    SETTINGS index_granularity = 32, low_cardinality_max_dictionary_size = 1048576, low_cardinality_use_single_dictionary_for_part = 1

    Then I also set the settings on the session in clickhouse-local for good measure:

    :) set low_cardinality_max_dictionary_size = 1048576
    :) set low_cardinality_use_single_dictionary_for_part = 1
    
    :) select value from system.settings where name in ('low_cardinality_max_dictionary_size', 'low_cardinality_use_single_dictionary_for_part')
    ...
       ┌─value───┐
    1. │ 1048576 │
    2. │ 1       │
       └─────────┘
    

    With the following change:

    diff --git a/src/DataTypes/Serializations/SerializationLowCardinality.cpp b/src/DataTypes/Serializations/SerializationLowCardinality.cpp
    index c7325aab43a..719843c1fb7 100644
    --- a/src/DataTypes/Serializations/SerializationLowCardinality.cpp
    +++ b/src/DataTypes/Serializations/SerializationLowCardinality.cpp
    @@ -477,6 +477,8 @@ void SerializationLowCardinality::serializeBinaryBulkWithMultipleStreams(
         ColumnPtr positions = sub_column->getIndexesPtr();
         ColumnPtr keys = sub_column->getDictionary().getNestedColumn();
     
    +    printf("low_cardinality_max_dictionary_size = %lu, low_cardinality_use_single_dictionary_for_part = %d\n", settings.low_cardinality_max_dictionary_size, settings.low_cardinality_use_single_dictionary_for_part);
    +
         if (settings.low_cardinality_max_dictionary_size)
         {
             /// Insert used_keys into global dictionary and update sub_index.
    

    For this insert:

    :) insert into stack_map_v2_snapshot_32 select * from stack_map_v2_snapshot
    

    I'm getting the default values (lots of lines like this):

    low_cardinality_max_dictionary_size = 8192, low_cardinality_use_single_dictionary_for_part = 0
    low_cardinality_max_dictionary_size = 8192, low_cardinality_use_single_dictionary_for_part = 0
    low_cardinality_max_dictionary_size = 8192, low_cardinality_use_single_dictionary_for_part = 0
    low_cardinality_max_dictionary_size = 8192, low_cardinality_use_single_dictionary_for_part = 0
    

    If I force low_cardinality_use_single_dictionary_for_part=1 in code:

    diff --git a/src/Storages/MergeTree/MergeTreeDataPartWriterWide.cpp b/src/Storages/MergeTree/MergeTreeDataPartWriterWide.cpp
    index 8495063c252..83f321b1882 100644
    --- a/src/Storages/MergeTree/MergeTreeDataPartWriterWide.cpp
    +++ b/src/Storages/MergeTree/MergeTreeDataPartWriterWide.cpp
    @@ -487,7 +487,7 @@ ISerialization::SerializeBinaryBulkSettings MergeTreeDataPartWriterWide::getSeri
         serialize_settings.object_shared_data_serialization_version = settings.object_shared_data_serialization_version;
         serialize_settings.object_shared_data_buckets = settings.object_shared_data_buckets;
         serialize_settings.low_cardinality_max_dictionary_size = settings.low_cardinality_max_dictionary_size;
    -    serialize_settings.low_cardinality_use_single_dictionary_for_part = settings.low_cardinality_use_single_dictionary_for_part;
    +    serialize_settings.low_cardinality_use_single_dictionary_for_part = 1;
         serialize_settings.object_and_dynamic_write_statistics = ISerialization::SerializeBinaryBulkSettings::ObjectAndDynamicStatisticsMode::SUFFIX;
         return serialize_settings;
     }

    Then it does what I expect it to do and the dictionary is shrunk to a reasonable size:

    ivan@cube:~$ ls -l ~/huh/data/default/stack_map_v2_snapshot_32/all_1_1_1/stack.dict.bin ~/huh/data/default/stack_map_v2_snapshot_32_forced/all_1_1_1/stack.dict.bin
    -rw-rw-r-- 1 ivan ivan 40469055 Mar  9 00:05 /home/ivan/huh/data/default/stack_map_v2_snapshot_32/all_1_1_1/stack.dict.bin
    -rw-rw-r-- 1 ivan ivan   155866 Mar  9 00:08 /home/ivan/huh/data/default/stack_map_v2_snapshot_32_forced/all_1_1_1/stack.dict.bin
    
       ┌─table───────────────────────────┬─parts─┬───rows─┬─uncompressed─┬─compressed─┬─compression_ratio─┐
    1. │ stack_map_v2_snapshot           │     1 │ 533423 │    216892645 │   41316087 │              5.24 │
    2. │ stack_map_v2_snapshot_32_forced │     1 │ 533423 │    240727844 │   56381323 │              4.26 │
    3. │ stack_map_v2_snapshot_32        │     1 │ 533423 │    380536785 │   64164632 │              5.93 │
       └─────────────────────────────────┴───────┴────────┴──────────────┴────────────┴───────────────────┘
    

    I suppose this does not explain why index granularity balloons the dictionary size, but it points to the related issue of the compensating levers of low_cardinality_use_single_dictionary_for_part not being connected to anything.

  4. bobrik commented on Mar 9, 2026

    @bobrik
    ContributorAuthor

    Here's a theory: for granule size of 128k the dict overflows in every granule and overflow keys are written and deduplicated per granule. There are only a few granules, so this is rather efficient. For granule size of 32, the dict overflows much more often, which triggers the same process of writing overflow keys per granule that overflows, but there are way more granules, so there are way more dictionaries flushed.

    if (need_additional_keys)
    {
    UInt64 num_keys = keys->size();
    writeBinaryLittleEndian(num_keys, *indexes_stream);
    dict_inner_serialization->serializeBinaryBulk(*keys, *indexes_stream, 0, num_keys);
    }

    While dictionaries are per part, dictionary flushing and overflow keys are per granule (that overflows). Larger granules dampen the effect because they reduce the number of times when a dictionary can be flushed. It's still very much unexpected and there's probably a better way to handle this.

    Ultimately the fix for my data with existing assumptions is low_cardinality_use_single_dictionary_for_part=1 to force one dictionary per part (however large it is), but it seems broken as it never applies, as described in my previous comment.

  5. bobrik commented on Mar 9, 2026

    @bobrik
    ContributorAuthor

    This does the trick:

    diff --git a/src/Storages/MergeTree/MergeTreeIOSettings.cpp b/src/Storages/MergeTree/MergeTreeIOSettings.cpp
    index 9d2fbb21424..e65394fe4cd 100644
    --- a/src/Storages/MergeTree/MergeTreeIOSettings.cpp
    +++ b/src/Storages/MergeTree/MergeTreeIOSettings.cpp
    @@ -54,6 +54,8 @@ namespace MergeTreeSetting
         extern const MergeTreeSettingsNonZeroUInt64 object_shared_data_buckets_for_compact_part;
         extern const MergeTreeSettingsNonZeroUInt64 object_shared_data_buckets_for_wide_part;
         extern const MergeTreeSettingsMergeTreeDynamicSerializationVersion dynamic_serialization_version;
    +    extern const MergeTreeSettingsUInt64 low_cardinality_max_dictionary_size;
    +    extern const MergeTreeSettingsBool low_cardinality_use_single_dictionary_for_part;
     }
     
     MergeTreeWriterSettings::MergeTreeWriterSettings(
    @@ -79,8 +81,8 @@ MergeTreeWriterSettings::MergeTreeWriterSettings(
         , save_primary_index_in_memory(save_primary_index_in_memory_)
         , blocks_are_granules_size(blocks_are_granules_size_)
         , query_write_settings(query_write_settings_)
    -    , low_cardinality_max_dictionary_size(global_settings[Setting::low_cardinality_max_dictionary_size])
    -    , low_cardinality_use_single_dictionary_for_part(global_settings[Setting::low_cardinality_use_single_dictionary_for_part] != 0)
    +    , low_cardinality_max_dictionary_size((*storage_settings)[MergeTreeSetting::low_cardinality_max_dictionary_size] ? (*storage_settings)[MergeTreeSetting::low_cardinality_max_dictionary_size] : global_settings[Setting::low_cardinality_max_dictionary_size])
    +    , low_cardinality_use_single_dictionary_for_part((*storage_settings)[MergeTreeSetting::low_cardinality_use_single_dictionary_for_part] ? (*storage_settings)[MergeTreeSetting::low_cardinality_use_single_dictionary_for_part] != 0 : global_settings[Setting::low_cardinality_use_single_dictionary_for_part] != 0)
         , use_compact_variant_discriminators_serialization((*storage_settings)[MergeTreeSetting::use_compact_variant_discriminators_serialization])
         , dynamic_serialization_version(global_settings[Setting::merge_tree_use_v1_object_and_dynamic_serialization] ? MergeTreeDynamicSerializationVersion::V1 : (*storage_settings)[MergeTreeSetting::dynamic_serialization_version])
         , object_serialization_version(global_settings[Setting::merge_tree_use_v1_object_and_dynamic_serialization] ? MergeTreeObjectSerializationVersion::V1 : (*storage_settings)[MergeTreeSetting::object_serialization_version])
    diff --git a/src/Storages/MergeTree/MergeTreeSettings.cpp b/src/Storages/MergeTree/MergeTreeSettings.cpp
    index b1c4424da11..321f62a9e12 100644
    --- a/src/Storages/MergeTree/MergeTreeSettings.cpp
    +++ b/src/Storages/MergeTree/MergeTreeSettings.cpp
    @@ -64,6 +64,8 @@ namespace ErrorCodes
         setting). The value specified when the table is created overrides the global
         value for this setting.
         )", 0) \
    +    DECLARE(UInt64, low_cardinality_max_dictionary_size, 8192, R"(TBD)", 0) \
    +    DECLARE(Bool, low_cardinality_use_single_dictionary_for_part, 0, R"(TBD)", 0) \
         DECLARE(UInt64, index_granularity, 8192, R"(
         Maximum number of data rows between the marks of an index. I.e how many rows
         correspond to one primary key value.
    
    CREATE TABLE stack_map_v2_snapshot_32
    (
        `id` UInt128 CODEC(NONE),
        `stack` Array(LowCardinality(String)) CODEC(ZSTD(1)),
        `seen` datetime CODEC(ZSTD(1))
    )
    ENGINE = ReplacingMergeTree(seen)
    PRIMARY KEY (id, stack)
    SETTINGS index_granularity = 32, low_cardinality_max_dictionary_size = 1048576, low_cardinality_use_single_dictionary_for_part = 1

    Uncompressed size is now smaller for 32 with settings overrides than for 128k with no overrides:

       ┌─table────────────────────────┬─parts─┬───rows─┬─uncompressed─┬─compressed─┬─compression_ratio─┐
    1. │ stack_map_v2_snapshot_32     │     1 │ 533423 │     71568998 │   25252503 │              2.83 │
    2. │ stack_map_v2_snapshot_131072 │     1 │ 533423 │    111153753 │   27465842 │              4.04 │
    3. │ stack_map_v2_snapshot        │     1 │ 533423 │    216892645 │   41316087 │              5.24 │
       └──────────────────────────────┴───────┴────────┴──────────────┴────────────┴───────────────────┘
    

    The dictionary size for 32 is the same as 128k with no setting overrides:

    ivan@cube:~$ ls -lh ~/huh/data/default/stack_map_v2_snapshot_32/all_1_1_1/stack.dict.bin ~/huh/data/default/stack_map_v2_snapshot_131072/all_1_1_1/stack.dict.bin
    -rw-rw-r-- 1 ivan ivan 1.5M Mar  9 07:05 /home/ivan/huh/data/default/stack_map_v2_snapshot_131072/all_1_1_1/stack.dict.bin
    -rw-rw-r-- 1 ivan ivan 1.5M Mar  9 07:09 /home/ivan/huh/data/default/stack_map_v2_snapshot_32/all_1_1_1/stack.dict.bin
    

    I kind of expected the dict to be smaller too now that we do 1 dict instead of 9 (for 128k), but it's too late to dig into it today.

  6. den-crane commented on Mar 9, 2026

    @den-crane
    Contributor

    @bobrik

    executeQuery: Read 2560 rows, 2.21 MiB
    executeQuery: Read 1056 rows, 832.83 KiB

    I would not trust these numbers much. They are different but it has zero impact on performance.

    CREATE TABLE stack_map_8192
    (
        `id` UInt128 CODEC(NONE),
        `stack` Array(LowCardinality(String)) CODEC(ZSTD(1)),
        `seen` datetime CODEC(ZSTD(1)),
    )
    ENGINE = ReplacingMergeTree(seen)
    PRIMARY KEY (id, stack)
    settings old_parts_lifetime = 1 as 
    select number, arrayMap(i-> toString(cityHash64((i+1)*number%3333)), range(5)), 1 from numbers(1e7);
    
    optimize table stack_map_8192 final;
    
    
    CREATE TABLE stack_map_256 
    (
        `id` UInt128 CODEC(NONE),
        `stack` Array(LowCardinality(String)) CODEC(ZSTD(1)),
        `seen` datetime CODEC(ZSTD(1)),
    )
    ENGINE = ReplacingMergeTree(seen)
    PRIMARY KEY (id, stack)
    SETTINGS index_granularity = 256, old_parts_lifetime = 1 as
    select number, arrayMap(i-> toString(cityHash64((i+1)*number%3333)), range(5)), 1 from numbers(1e7);
    
    optimize table stack_map_256 final;
    
    CREATE TABLE stack_map_32 
    (
        `id` UInt128 CODEC(NONE),
        `stack` Array(LowCardinality(String)) CODEC(ZSTD(1)),
        `seen` datetime CODEC(ZSTD(1)),
    )
    ENGINE = ReplacingMergeTree(seen)
    PRIMARY KEY (id, stack)
    SETTINGS index_granularity = 32, old_parts_lifetime = 1 as
    select number, arrayMap(i-> toString(cityHash64((i+1)*number%3333)), range(5)), 1 from numbers(1e7);
    
    optimize table stack_map_32 final;
    
    
    clickhouse-benchmark  --database=dw -c 100 -i 100000 <<< "select * from stack_map_256 where id = (select rand()%46645) settings max_threads=1"
    queries: 100000, QPS: 4526.260, RPS: 1167582.381, MiB/s: 33.019, result RPS: 4526.260, result MiB/s: 0.794.
    
    0%		0.006 sec.
    10%		0.014 sec.
    20%		0.015 sec.
    30%		0.017 sec.
    40%		0.018 sec.
    50%		0.019 sec.    ------<<<<
    60%		0.020 sec.
    70%		0.021 sec.
    80%		0.022 sec.
    90%		0.025 sec.
    95%		0.026 sec.
    99%		0.031 sec.
    99.9%		0.081 sec.
    99.99%		0.130 sec.
    
    
    clickhouse-benchmark  --database=dw -c 100 -i 100000 <<< "select * from stack_map_32 where id = (select rand()%46645) settings max_threads=1"
    queries: 100000, QPS: 4374.979, RPS: 148764.688, MiB/s: 4.114, result RPS: 4374.979, result MiB/s: 0.767.
    
    0%		0.006 sec.
    10%		0.014 sec.
    20%		0.016 sec.
    30%		0.017 sec.
    40%		0.018 sec.
    50%		0.019 sec.  ------<<<<
    60%		0.020 sec.
    70%		0.022 sec.
    80%		0.023 sec.
    90%		0.025 sec.
    95%		0.027 sec.
    99%		0.032 sec.
    99.9%		0.154 sec.
    99.99%		0.165 sec.
    
    
    clickhouse-benchmark  --database=dw -c 100 -i 100000 <<< "select * from stack_map_8192 where id = (select rand()%46645) settings max_threads=1"
    queries: 100000, QPS: 4360.197, RPS: 35727378.228, MiB/s: 997.028, result RPS: 4360.197, result MiB/s: 0.765.
    
    0%		0.005 sec.
    10%		0.014 sec.
    20%		0.016 sec.
    30%		0.017 sec.
    40%		0.018 sec.
    50%		0.019 sec. ------<<<<
    60%		0.020 sec.
    70%		0.022 sec.
    80%		0.023 sec.
    90%		0.025 sec.
    95%		0.027 sec.
    99%		0.032 sec.
    99.9%		0.141 sec.
    99.99%		0.154 sec.
    
    
    SELECT
        tables[1] AS `table`,
        round(avg(read_bytes), 2) AS _read_bytes,
        round(sum(ProfileEvents['CompressedReadBufferBytes']) / 1000, 2) AS CompressedReadBufferBytes,
        round(sum(ProfileEvents['OSReadChars']) / 1000, 2) AS OSReadChars,
        round(sum(ProfileEvents['ReadCompressedBytes']) / 1000, 2) AS ReadCompressedBytes,
        round(sum(ProfileEvents['UserTimeMicroseconds']) / 1000, 2) AS userCPUms,
        count(),
        round(sum(query_duration_ms), 2) AS _query_duration_ms,
        round(userCPUms / _query_duration_ms, 2) AS cpu_per_sec
    FROM system.query_log
    WHERE (type = 2) AND (event_date >= today()) AND ((tables[1]) LIKE '%stack_map%') AND (query LIKE '%46645%')
    GROUP BY `table`
    
    ┌─table─────────────┬─_read_bytes─┬─CompressedReadBufferBytes─┬─OSReadChars─┬─ReadCompressedBytes─┬─userCPUms─┬─count()─┬─_query_duration_ms─┬─cpu_per_sec─┐
    │ dw.stack_map_32   │      986.07 │               33044169.09 │ 12785593.34 │         12785675.90 │ 268061.90 │  100000 │            1834091 │        0.15 │
    │ dw.stack_map_8192 │   239773.59 │               41210172.86 │ 32311276.54 │         19209820.42 │ 276780.65 │  100000 │            1837878 │        0.15 │
    │ dw.stack_map_256  │     7649.26 │               33160572.86 │ 12686880.77 │         12686900.61 │ 266375.72 │  100000 │            1765821 │        0.15 │
    └───────────────────┴─────────────┴───────────────────────────┴─────────────┴─────────────────────┴───────────┴─────────┴────────────────────┴─────────────┘
    

    _query_duration_ms / CompressedReadBufferBytes -- are the same (and they are sums for 100000 executions).
    From my POV index_granularity has no good impact on performance for this synthetic dataset.

    From my naive understanding: if a table's granule fits into 1Mb then there is no difference how many rows in the granule, 32/256/8192, ClickHouse would process (read/decompress) 1Mb anyway.

    If the average stack size ~1000 bytes, then with index_granularity=8192 => granule_size = ~8MB, has sense to reduce index_granularity 8192 / 8 = 1024 to make granule = 1Mb.

    In my case avg stacks' size is less than 112 bytes.

    select avg(length(toString(stack))) from stack_map_8192;
    112.9528919
    
  7. den-crane commented on Mar 9, 2026

    @den-crane
    Contributor

    There's something wrong with setting propagation.

    It has no sense to use users' settings in DDL.
    ClickHouse allows users' settings because some settings impact on the CREATE TABLE process.

    CREATE TABLE stack_map_v2_snapshot_32
    ...
    SETTINGS index_granularity = 32, low_cardinality_max_dictionary_size = 1048576, low_cardinality_use_single_dictionary_for_part = 1
    

    It works as

    CREATE TABLE stack_map_v2_snapshot_32
    ...
    TABLE SETTINGS index_granularity = 32
    QUERY SETTINGS low_cardinality_max_dictionary_size = 1048576, low_cardinality_use_single_dictionary_for_part = 1
    

    These
    QUERY SETTINGS low_cardinality_max_dictionary_size = 1048576, low_cardinality_use_single_dictionary_for_part = 1
    are noop on CREATE TABLE.

    You need to define low_cardinality_max_dictionary_size/low_cardinality_use_single_dictionary_for_part against insert (query/session/user)

  8. bobrik commented on Mar 10, 2026

    @bobrik
    ContributorAuthor

    I would not trust these numbers much. They are different but it has zero impact on performance.

    These are toy tables. My production table is 150 million entries and I want to look up 100k to 500k ids that I happen to need to resolve at a time. I wouldn't focus too much on the exact granule size until the dictionary ballooning is under control. I will review the exact right number that works for us, but this is secondary to the problem at hand.

    From my naive understanding: if a table's granule fits into 1Mb then there is no difference how many rows in the granule, 32/256/8192, ClickHouse would process (read/decompress) 1Mb anyway.

    The blocks size is different between 32 and 8192 (64k vs 1M):

    root@36ssds1164:~# clickhouse-compressor --stat --input /state/clickhouse/pdx-performance/data/r0/stack_map_v2_staging_replica/all_31853_40751_7/stack.bin | head
    1048576 116899
    1048576 124320
    1048576 137734
    1048576 140750
    1048576 130895
    1048576 113778
    1048576 122968
    1048576 252186
    214054  67789
    1048576 123311
    
    root@36ssds1164:~# clickhouse-compressor --stat --input /state/clickhouse/pdx-performance/data/r0/stack_map_v2_fine_granularity_staging_replica/all_90487_97697_7/stack.bin | head
    69538   23388
    66836   17000
    66207   25538
    125259  29257
    69860   24324
    76792   13780
    98703   31209
    130537  32662
    68662   24241
    116368  32130
    

    You can see that compression ratio is worse, but the uncompressed size is also a lot smaller (#98968 (comment)).

    In my case avg stacks' size is less than 112 bytes.

    That's pre-dictionary. It doesn't matter how long the raw strings are, we are not storing them like that.

    The number is 8423 for me.

    It has no sense to use users' settings in DDL.

    I agree, that's why I put them into CREATE TABLE SETTINGS block, where they do make sense (to me at least), similar to index granularity. It doesn't work there as it's not a table setting as you correctly note.

    It also doesn't work if I set them in the session that does the INSERT query in clickhouse-local:

    CREATE TABLE stack_map_v2_snapshot_32
    (
        `id` UInt128 CODEC(NONE),
        `stack` Array(LowCardinality(String)) CODEC(ZSTD(1)),
        `seen` datetime CODEC(ZSTD(1))
    )
    ENGINE = ReplacingMergeTree(seen)
    PRIMARY KEY (id, stack)
    SETTINGS index_granularity = 32
    
    SET low_cardinality_use_single_dictionary_for_part = 1
    SET low_cardinality_max_dictionary_size = 1048576
    
    SELECT value
    FROM system.settings
    WHERE name IN ('low_cardinality_max_dictionary_size', 'low_cardinality_use_single_dictionary_for_part')
    
    Query id: 425ed620-4d1d-4efa-bfe9-4a4bf9c24299
    
       ┌─value───┐
    1. │ 1048576 │
    2. │ 1       │
       └─────────┘
    
    INSERT INTO stack_map_v2_snapshot_32 SELECT *
    FROM stack_map_v2_snapshot
    

    That's on v26.1.1.1-new. The same sequence produces the same outcome with a proper ClickHouse server v25.10.3.100.

    Maybe it does work as a global setting or a profile setting. From the code that I changed, it looks like global_settings is what's getting consulted, sort of makes sense if you remember that merges happen outside of user sessions and they need to look at the settings to decide how to lay out dictionaries. That's not very flexible though. Table level setting as with my patch feels right.

    cc @KochetovNicolai, please have a look at #98968 (comment) and #98968 (comment) as you seem to be the person who touched a bunch of the related low cardinality code.

  9. bobrik commented on Mar 10, 2026

    @bobrik
    ContributorAuthor

    From #98968 (comment):

    I kind of expected the dict to be smaller too now that we do 1 dict instead of 9 (for 128k), but it's too late to dig into it today.

    They are not exactly the same, just very close:

    ivan@cube:~$ ls -l ~/huh/data/default/stack_map_v2_snapshot_32/all_1_1_1/stack.dict.bin ~/huh/data/default/stack_map_v2_snapshot_131072/all_1_1_1/stack.dict.bin
    -rw-rw-r-- 1 ivan ivan 1534436 Mar  9 07:05 /home/ivan/huh/data/default/stack_map_v2_snapshot_131072/all_1_1_1/stack.dict.bin
    -rw-rw-r-- 1 ivan ivan 1521639 Mar 10 03:27 /home/ivan/huh/data/default/stack_map_v2_snapshot_32/all_1_1_1/stack.dict.bin
    

    There are clearly multiple logical blocks (smaller than 1048576) for 128k:

    ivan@cube:~$ ~/projects/clickhouse/build/programs/clickhouse-compressor --stat --input /home/ivan/huh/data/default/stack_map_v2_snapshot_131072/all_1_1_1/stack.dict.bin
    CODEC(ZSTD(1))  1048576 132973
    CODEC(ZSTD(1))  129213  22861
    CODEC(ZSTD(1))  1048576 130556
    CODEC(ZSTD(1))  165566  24782
    CODEC(ZSTD(1))  1048576 129229
    CODEC(ZSTD(1))  117697  20877
    CODEC(ZSTD(1))  1048576 134290
    CODEC(ZSTD(1))  94096   16337
    CODEC(ZSTD(1))  1048576 125522
    CODEC(ZSTD(1))  229055  30302
    CODEC(ZSTD(1))  1048576 128026
    CODEC(ZSTD(1))  188468  25830
    CODEC(ZSTD(1))  1048576 129981
    CODEC(ZSTD(1))  153559  23589
    CODEC(ZSTD(1))  1048576 139740
    CODEC(ZSTD(1))  79955   12338
    CODEC(ZSTD(1))  1048576 129567
    CODEC(ZSTD(1))  141491  23070
    CODEC(ZSTD(1))  1048576 131035
    CODEC(ZSTD(1))  134162  22607
    CODEC(ZSTD(1))  1482    588
    

    I'm using the same logical block splitting heuristic here as I noted in #96704.

    There's only one logical block for 32 with one dictionary forced via my patch:

    ivan@cube:~$ ~/projects/clickhouse/build/programs/clickhouse-compressor --stat --input /home/ivan/huh/data/default/stack_map_v2_snapshot_32/all_1_1_1/stack.dict.bin
    CODEC(ZSTD(1))  1048576 132977
    CODEC(ZSTD(1))  1048576 155090
    CODEC(ZSTD(1))  1048576 138021
    CODEC(ZSTD(1))  1048576 126706
    CODEC(ZSTD(1))  1048576 139225
    CODEC(ZSTD(1))  1048576 153863
    CODEC(ZSTD(1))  1048576 146383
    CODEC(ZSTD(1))  1048576 141126
    CODEC(ZSTD(1))  1048576 135454
    CODEC(ZSTD(1))  1048576 126417
    CODEC(ZSTD(1))  879444  126201
    

    Decompressing both and checking for duplicates:

    ivan@cube:~$ ~/projects/clickhouse/build/programs/clickhouse-compressor --decompress --input /home/ivan/huh/data/default/stack_map_v2_snapshot_131072/all_1_1_1/stack.dict.bin --output 131072.bin
    ivan@cube:~$ ~/projects/clickhouse/build/programs/clickhouse-compressor --decompress --input /home/ivan/huh/data/default/stack_map_v2_snapshot_32/all_1_1_1/stack.dict.bin --output 32.bin
    

    None for 32:

    ivan@cube:~$ strings 32.bin | sort | uniq -c | sort | tail
          1 zstream_run_func
          1 zstream_run_once
          1 zstream_run_try
          1 ztrycalloc_usable_internal      je_calloc
          1 ztrymalloc_usable_internal
          1 ztryrealloc_usableEv8::internal::NexusConfig::NewHandle(v8::internal::MaybeObject) const.ZSTD_estimateCCtxSize_usingCCtxParams_internal
          1 ztryrealloc_usable_internal
          1 ZUINT64_it      add_orderlDB::UniqToCountPass::run(std::__1::shared_ptr<DB::IQueryTreeNode>&, std::__1::shared_ptr<DB::Context const>)pDB::InDepthQueryTreeVisitorWithContext<DB::UniqToCountVisitor>::visit(std::__1::shared_ptr<DB::IQueryTreeNode>&)xDB::InDepthQueryTreeVisitorWithContext<DB::UniqToCountVisitor>::visitChildren(std::__1::shared_ptr<DB::IQueryTreeNode>&)
          1 zzlFind
          1 zzlInsertAt
    

    At many as 9 for 128k (matching the number of dictionaries/logical blocks):

    ivan@cube:~$ strings 131072.bin | sort | uniq -c | sort | tail
          9 xfs_end_ioend
          9 xfs_file_buffered_read
          9 xfs_file_write_checks
          9 xfs_icreate
          9 xfs_inactive_truncate
          9 xfs_trans_roll
          9 xfs_vn_rename
          9 ___xstat64
          9 ZSTD_buildSeqStore
          9 ZSTD_execSequence
    

    One intuitive thought here is that having 10x number of dictionaries does not make much of a difference. You have to remember to zoom out and see that it does in fact help when you look at the top line number:

       ┌─table────────────────────────┬─parts─┬───rows─┬─uncompressed─┬─compressed─┬─compression_ratio─┐
    1. │ stack_map_v2_snapshot_32     │     1 │ 533423 │     71568998 │   25252503 │              2.83 │
    2. │ stack_map_v2_snapshot_131072 │     1 │ 533423 │    111153753 │   27465842 │              4.04 │
       └──────────────────────────────┴───────┴────────┴──────────────┴────────────┴───────────────────┘
    
    ivan@cube:~$ ls -lh ~/huh/data/default/stack_map_v2_snapshot_32/all_1_1_1/stack.bin ~/huh/data/default/stack_map_v2_snapshot_131072/all_1_1_1/stack.bin
    -rw-rw-r-- 1 ivan ivan 15M Mar  9 07:05 /home/ivan/huh/data/default/stack_map_v2_snapshot_131072/all_1_1_1/stack.bin
    -rw-rw-r-- 1 ivan ivan 13M Mar 10 03:27 /home/ivan/huh/data/default/stack_map_v2_snapshot_32/all_1_1_1/stack.bin
    
  10. bobrik commented on Mar 10, 2026

    @bobrik
    ContributorAuthor

    I deployed this into production for the default profile:

                      +  <low_cardinality_max_dictionary_size>10485760</low_cardinality_max_dictionary_size>
                      +  <low_cardinality_use_single_dictionary_for_part>1</low_cardinality_use_single_dictionary_for_part>
    

    The parts that were merged after a restart show a clear improvement (10x uncompressed size!):

        ┌─table─────────────────────────────────────────┬─part_name───────────┬─column─┬─────rows─┬─uncompressed─┬──compressed─┬─uncompressed_per_row─┬─compressed_per_row─┬─compression_ratio─┐
     1. │ stack_map_v2_fine_granularity_staging_replica │ all_0_48817_8       │ stack  │ 28804267 │  89887069295 │ 11646544310 │              3120.61 │             404.33 │              7.71 │
     2. │ stack_map_v2_fine_granularity_staging_replica │ all_100385_100953_4 │ stack  │  9494466 │   2702744556 │   663803557 │               284.66 │              69.91 │              4.07 │
     3. │ stack_map_v2_fine_granularity_staging_replica │ all_100954_100985_2 │ stack  │  2119344 │    585707044 │   135765036 │               276.36 │              64.05 │              4.31 │
     4. │ stack_map_v2_fine_granularity_staging_replica │ all_100986_101015_2 │ stack  │  2070214 │    574962374 │   133109194 │               277.73 │              64.29 │              4.31 │
     5. │ stack_map_v2_fine_granularity_staging_replica │ all_101016_101021_1 │ stack  │   666312 │    200916516 │    43521739 │               301.53 │              65.31 │              4.61 │
     6. │ stack_map_v2_fine_granularity_staging_replica │ all_101022_101027_1 │ stack  │   664431 │    204703426 │    43794747 │               308.08 │              65.91 │              4.67 │
     7. │ stack_map_v2_fine_granularity_staging_replica │ all_101028_101033_1 │ stack  │   667549 │    204578638 │    44144281 │               306.46 │              66.12 │              4.63 │
     8. │ stack_map_v2_fine_granularity_staging_replica │ all_101034_101034_0 │ stack  │   131087 │     54079737 │    10382884 │               412.54 │              79.20 │              5.20 │
     9. │ stack_map_v2_fine_granularity_staging_replica │ all_48818_82774_8   │ stack  │ 22924043 │  71171633074 │  9187477540 │              3104.67 │             400.77 │              7.74 │
    10. │ stack_map_v2_fine_granularity_staging_replica │ all_82775_99693_8   │ stack  │ 25273112 │  76758373617 │ 10072281680 │              3037.15 │             398.53 │              7.62 │
    11. │ stack_map_v2_fine_granularity_staging_replica │ all_99694_100384_4  │ stack  │  8559139 │  24896545187 │  3316201778 │              2908.76 │             387.44 │              7.50 │
        └───────────────────────────────────────────────┴─────────────────────┴────────┴──────────┴──────────────┴─────────────┴──────────────────────┴────────────────────┴───────────────────┘
    

    Similarly sized part of ~9 million rows (rows 11 and 2 above, respectively):

    • Merged before the change (8.5m rows):
    # ls -lh /state/clickhouse/pdx-performance/data/r0/stack_map_v2_fine_granularity_staging_replica/all_99694_100384_4/stack.{bin,dict.bin}
    -rw-r----- 1 root root 477M Mar 10 08:17 /state/clickhouse/pdx-performance/data/r0/stack_map_v2_fine_granularity_staging_replica/all_99694_100384_4/stack.bin
    -rw-r----- 1 root root 2.7G Mar 10 08:17 /state/clickhouse/pdx-performance/data/r0/stack_map_v2_fine_granularity_staging_replica/all_99694_100384_4/stack.dict.bin
    
    • Merged after the change (9.5m rows):
    # ls -lh /state/clickhouse/pdx-performance/data/r0/stack_map_v2_fine_granularity_staging_replica/all_100385_100953_4/stack.{bin,dict.bin}
    -rw-r----- 1 root root 608M Mar 10 18:57 /state/clickhouse/pdx-performance/data/r0/stack_map_v2_fine_granularity_staging_replica/all_100385_100953_4/stack.bin
    -rw-r----- 1 root root  16M Mar 10 18:57 /state/clickhouse/pdx-performance/data/r0/stack_map_v2_fine_granularity_staging_replica/all_100385_100953_4/stack.dict.bin
    

    Similar-ish sized part from the previous table with index_granularity = 8192 and 11.2m rows:

       ┌─table────────────────────────┬─part_name─────────┬─column─┬─────rows─┬─uncompressed─┬─compressed─┬─uncompressed_per_row─┬─compressed_per_row─┬─compression_ratio─┐
    1. │ stack_map_v2_staging_replica │ all_31853_40751_7 │ stack  │ 11196801 │  13564920591 │ 1863570916 │              1211.49 │             166.43 │              7.27 │
       └──────────────────────────────┴───────────────────┴────────┴──────────┴──────────────┴────────────┴──────────────────────┴────────────────────┴───────────────────┘
    
    # ls -lh /state/clickhouse/pdx-performance/data/r0/stack_map_v2_staging_replica/all_31853_40751_7/stack.{bin,dict.bin}
    -rw-r----- 1 root root 1.6G Mar  5 10:31 /state/clickhouse/pdx-performance/data/r0/stack_map_v2_staging_replica/all_31853_40751_7/stack.bin
    -rw-r----- 1 root root 226M Mar  5 10:31 /state/clickhouse/pdx-performance/data/r0/stack_map_v2_staging_replica/all_31853_40751_7/stack.dict.bin
    

    Having a single dict is the clear winner at 5.5x smaller row vs multiple dicts with granule size of 32 and 2.38x smaller row vs multiple dicts and granule size of 8192.

  11. bobrik commented on Mar 11, 2026

    @bobrik
    ContributorAuthor

    There are unexpected issues with repeated decompressions: #99236.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    question

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions