Blog

ClickHouse Compression Codecs and Storage Costs

Storage cost is an engineering decision made at schema definition time. Matching each column’s codec to its value distribution is the primary lever. Columnar storage groups values contiguously so encoders can exploit regularity, while chains such as CODEC(Delta, ZSTD(1)) transform values before compressing them. Getting those choices right before replication and backup multipliers apply is the highest-leverage moment in schema design.

Delta encoding for timestamps and monotonically increasing integers

Timestamps are a natural starting point because consecutive values often differ by far less than their full 64-bit representation. Delta encoding stores those differences in place of the original values, so the next compression stage has a smaller range to work with. Monotonically increasing integers offer the same opportunity, making Delta a starting choice for both time columns and ordered integer sequences. The data type suggests what to try, but the sequence sets how much it helps.

For timestamp columns, the recommended chain is CODEC(Delta, ZSTD(1)). Delta first reduces the value range, and ZSTD then compresses the resulting small differences. Neither stage performs the entire job on its own. Together, they give much better compression ratios than either codec alone because the transformation gives the general compressor more regular data to work with. This is why choosing a structure-aware encoder is different from simply increasing a general codec’s compression level.

DoubleDelta extends the same reasoning to sequences whose differences are themselves regular, including event IDs and counters with uniform increments. Here, the increments provide another layer of predictability. However, arrival order is not necessarily the order that gives Delta its best input. Out-of-order data therefore connects the codec decision to MergeTree sort key design, because the relevant regularity is between consecutive stored values. A timestamp type alone does not establish that regularity.

Gorilla encoding for slowly changing floats

An IoT sensor reading often drifts from one observation to the next. That pattern calls for a different encoder. Gorilla is designed for time-series floats, including sensor readings, CPU utilization, and response latencies, whose consecutive values change slowly. It encodes the bitwise differences between successive values and stores only the bits that changed.

For an IoT schema, the practical distinction is between a metric that drifts and one that jumps. A slowly changing float is a strong candidate for Gorilla because its successive representations retain useful similarities. Random or high-variance distributions are a poor fit when most bits change from one row to the next. The column’s label cannot settle that distinction. A sensor reading and a response-latency metric are both worth trying, but their value distributions must suit the encoding.

The recommended chain for most float metric columns is CODEC(Gorilla, ZSTD(1)). Gorilla uses the bits that successive values share, and the general codec that follows compresses the bit patterns left over. Pure Gorilla leaves significant compression opportunities unused. As with Delta, the two stages address different features of the same data rather than offering interchangeable ways to compress it.

LowCardinality for repeated string columns

Applying LowCardinality to a city string column reduced storage from 14.8 MB to 2.1 MB. That reduction comes from LowCardinality(String) replacing string values with variable-width integer indices into a dictionary. Dictionary encoding takes place before a general codec is applied.

This makes LowCardinality a schema choice for almost every string column with a limited set of distinct values. The practical candidates have thousands of distinct values or fewer relative to the total row count, including status codes, country codes, region names, event types, log levels, and HTTP methods. Repetition is the deciding property. When many rows reuse a small vocabulary, dictionary indices avoid representing that vocabulary repeatedly as full strings. A general codec can then compress the encoded representation.

However, applying the same modifier to high-cardinality strings can degrade storage behavior. User IDs and free-form URLs are often a poor fit when the number of distinct values keeps growing without a limit. The dictionary then consumes memory and defeats the purpose of the encoding. A string type alone is not enough. The practical rule is to reserve LowCardinality for genuinely low-cardinality columns and use ZSTD directly for high-cardinality strings.

ZSTD for text, JSON payloads, and high-cardinality strings

Raw log text, JSON blobs, UUIDs, URLs, and free-form identifiers often lack the monotonic or low-cardinality structure needed by the preceding choices. ZSTD is the general codec for this residual category because its dictionary-based compression finds repeated patterns across values that LZ4 misses. High cardinality changes the kind of repetition available, from reuse of whole values to patterns within the content.

LZ4 is the default codec, with fast encoding at roughly 740–780 MB/s, compression ratios in the two-to-three times range, and low CPU cost. It is a reasonable general default. However, its speed does not make it the best storage choice for every column, especially where another encoder can exploit structure or ZSTD can capture more content repetition. For text and other high-cardinality content, the next choice is which ZSTD level to use. The choice must account for query temperature as well as compressed size.

