ClickHouse TTL: delete, move and roll up old data

Row and column TTL, moving cold parts to cheaper disks, rollups and recompression, how TTL rides on merges, and the system-table queries that prove it is running. Tested on ClickHouse 26.10.

A ClickHouse TTL is a clause on a MergeTree table that tells the server what to do with data once it reaches a given age: delete the rows, reset a column, move the part to another disk, recompress it, or aggregate it into a rollup. The rule is an expression such as ts + INTERVAL 12 MONTH, and the server evaluates it per data part. The catch is in the MergeTree reference: “Data with an expired TTL is removed when ClickHouse merges data parts.” TTL is not a filter on reads. Until a TTL merge runs, a SELECT still returns the expired rows, and the default merge_with_ttl_timeout waits at least 14,400 seconds (4 hours) before repeating a delete-TTL merge in the same partition. So a TTL is a retention policy carried out on the merge scheduler’s timetable, not a guarantee to the second. Every rule type, the merge behaviour and the checks below were run on ClickHouse 26.10.2.

How does TTL work in ClickHouse?

When a part is written, ClickHouse computes the minimum and maximum value of each TTL expression over the rows in that part and stores them with the part. A background task compares those values with the current time. When a part holds expired data, the server schedules an off-schedule merge for it, and that merge applies the rule while rewriting the part.

That design has three consequences worth knowing before you write the first rule:

  1. Expired rows remain visible until their part is merged. The reference says it directly: “If you perform the SELECT query between merges, you may get expired data.” If a query must never see expired rows, add the same condition to the query or a view (WHERE ts >= now() - INTERVAL 12 MONTH).
  2. Whole expired parts are cheap; partly expired parts are not. If every row in a part has expired, the server just drops the part. If only some have, it rewrites the part without them.
  3. TTL competes with normal merges. max_number_of_merges_with_ttl_in_pool (default 2) caps how many TTL merges run at once, “to leave free threads for regular merges and avoid Too many parts”, in the setting’s own words.

You can watch the first two in system.part_log, which tags every merge with a merge_reason. We created a table with a 12-month delete TTL and inserted 10 million rows covering about 23 months:

CREATE TABLE events
(
    tenant_id UInt32,
    ts        DateTime,
    event     LowCardinality(String),
    payload   String
)
ENGINE = MergeTree
PARTITION BY toYYYYMM(ts)
ORDER BY (tenant_id, ts)
TTL ts + INTERVAL 12 MONTH DELETE;

INSERT INTO events
SELECT number % 100, now() - toIntervalSecond(number * 6), 'click', repeat('x', 50)
FROM numbers(10000000);

SELECT merge_reason, count() AS merges, sum(rows) AS rows_out
FROM system.part_log
WHERE table = 'events' AND event_type = 'MergeParts'
GROUP BY merge_reason;
merge_reasonmergesrows_out
TTLDropMerge150
TTLDeleteMerge2539,849

Within seconds, the 15 parts whose rows had all expired were dropped without rewriting anything (TTLDropMerge), and only the two parts that straddled the 12-month boundary were rewritten (TTLDeleteMerge). The table went from 10 million to 5.26 million rows. Monthly partitions did that work: with the TTL on the same column as the partition key, almost every expired part is expired in full.

Row TTL: delete old rows automatically

A row TTL is the clause at the end of the table definition. DELETE is the default action, so TTL ts + INTERVAL 12 MONTH and TTL ts + INTERVAL 12 MONTH DELETE are the same rule. The expression must return a Date, Date32, DateTime or DateTime64, and it can use any column, so ts + toIntervalDay(retention_days) works for a per-row retention.

Add WHERE to expire only some of the rows. This keeps paid-plan audit rows for a year but free-plan rows for 30 days:

CREATE TABLE audit
(
    ts        DateTime,
    tenant_id UInt32,
    plan      LowCardinality(String),
    body      String
)
ENGINE = MergeTree
PARTITION BY toYYYYMM(ts)
ORDER BY (tenant_id, ts)
TTL ts + INTERVAL 30 DAY DELETE WHERE plan = 'free',
    ts + INTERVAL 365 DAY DELETE;

After the TTL merges ran on 200,000 rows covering about 23 months, the table held no free-plan rows older than 30 days, about 48,000 paid-plan rows between 30 and 365 days old, and nothing older than a year. A WHERE rule can never drop a whole part by itself, because it has to look at each row, so expect it to rewrite parts.

ttl_only_drop_parts: never rewrite, only drop

If you do not mind keeping a few expired rows a little longer, ttl_only_drop_parts = 1 makes the server drop parts whose rows have all expired and leave partly expired parts alone. That turns retention into pure metadata work. It only works well when the partition key matches the TTL grain:

