ClickHouse MergeTree Storage Engine Internals
ClickHouse is recognized as one of the fastest open-source columnar database management systems in existence for Online Analytical Processing (OLAP). At the core of ClickHouse lies the MergeTree family of storage engines. To design high-performance schemas that scale effortlessly from millions of rows to hundreds of billions of rows, a database architect must first develop a precise mental model of how ClickHouse organizes, compresses, indexes, and merges data on the physical filesystem.
1.1 Physical Anatomy of Data Parts on the Filesystem
Unlike traditional relational databases that manage large monolithic data files or fixed-size pages (such as PostgreSQL 8KB pages or InnoDB 16KB pages), ClickHouse adopts a Log-Structured Merge-Tree (LSM) architecture. When an insert query is executed against a MergeTree table, the incoming batch of rows is written to disk as a completely new, immutable directory known as a data part.
Data parts reside on disk within the path:
Each column in the table is decomposed into two distinct files on disk:
- The Column Data File (
{column}.bin): Contains the actual column values. The data is divided into compressed frames ranging from 64KB to 1MB. Because identical types are clustered contiguously, ClickHouse achieves astounding compression ratios (typically 4x to 10x) using algorithms like LZ4 or ZSTD paired with lightweight codecs (e.g.,DoubleDelta,Gorilla, orT64). - The Mark File (
{column}.mrk3): Acts as the bridging translation layer between the sparse in-memory primary index and the physical compressed bytes on disk. A mark file contains an entry for every granule (by default, every 8,192 rows). Each mark records two 64-bit integer pointers: the exact file offset of the compressed block within the.binfile, and the decompressed byte offset of the specific granule within that uncompressed memory buffer.
1.2 The Mechanics of the Sparse Primary Index (primary.idx)
The crowning architectural breakthrough of ClickHouse is its sparse primary index. In traditional OLTP databases (like PostgreSQL, MySQL, or Oracle), indexes are dense B-Trees where every single row has a dedicated index entry. If a table contains 10 billion rows, a dense index requires 10 billion pointers, consuming hundreds of gigabytes of RAM or thrashing the disk buffer pool.
ClickHouse discards dense indexing entirely. Rows in a MergeTree part are physically sorted on disk by the columns defined in ORDER BY. Instead of indexing every row, ClickHouse samples only one row out of every 8,192 rows (governed by the setting index_granularity = 8192). This sampled value represents the boundary value of a granule.
These sparse mark values are stored in primary.idx. Because there is only one mark per 8,192 rows, the entire primary index for a table with 10 billion rows contains only ~1.22 million entries and consumes less than 40 MB of RAM! ClickHouse loads the entire primary.idx file of every active part directly into system RAM upon server startup.
1.3 Background Compaction and the Merge Lifecycle
Because insert operations generate new data parts append-only, high-frequency writes would quickly lead to thousands of small, fragmented directories if left unchecked. To prevent this, ClickHouse executes continuous background merge compaction.
A background thread pool periodically selects a set of adjacent parts belonging to the same partition. It reads the rows from each part in order, performs a multi-way merge sort (analogous to the merge step in merge sort), and streams the merged, sorted rows into a new, consolidated part with an incremented level (for example, parts 202611_1_1_0 and 202611_2_2_0 merge to form 202611_1_2_1). Once the merge completes atomically, the old parts are marked inactive and subsequently deleted from the filesystem after a grace period (governed by old_parts_lifetime, default 8 minutes).
The Critical Distinction Between PARTITION BY and ORDER BY
The single most common and destructive architectural mistake made by software engineers new to ClickHouse is treating PARTITION BY as if it were a query index. In systems like Apache Hive, Trino, or legacy PostgreSQL, partitioning is frequently used to accelerate queries by splitting data into folders. In ClickHouse, this intuition leads to catastrophic production failures.
2.1 What PARTITION BY is Actually For
In ClickHouse MergeTree, PARTITION BY does NOT exist to accelerate search queries. Instead, partitioning is strictly a data lifecycle and operational management tool. The official ClickHouse engineering guideline is unequivocal:
"A partition is a logical combination of records in a table by a specified criterion. Partitions are designed for seamless manipulation of data slices (such as detaching, moving between disks, or dropping entire months). Do not partition by too fine a granularity. Never create more than 1,000 partitions in a table."
The only valid architectural justifications for a partition key in ClickHouse are:
- Instantaneous Zero-I/O Bulk Deletion: Executing
ALTER TABLE events DROP PARTITION '202501'deletes an entire directory tree via an atomic filesystem metadata call in under 5 milliseconds, without reading or writing a single row. - Partition Detachment and Cold Archival: Moving a partition out of the active engine into offline storage via
DETACH PARTITION. - Tiered Storage Migration: Moving aged partition directories from high-speed NVMe SSDs to AWS S3 object storage buckets.
2.2 The Anatomy of Partition Explosion: Error 252 (TOO_MANY_PARTS)
Consider an engineering team that sets up a telemetry analytics table and defines:
If the table retains 3 years of data (1,095 days), the cluster maintains over 1,000 active partition directories. During ingestion, a Kafka ingestion microservice pushes batches of 50,000 rows every 2 seconds. Because network latency, client retries, and out-of-order event arrivals cause events from yesterday, today, and last week to be present in the same insert payload, a single INSERT statement touches 5 to 10 distinct partitions.
ClickHouse must write a new part directory for every partition touched in the insert. Instead of writing 1 part, it writes 10 parts every 2 seconds. The background merge compaction pool can only merge parts that share the exact same partition key. It cannot combine parts from yesterday with parts from today.
Soon, the number of unmerged parts in active partitions exceeds 150 (parts_to_delay_insert), and ClickHouse throttles the client by injecting sleep latencies. Within minutes, unmerged parts surpass 300 (parts_to_throw_insert), and ClickHouse aborts the transaction with the infamous error:
The ingestion pipeline grinds to a complete halt, message queues back up, and the database becomes unresponsive.
2.3 The Solution: Monthly Partitions and Sparse Index Ordering
To eliminate partition explosion permanently, adopt the golden rule of ClickHouse architecture:
Always use PARTITION BY toYYYYMM(timestamp) for time-series and event telemetry. For a 3-year retention policy, toYYYYMM(timestamp) produces exactly 36 partitions. 36 partitions provide trivial background compaction, negligible filesystem inode consumption, and allow bulk monthly TTL drops while letting the ORDER BY key handle all sub-month, daily, and millisecond query pruning via RAM binary search!
Designing Optimal Sorting Keys: Low-to-High Cardinality Sequencing
If PARTITION BY is for data management, ORDER BY is the engine that drives 100% of ClickHouse query performance. The columns listed in the ORDER BY tuple dictate the physical sort order of every row inside every columnar .bin file and establish the entries in the primary.idx sparse index.
3.1 The Low-to-High Cardinality Principle
In ClickHouse, multi-column sorting keys behave lexicographically, exactly like words in a dictionary. Consider an ORDER BY tuple defined as:
Here is why this sequence is architecturally optimal:
tenant_id(Low Cardinality, ~100 to 10,000 values): Rows belonging to customer 42 are grouped contiguously on disk. All data for tenant 42 occupies a single uninterrupted span of granules. When tenant 42 queries their data, ClickHouse locates the start and end mark via binary search and discards 99% of the table instantly.event_type(Low Cardinality, ~5 to 50 values): Within tenant 42's physical disk span, all'purchase'events are clustered together. A query filteringWHERE tenant_id = 42 AND event_type = 'purchase'narrows the candidate mark range even further.user_id(High Cardinality, ~1M to 50M UUIDs): Within the tenant and event slice, rows are grouped by individual user.timestamp(Monotonic Sequence): Finally, within each user's activity, rows are sorted chronologically.
3.2 The Inverted Cardinality Pathology: Why Timestamp-First Fails
Engineers migrating from time-series engines like InfluxDB or TimescaleDB frequently put timestamp as the very first column in the sorting key:
When timestamp is first, data is sorted chronologically at millisecond resolution. Every single millisecond contains rows from dozens of different tenants. As a result, tenant 42's rows are dispersed evenly across every single granule in the entire database!
If tenant 42 logs into their SaaS dashboard and runs a query across the last 30 days:
WHERE tenant_id = 42 AND timestamp >= now() - INTERVAL 30 DAY;
Because tenant_id is in the second position of the sorting key and timestamp is an open range, ClickHouse cannot use binary search on tenant_id. The primary index marks cannot eliminate any candidate blocks. ClickHouse is forced to read every single mark for the last 30 days from disk, decompress hundreds of gigabytes of data, and filter out the 99% of rows that belong to other tenants. Query latency explodes from 15ms to 8,500ms.
3.3 Primary Key vs Sorting Key Decoupling
ClickHouse allows an advanced architectural separation: the PRIMARY KEY can be a strict prefix of the ORDER BY clause:
ORDER BY (tenant_id, event_type, user_id, timestamp)
By restricting the PRIMARY KEY to (tenant_id, event_type), ClickHouse only includes those two columns in the in-memory primary.idx index, keeping RAM usage to an absolute minimum (under 10 MB). Meanwhile, the physical rows on disk are still sorted by the full 4-column tuple, ensuring maximum data compression in the .bin files!
Secondary Data Skipping Indices & Bloom Filters
In any real-world analytics application, queries do not always filter on the leading columns of the sorting key. An analyst might need to search for a specific user_id, a distinct error_code, or a substring in a url_path without specifying a tenant_id. In these scenarios, the sparse primary index cannot prune marks.
To accelerate non-prefix queries without resorting to heavy dense secondary B-Trees, ClickHouse provides Data Skipping Indices.
4.1 How Data Skipping Indices Function Internally
A skipping index is evaluated on blocks of granules specified by the index's GRANULARITY parameter (for example, GRANULARITY 4 aggregates metadata across 4 * 8,192 = 32,768 rows). During table writes, ClickHouse computes summary metadata for each block of granules and writes it to a secondary index file (skp_idx_{name}.idx and skp_idx_{name}.mrk3).
During query execution, ClickHouse checks the skipping index metadata before touching the columnar .bin data. If the index proves that the target value cannot exist within those 32,768 rows, the engine skips reading the mark range entirely.
4.2 The Four Primary Skipping Index Types
Stores the minimum and maximum values for the column across the granule block. Extremely lightweight with near-zero storage overhead. Highly effective on columns that are correlated with the sort order or naturally clustered (such as auto-incrementing IDs or sensor temperatures).
Stores a distinct hash set of all values in the granule block up to max_rows. If distinct values exceed the threshold, the set marks the block as "overflowed" and skips evaluation. Ideal for low-cardinality status codes, payment flags, or localized country codes.
Employs a space-efficient probabilistic bit array. For point lookups on high-cardinality identifiers (like user_id, order_id, or ip_address), a Bloom filter with a 0.01 (1%) false positive rate prunes 90% to 99% of granules on needle-in-a-haystack queries.
Tokenizes strings by non-alphanumeric delimiters or character n-grams and inserts tokens into a Bloom filter. Unlocks blistering speed for URL path searches (WHERE url LIKE '%checkout%') and log analysis without full-text search engines.
4.3 The Skipping Index Performance Trap
Skipping indices are NOT free. Every skipping index consumes disk space and incurs CPU overhead during merges and query execution. If a column is uniformly distributed across granules (such that every 32,768-row block contains at least one match for the query condition), the skipping index will evaluate every block, fail to skip any data, and result in a query that is 10% to 30% slower than raw columnar scanning!
Only add skipping indices to columns that are filtered frequently and have strong locality or sparse distribution.
Compaction Tuning, Mutations & Automated S3 Storage Tiering
Operating a multi-terabyte ClickHouse deployment in enterprise production requires mastering system-level tuning: configuring background compaction thread pools, handling data updates without inducing write freezes, and tiering cold historical data to cloud object storage.
5.1 Tuning the Background Merge Pool
Under heavy sustained write loads (e.g., 500M+ rows/day), the default merge pool configuration may fall behind. The primary settings in config.xml governing merge compaction are:
background_pool_size(Default: 16): Sized according to CPU core count. On modern 32-core or 64-core bare-metal nodes with NVMe arrays, increase this value to32or48to allow more concurrent merge threads.max_bytes_to_merge_at_max_space_in_pool(Default: 150 GB): Controls the maximum allowable size of parts merged during compaction. Lowering this prevents massive merges from monopolizing disk I/O channels.parts_to_delay_insertandparts_to_throw_insert: For high-throughput ingestion with wide schemas, tune these table-level settings to150and300(up from legacy defaults of 50 and 100) to provide buffer headroom during traffic spikes.
5.2 The Peril of Mutations (ALTER TABLE UPDATE / DELETE)
In transactional SQL databases, UPDATE users SET status = 'active' WHERE id = 42 updates a single row in place via page locks. In ClickHouse MergeTree, in-place row updates do not exist.
When an ALTER TABLE ... UPDATE or DELETE mutation is submitted:
- ClickHouse creates an asynchronous background mutation task.
- The engine iterates through every single active data part in the target partition.
- It reads the entire part from disk, rewrites the modified columns, recalculates marks, and writes an entirely new part directory with an incremented mutation version (e.g.
202611_1_2_1_1).
Executing frequent single-row mutations will completely saturate storage I/O, starve merge threads, and trigger TOO_MANY_PARTS failures. For workloads requiring frequent row updates or soft deletes, architects must use specialized engines such as ReplacingMergeTree (which deduplicates rows with identical sorting keys during background merges) or CollapsingMergeTree.
5.3 Zero-Downtime Automated S3 & Cloud Object Storage Tiering
Storing 3 to 5 years of telemetry data entirely on local high-performance NVMe SSDs is financially prohibitive. ClickHouse solves this through Multi-Volume Storage Policies.
In config.xml, define a tiered storage policy linking local NVMe with an AWS S3 bucket:
Then, in your table DDL, declare an automated lifecycle TTL expression:
TTL toDateTime(timestamp) + INTERVAL 14 DAY TO VOLUME 'cold',
toDateTime(timestamp) + INTERVAL 365 DAY DELETE;
Data younger than 14 days is ingested and queried on local ultra-fast NVMe SSDs. When a part crosses the 14-day threshold, ClickHouse automatically streams it into AWS S3 in the background. SQL analysts querying 6-month historical trends query the exact same table; ClickHouse executes transparent byte-range HTTP requests against S3, reducing storage bills by up to 90% with zero engineering friction.
Production Multi-Billion Row Telemetry & Analytics Blueprint
To synthesize all architectural principles explored in this masterclass, here is an end-to-end, battle-tested production blueprint designed to handle 10 billion rows per year with sub-50ms p95 query latencies, minimal RAM consumption, and automated S3 cold storage migration.
6.1 Complete Production MergeTree Schema
6.2 Architectural Verification & Ingestion Checklist
Prior to deploying this schema to your staging or production Kubernetes cluster, verify these four operational checkpoints:
- Batch Sizing: Ingestion clients (such as Kafka Engine, Vector, or FluentBit) MUST buffer records and insert batches of at least 10,000 to 100,000 rows per HTTP/TCP request. Never execute single-row
INSERT INTO ... VALUES (...)queries. - Pre-Sorting at Ingestion: If the ingestion pipeline aggregates records across many tenants, sorting the batch by
(tenant_id, timestamp)in client memory prior to sending the INSERT batch reduces part fragmentation and improves initial part compression. - Index Materialization: When adding secondary data skipping indices to pre-existing tables, always execute
ALTER TABLE table_name MATERIALIZE INDEX index_name;to build the index across historical parts in the background. - Monitoring Active Merges: Set up Prometheus and Grafana alerts on
system.partsandsystem.mergesto detect any partition accumulating more than 50 active unmerged parts.
Frequently Asked Architectural Questions
Detailed engineering explanations covering ClickHouse MergeTree storage mechanics, error codes, index sizing, and compaction tuning.
Q1What is the physical on-disk directory anatomy of a ClickHouse MergeTree data part?
Every ClickHouse MergeTree table stores its physical data on the host filesystem under /var/lib/clickhouse/data/{database}/{table}/. Within this table directory, data is partitioned into subdirectories called "parts", named according to the deterministic convention {partition_id}_{min_block_num}_{max_block_num}_{level}_{mutation}. Inside each active part folder, the engine stores individual columnar files. For every table column, there is a compressed binary data file ({column}.bin) structured in compressed frames of 64KB to 1MB, and an index mark file ({column}.mrk3 or .mrk2) that maps index mark numbers to both the physical compressed byte offset in the .bin file and the uncompressed decompressed byte offset. In addition, the part directory contains the global primary.idx binary sparse index file loaded directly into system RAM, count.txt defining the exact row count of the part, columns.txt defining column types, checksums.txt containing cryptographic hashes of all files for data integrity verification, and default_compression_codec.txt indicating the active compression algorithm.
Q2Why does creating daily partitions with long retention cause Error 252 (TOO_MANY_PARTS) and write stalls?
A frequent architectural anti-pattern imported from relational databases or legacy Hadoop/Hive installations is defining PARTITION BY toDate(timestamp). While partitioning by day appears intuitive for time-series data, it creates catastrophic operational pathology in high-throughput ClickHouse clusters. When an ingestion client issues bulk inserts that span multiple timestamps or when retention extends to 2 or 3 years, the table maintains 700 to 1,000+ active partition folders. Because ClickHouse writes at least one new part per partition per insert batch, high-frequency writes fragment ingestion across hundreds of separate directories simultaneously. The background merge compaction pool can only merge parts within the same partition; it cannot merge parts across partition boundaries. As a result, active parts accumulate faster than the merge pool can compact them, rapidly exceeding parts_to_delay_insert (150 parts) and parts_to_throw_insert (300 parts), triggering ClickHouse Error 252 (TOO_MANY_PARTS) and rejecting new writes. Furthermore, every active part maintains open file descriptors for every column (.bin and .mrk3), exhausting OS ulimits and saturating kernel directory cache lookups.
Q3Why must sorting key (ORDER BY) columns be sequenced strictly from low to high cardinality?
ClickHouse stores rows on disk ordered lexicographically by the tuple specified in the ORDER BY clause. Because ClickHouse employs a sparse index with one index mark every 8,192 rows rather than a dense B-Tree indexing every row, the ordering of columns determines how effectively primary index ranges can prune disk blocks during range scans. When a low-cardinality column such as tenant_id (e.g., 50 distinct values) or event_type (10 distinct values) is placed first, all rows belonging to tenant 42 are clustered together in contiguous physical disk granules. Within that contiguous physical slice, secondary columns are sequentially ordered. Queries filtering on tenant_id can binary-search the primary index in RAM, immediately pruning 98% of all marks across the entire cluster. Conversely, if a high-cardinality column like user_id (10 million unique UUIDs) is placed first, rows for any given tenant_id are scattered across virtually every single granule on disk, destroying mark compression, invalidating secondary column binary search, and forcing the query engine to inspect every disk mark across the table.
Q4How does ClickHouse sparse primary indexing fundamentally differ from dense B-Tree indexing in PostgreSQL or MySQL?
In traditional transactional RDBMS engines like PostgreSQL and MySQL, secondary indexes are dense B-Trees or B+ Trees where every individual row in the table possesses an explicit pointer entry. While dense B-Trees allow instantaneous O(log N) point-lookups for single rows, they impose massive memory and disk write amplification: index sizes frequently match or exceed the raw data size, and concurrent inserts incur costly B-Tree rebalancing and random disk writes. In contrast, ClickHouse MergeTree is an append-only columnar storage engine designed for multi-gigabyte throughput. It utilizes a sparse index governed by index_granularity (typically 8,192 rows). The primary index does not store individual row locations; instead, it samples only the first row value of each 8,192-row granule and stores this sparse sequence in a tiny in-memory array (primary.idx). During a query, ClickHouse evaluates primary key predicates against this compact RAM array to locate candidate mark intervals, and then streams entire 8,192-row columnar vector blocks directly into CPU SIMD registers for evaluation.
Q5What is the exact mathematical equation for calculating ClickHouse primary index RAM footprint?
The memory consumed by a ClickHouse MergeTree primary index in system RAM is directly proportional to the total row count, the index granularity, and the cumulative serialized byte size of the columns comprising the sorting key. The formula is: Total_Index_Marks = ceil(Total_Rows / index_granularity). The byte size per mark is calculated as: Key_Bytes_Per_Mark = Sum(Column_Byte_Footprints) + 16_bytes (accounting for ClickHouse in-memory pointer and mark descriptor overhead). Therefore, Total_Primary_Index_RAM = Total_Index_Marks * Key_Bytes_Per_Mark. For example, in a table containing 10 billion rows with an index_granularity of 8,192 and an ORDER BY key composed of UInt32 tenant_id (4 bytes), LowCardinality(String) event_type (2 bytes), and DateTime64 timestamp (8 bytes), Total_Index_Marks = ceil(10,000,000,000 / 8,192) = 1,220,704 marks. With Key_Bytes_Per_Mark = 14 + 16 = 30 bytes, the total primary index RAM footprint across the entire 10-billion-row dataset is approximately 36.6 MB. This astonishingly compact footprint allows ClickHouse to hold the primary indexing topology of tens of billions of rows permanently in CPU L3 cache and RAM.
Q6When do secondary data skipping indices (minmax, set, bloom_filter) degrade query performance instead of accelerating it?
Data skipping indices in ClickHouse aggregate metadata across multiples of index granules (governed by the skipping index GRANULARITY setting, usually 1 to 8 marks). A skipping index only accelerates queries when the filter predicate matches a small minority of granules and allows ClickHouse to skip reading entire chunks of compressed .bin data. If a column has high entropy or appears uniformly distributed across all granules, every single granule will pass the skipping index evaluation (e.g., a minmax index on a randomly distributed hash or a bloom_filter with a high false-positive rate). In this scenario, ClickHouse is forced to read the skipping index .idx file from disk or OS page cache, execute bloom filter bitwise hash operations or minmax comparisons for every granule, only to conclude that zero granules can be skipped. The query incurs additional CPU overhead, memory consumption, and disk I/O, running measurably slower than a pure vectorized columnar scan without the index.
Q7How do multi-tier storage policies and TTL expressions seamlessly offload cold data to AWS S3 or Cloudflare R2?
ClickHouse provides native multi-volume tiered storage governed by the storage_configuration section in server configuration. Administrators define storage policies combining fast local NVMe SSDs (volume "hot") with remote S3-compatible object storage buckets (volume "cold"). In the MergeTree table DDL, declarative TTL expressions specify lifecycle migration boundaries. For instance, TTL timestamp + INTERVAL 14 DAY TO VOLUME "cold", timestamp + INTERVAL 365 DAY DELETE instructs ClickHouse to monitor part age. During background compaction or dedicated TTL passes, ClickHouse identifies parts whose maximum timestamp exceeds 14 days and writes the newly merged part directly to AWS S3 or Cloudflare R2 object storage, deleting the local NVMe copy. Crucially, this storage migration is 100% transparent to SQL client applications: queries querying historical data execute identical SELECT queries against the same table, with ClickHouse handling range requests and object storage byte streaming automatically.