For raw JSON, ZSTD is a baseline rather than the limit of what schema design can achieve. Using the JSON type to expose typed sub-columns allows the codec hierarchy to apply within what was previously an opaque blob. Numeric attributes can then become candidates for Delta or Gorilla according to their value distributions. The unit of choice becomes more precise. This is a forward path for schema evolution.

Modeling the actual storage cost reduction before committing to a schema

Codec selection and storage estimation belong in the same schema-design exercise. A compression ratio shows how much the stored data has shrunk, but the storage bill also includes replication and the backups that are kept. Replicated MergeTree multiplies the compressed footprint by the replication factor, so an inefficient column is paid for at every replica. The copies amplify the original design choice. A schema that achieves a four times compression ratio still pays for two or three copies of that compressed data in a replicated cluster.

The model needs to count the space used by compressed live data across replicas and by the backups that are kept. Under the stated default of one backup retained for one day, the backup effectively doubles the storage line. Longer retention adds another multiplier. Keeping backups for more days or weeks raises storage costs in proportion, so shrinking the compressed base saves more as retention grows. Modeling only the primary copy understates the footprint that the codec decision influences.

The practical measurement step is to load representative data before committing production volume to the schema. system.parts_columns exposes compressed and uncompressed column sizes per part, making it the appropriate tool for comparing codec choices against actual data. The measurements anchor the estimate in the column distribution. They also separate a promising codec rule from a compression result demonstrated by the proposed schema.

Those measurements can then feed the replication and retention assumptions used in the storage model. The purpose is not to treat every column as equally compressible, but to estimate the full footprint from the representation each column actually achieves. This keeps codec selection tied to cost. It also places the comparison before accumulated production data makes an unsuitable schema expensive to retain.

Where the CPU cost of aggressive compression actually shows up

Better compression reduces disk reads, which structurally favors OLAP workloads. In those workloads, the I/O savings almost always outweigh decompression CPU cost, making compression a performance gain as well as a storage lever. That balance is not an unconditional guarantee. Higher ZSTD levels and chains such as Delta with ZSTD increase decompression CPU cost at query time. Ignoring that tradeoff can produce a schema that is cheap to store but slow to query.

The practical rule is to match compression aggressiveness to query temperature. LZ4 is the starting choice for hot columns on paths with sub-second SLAs, while ZSTD(1) or ZSTD(3) fits cold or archival columns where slightly higher latency is acceptable. Write-heavy archival columns may favor ZSTD, but the relevant question remains how the stored data is queried. Storage efficiency and latency requirements have to be considered together.

Agentic and observability workloads make that distinction especially consequential because a single agent loop can generate many SQL queries against the same tables in seconds. Repeated queries multiply the latency cost of over-compressed hot columns. Query frequency changes the operational balance. A compression choice that is acceptable for occasional archival access can become unsuitable when the same column moves into a frequently queried path.

A systematic checklist for assigning codecs at schema definition time

The column-by-column procedure begins with three questions about the values. Is the column monotonically increasing or otherwise delta-compressible, is it a slowly changing float, or does it have low cardinality. Each question identifies a different encoding opportunity. Monotonically increasing integers and timestamps start with CODEC(Delta, ZSTD(1)), while uniform-increment sequences such as event IDs are candidates for DoubleDelta. Slowly changing floats start with CODEC(Gorilla, ZSTD(1)).

For strings, the next decision is whether a bounded vocabulary is repeated across many rows. Status codes, regions, log levels, and event types are candidates for LowCardinality(String) with CODEC(ZSTD(1)) applied on top. High-cardinality strings, raw text, and JSON blobs instead start with general compression. Within that branch, CODEC(ZSTD(1)) is the starting choice for hot columns and CODEC(ZSTD(3)) for cold archival columns. The stricter sub-second hot-path requirement can override that starting choice in favor of LZ4.

JSON columns with numeric attributes require a schema decision before the codec assignment is complete. Exposing typed sub-columns through the JSON type allows Delta or Gorilla to be selected according to the attributes’ distributions. Validation follows the proposed assignments. Before production data is written at scale, system.parts_columns shows the compressed and uncompressed size of each column to help check the choices, while system.parts shows how much storage each part uses. The resulting measurements belong in the replication and backup model.

A cold column that moves to a hot analytical path may need LZ4, while a string column whose cardinality once stayed within a limit but now keeps growing may need LowCardinality removed. Both access patterns and distributions can change. Revisiting those properties preserves the connection between the schema and the workload it serves. The same schema can move from an open-source deployment to Cloud, so the codec framework can guide the design through that move.

All posts