CREATE TABLE logs
(
    ts  DateTime,
    msg String
)
ENGINE = MergeTree
PARTITION BY toDate(ts)
ORDER BY ts
TTL ts + INTERVAL 7 DAY DELETE
SETTINGS ttl_only_drop_parts = 1;

On 14 days of minute-level rows, the server dropped the seven fully expired days with seven TTLDropMerge events and no rewrites. The oldest day stayed, because its last rows had not expired yet: 369 rows past the 7-day limit were still in the table. With daily partitions the overshoot is at most a day. With monthly partitions and ttl_only_drop_parts, it is up to a month, so match the partition grain to how precise the retention must be. ClickHouse partitioning best practices covers picking that key; the TTL guide recommends daily partitions for TTLs of days or weeks and monthly ones for months or years.

The setting only governs row-deleting TTLs. Column TTLs still need part rewrites, and the setting’s description notes that such a rewrite also removes the expired rows in the part.

Column TTL: clear sensitive fields, keep the row

A column TTL resets one column to its type’s default value once it expires, and keeps the row. It is the tool for “keep the session for analytics, drop the IP address after 30 days”:

CREATE TABLE sessions
(
    user_id    UInt64,
    ts         DateTime,
    ip         String TTL ts + INTERVAL 30 DAY,
    user_agent String TTL ts + INTERVAL 30 DAY,
    country    LowCardinality(String)
)
ENGINE = MergeTree
PARTITION BY toYYYYMM(ts)
ORDER BY (user_id, ts);

After the TTL merges, the 1,280 sessions older than 30 days had empty ip and user_agent values while country was untouched, and the 720 newer sessions kept every field. When every value of a column in a part has expired, ClickHouse removes that column’s files from the part. Two limits apply: a column TTL cannot be set on a key column, and the reset value is the type’s default (an empty string for String, 0 for numbers), so downstream queries see blanks, not missing rows. If your goal is legal erasure, also remember that a reset only happens when the part is merged, so the old values sit on disk until then.

How to move cold data to cheaper disks with TTL

A TO DISK or TO VOLUME rule moves parts instead of deleting rows. It needs a storage policy in the server configuration first; the table refers to it by name. This one has a hot volume on fast local disk and a cold volume on a larger, cheaper disk:

<storage_configuration>
  <disks>
    <hot><path>/var/lib/clickhouse/hot/</path></hot>
    <cold><path>/mnt/cold/clickhouse/</path></cold>
  </disks>
  <policies>
    <hot_cold>
      <volumes>
        <hot><disk>hot</disk></hot>
        <cold><disk>cold</disk></cold>
      </volumes>
    </hot_cold>
  </policies>
</storage_configuration>
CREATE TABLE metrics
(
    ts    DateTime,
    host  LowCardinality(String),
    value Float64
)
ENGINE = MergeTree
PARTITION BY toYYYYMM(ts)
ORDER BY (host, ts)
TTL ts + INTERVAL 30 DAY TO VOLUME 'cold',
    ts + INTERVAL 180 DAY DELETE
SETTINGS storage_policy = 'hot_cold';

The cold disk can be an HDD or an object-storage disk such as S3; the external storage docs list the disk types. Moves differ from deletes in two ways that surprise people:

  • A part moves only when all of its rows match. The reference states that “for parts moving or recompressing, all rows of a part must satisfy the TTL expression criteria.” On our test table, the October partition stayed on hot even though its first 12 days were older than 30 days, because its last rows were not. The partition grain sets how late data moves.
  • Moves can happen on insert. With the default perform_ttl_move_on_insert, a part whose move TTL has already passed is written straight to the target volume. When we inserted about 280 days of history, the parts for the months that were already past the move TTL were written straight to cold and never touched hot; system.part_log showed no MovePart event for them. That is handy for backfills, but if the cold volume is slow object storage it makes the backfill slow; set perform_ttl_move_on_insert to false on the volume to write to the default volume first and move in the background.

A part that becomes eligible later is moved by a background task, which records a MovePart event in system.part_log. On ClickHouse Cloud this does not apply: the TTL guide notes that tiered storage with volumes is “Not supported in ClickHouse Cloud”, where storage is already object storage. See ClickHouse Cloud vs self-hosted for the rest of that trade-off.

RECOMPRESS and GROUP BY: keep old data, smaller

Two TTL actions shrink history instead of deleting it.

RECOMPRESS rewrites old parts with a heavier codec, trading CPU on the rewrite for less disk. Like moves, it applies to a part only when all of its rows qualify, and merge_with_recompression_ttl_timeout (default 4 hours) paces it:

ALTER TABLE audit
    MODIFY TTL ts + INTERVAL 7 DAY RECOMPRESS CODEC(ZSTD(12)),
               ts + INTERVAL 30 DAY DELETE WHERE plan = 'free',
               ts + INTERVAL 365 DAY DELETE;

system.parts.default_compression_codec shows the result: with this rule on our audit table, all 12 older monthly parts read ZSTD(12) after the merges, and the current month, which still held rows newer than 7 days, stayed on the default LZ4. Note that MODIFY TTL replaces the whole TTL clause, so repeat the rules you want to keep.

GROUP BY rolls expired rows up instead of deleting them, for example minute-level page views into one row per page per day after 30 days. The GROUP BY columns must be a prefix of the table’s primary key (which is the ORDER BY key unless you set PRIMARY KEY), and SET says how to aggregate the other columns:

CREATE TABLE hits
(
    ts    DateTime,
    page  LowCardinality(String),
    views UInt64
)
ENGINE = MergeTree
PARTITION BY toYYYYMM(ts)
ORDER BY (page, toStartOfDay(ts), ts)
TTL ts + INTERVAL 30 DAY
    GROUP BY page, toStartOfDay(ts)
    SET views = sum(views), ts = min(ts);

On 100,000 minute rows for three pages, the TTL merge cut the table to 43,323 rows while sum(views) stayed exactly 100,000: each expired day became one row per page holding 1,440 views. Columns that are neither grouped nor SET get an arbitrary value from the group. If you also need the raw rows elsewhere, a materialized view into a separate rollup table is usually clearer; materialized views vs projections compares those options.

How to add or change TTL on an existing table

ALTER TABLE ... MODIFY TTL sets or replaces the rule. What happens to the data already in the table depends on materialize_ttl_after_modify, which is 1 by default:

ALTER TABLE events MODIFY TTL ts + INTERVAL 6 MONTH DELETE;

SELECT command, is_done, parts_to_do
FROM system.mutations
WHERE table = 'events';
-- (MATERIALIZE TTL)   1   0

With the default, the ALTER queues a MATERIALIZE TTL mutation that rewrites the existing parts and applies the new rule. On our 5-million-row table it finished in under a second, but on a large table it is a full rewrite with the cost of any mutation; deleting and updating rows in ClickHouse explains how mutations behave.

With SET materialize_ttl_after_modify = 0, the ALTER only changes metadata, and that has a trap. We tried it on a fresh table: the old parts had no TTL information, so after 20 seconds the table still held all 5 million rows, including six months of data that the new rule had already expired. Old parts only pick up the rule when they are merged for some other reason. To apply it on your own schedule, run the mutation yourself, ideally in a quiet hour:

ALTER TABLE e2 MATERIALIZE TTL SETTINGS mutations_sync = 1;
-- 5,000,000 rows -> 1,324,797 rows

On a big table with a row-only TTL and ttl_only_drop_parts = 1, the table setting materialize_ttl_recalculate_only = 1 makes MATERIALIZE TTL recalculate the stored TTL values instead of rewriting each part, and drop only the fully expired parts. ALTER TABLE ... REMOVE TTL deletes the rules. Removing or loosening a move rule does not bring moved parts back to the hot volume; use ALTER TABLE ... MOVE PARTITION ... TO VOLUME for that.

How to check that ClickHouse TTL is actually running

A TTL that silently stopped working looks exactly like one that works until the disk fills. Four checks catch the usual failures.

1. Parts holding rows past their expiry. system.parts stores the bounds of the unconditional DELETE rule per part in delete_ttl_info_min and delete_ttl_info_max; DELETE WHERE rules have their own rows_where_ttl_info.* columns. A part whose oldest TTL value is more than a day in the past means TTL merges are not keeping up. On a ttl_only_drop_parts table, use delete_ttl_info_max instead, because partly expired parts are expected to wait:

SELECT database, table,
       count()                  AS parts_overdue,
       sum(rows)                AS rows_in_them,
       min(delete_ttl_info_min) AS oldest_expiry
FROM system.parts
WHERE active
  AND rows > 0
  AND delete_ttl_info_min > toDateTime(0)
  AND delete_ttl_info_min < now() - INTERVAL 1 DAY
GROUP BY database, table
ORDER BY oldest_expiry;

2. Parts with no TTL information. A value of 1970-01-01 00:00:00 (zero) means the part was written before the rule existed and has not been materialized, the trap from the previous section. Every active part on our e2 table showed zero until we ran MATERIALIZE TTL. Filter for tables whose system.tables.create_table_query has an unconditional row TTL and parts where delete_ttl_info_max = 0; tables with only column, move, recompress or WHERE rules always show zero here, so leave them out.

3. Recent TTL activity in the part log. system.part_log records every TTL merge and move. The table exists when part_log is enabled in the server config, which the default config.xml does.

SELECT table, event_type, merge_reason, count() AS events, max(event_time) AS last_seen
FROM system.part_log
WHERE event_date >= today() - 7
  AND (merge_reason IN ('TTLDeleteMerge', 'TTLDropMerge', 'TTLRecompressMerge')
       OR event_type = 'MovePart')
GROUP BY ALL
ORDER BY table, last_seen DESC;

system.merges shows the ones running now, with a merge_type column, and system.parts.disk_name shows where each part lives after moves.

4. Stopped merges. SYSTEM STOP TTL MERGES and SYSTEM STOP MOVES are often run during maintenance and forgotten. While TTL merges were stopped on a test table, even OPTIMIZE TABLE ... FINAL kept all 100 expired rows. After SYSTEM START TTL MERGES, they were gone within seconds. If a table keeps expired data, check whether someone stopped its TTL merges before raising max_number_of_merges_with_ttl_in_pool.

You can force TTL now with OPTIMIZE TABLE ... FINAL, which rewrote a test table from 100 rows down to the 24 still in range, but the TTL guide calls this “not a great solution”, and FINAL merges every partition into a single part, a full rewrite on a large table. Lowering merge_with_ttl_timeout makes retention more prompt at the price of more merges, and the reference warns that a low value can cause many resource-heavy off-schedule merges.

Which TTL rule should you use?

GoalRuleWorks best with
Delete data after N days or monthsTTL ts + INTERVAL n DAY DELETEPartition key on the same column, same grain
Delete cheaply, accept a little overshootRow TTL plus ttl_only_drop_parts = 1Daily partitions for short retention
Different retention per row typeDELETE WHERE plan = 'free'Expect part rewrites
Clear personal data, keep the rowColumn TTLNon-key columns only
Cheaper storage for old dataTO VOLUME 'cold'A storage policy; self-hosted only
Smaller old data, still queryableRECOMPRESS CODEC(ZSTD(n))Old parts that are read rarely
Lower-grain historyGROUP BY primary-key prefix with SETA primary key that starts with the group columns

The same partitioning advice runs through every row: TTL is cheapest when expired data comes in whole parts, so partition by the TTL column at the TTL’s grain.

Where Goni fits

Retention is one part of running ClickHouse; trusting the tables on top is another. Goni is one option for that. Full disclosure: this is our product. It runs on ClickHouse and adds ELT connectors, a YAML semantic layer, data-quality tests, a SQL IDE, dashboards and alerts, so a rule like “keep 12 months” can be checked with a test instead of by memory. The drawback is that ClickHouse is the only warehouse Goni queries, and every TTL in this post works on any ClickHouse server without it. You can try it with the 14-day free trial.

FAQ

How do I delete old data in ClickHouse automatically?

Add a TTL to the MergeTree table, for example ALTER TABLE events MODIFY TTL ts + INTERVAL 12 MONTH DELETE. ClickHouse removes expired rows during background merges, so they disappear within hours, not instantly. Partition by the same column, such as toYYYYMM(ts), so most expired data goes as whole parts without rewrites.

Why is ClickHouse TTL not deleting data?

TTL only acts during merges, and merge_with_ttl_timeout waits 4 hours by default before repeating a delete-TTL merge in a partition. Other causes are parts written before the TTL existed (run ALTER TABLE ... MATERIALIZE TTL), stopped TTL merges (SYSTEM START TTL MERGES), and ttl_only_drop_parts keeping partly expired parts.

Does ClickHouse TTL apply on SELECT?

No. A SELECT can return rows whose TTL has expired if their part has not been merged yet. If a query must never see them, filter on the same condition in the query or a view, such as WHERE ts >= now() - INTERVAL 12 MONTH. OPTIMIZE TABLE ... FINAL forces TTL, but it rewrites the whole table.

How do I move old data to another disk in ClickHouse?

Define disks and volumes in a storage policy in the server config, set storage_policy on the table, and add a rule such as TTL ts + INTERVAL 30 DAY TO VOLUME 'cold'. A part moves only once all its rows qualify. Volume moves are for self-hosted ClickHouse; ClickHouse Cloud does not support them.

What is the difference between column TTL and table TTL?

A table TTL acts on whole rows: it deletes them, moves or recompresses their parts, or rolls them up with GROUP BY. A column TTL resets one column to its default value after the interval and keeps the row, which suits clearing personal fields like IP addresses. Column TTLs cannot apply to sorting or partition key columns.