Architecture

ClickHouse TTL: delete and move old data automatically

TTL looks like a one-line retention policy, but it runs through merges, not a timer. How row, column, move and rollup TTL work, why expired rows are still visible, and how to change TTL on a large table without rewriting all of it.

· 13 min read · AG Data Team

ClickHouse TTL lets a MergeTree table delete, move, recompress or aggregate old data by itself, based on a date expression you declare once. It is the standard way to keep a retention policy in ClickHouse, and it works well, as long as you remember that TTL is applied during merges, not at the moment data expires.

The MergeTree documentation defines two kinds of TTL. A column TTL resets a column to its type's default value when it expires. A table TTL acts on whole rows or parts: it can delete them, move them to another disk or volume, recompress them with another codec, or roll them up with GROUP BY. The expression must evaluate to a Date or DateTime, usually a timestamp column plus an INTERVAL.

A retention policy in one table definition

CREATE TABLE events
(
    event_time DateTime,
    user_id    UInt64,
    event_type LowCardinality(String),
    payload    String TTL event_time + INTERVAL 30 DAY
)
ENGINE = MergeTree
PARTITION BY toYYYYMM(event_time)
ORDER BY (event_type, user_id, event_time)
TTL event_time + INTERVAL 1 MONTH  TO VOLUME 'cold',
    event_time + INTERVAL 12 MONTH DELETE
SETTINGS storage_policy = 'hot_cold', ttl_only_drop_parts = 1;

This table keeps fresh data on the default volume, moves parts older than a month to the cold volume of its storage policy (the policy must define that volume), deletes rows after a year, and empties the bulky payload column after 30 days. A few rules from the documentation are worth knowing before you copy it:

Partial deletes and rollups

DELETE accepts a WHERE clause, so different kinds of rows can live for different periods in one table:

-- keep purchases for a year, everything else for 90 days
TTL event_time + INTERVAL 90 DAY DELETE WHERE event_type != 'purchase',
    event_time + INTERVAL 12 MONTH DELETE

GROUP BY turns expired raw rows into aggregates instead of deleting them. The documentation requires the GROUP BY key to be a prefix of the primary key. Columns that are neither in the key nor in SET get an arbitrary value from the group, as if any() was applied, so list every column that matters in SET.

-- daily totals survive, raw rows do not
CREATE TABLE metrics
(
    day     Date,
    host    String,
    ts      DateTime,
    value   Float64,
    samples UInt64 DEFAULT 1
)
ENGINE = MergeTree
ORDER BY (day, host, ts)
TTL ts + INTERVAL 7 DAY GROUP BY day, host
    SET value = sum(value), samples = sum(samples);

Why expired rows are still there

This is the most common TTL question. The TTL guide says it plainly: deleting or aggregating expired rows is not immediate, it happens during merges. When ClickHouse sees expired data in a part, it schedules an off-schedule merge, but no more often than merge_with_ttl_timeout allows: 14400 seconds (4 hours) by default. Recompression TTL has its own merge_with_recompression_ttl_timeout with the same default.

So a SELECT between merges can return rows that are past their TTL. If a query must never see them, filter on the same expression in the query itself. OPTIMIZE TABLE ... FINAL forces the cleanup, but the guide itself does not recommend it as a routine tool, and on a big table it rewrites a lot of data.

TTL merges also compete with regular merges. max_number_of_merges_with_ttl_in_pool (default 2) stops new TTL merges when that many are already running, to leave room for normal merges and avoid "Too many parts". For replicated tables, max_replicated_merges_with_ttl_in_queue (default 1) limits TTL merges in the replication queue. In our experience these limits are the reason a large backlog of expired data drains slower than people expect.

Partition by the TTL column and drop whole parts

Deleting rows inside a part means rewriting that part. Dropping a part that has fully expired is close to free. The guide recommends partitioning by the day or month of the same column used in the TTL, and the ttl_only_drop_parts setting (off by default) tells ClickHouse to drop parts only when all their rows have expired, instead of rewriting parts to cut out expired rows.

Two caveats. With ttl_only_drop_parts = 1 and monthly partitions, a month of data lives until its newest row expires, so the effective retention is up to one partition longer than the rule. And the setting only applies to row-deleting TTL: column TTL still needs merges that rewrite the part, and those merges remove expired rows as well. Choose partition granularity to match the TTL, but in our experience daily partitions with a multi-year TTL create more partitions than ClickHouse handles comfortably; monthly is usually the safer default for long retention.

TTL is not a precise delete. For "data older than N days is invisible" put a filter in your queries or views. For "remove this customer now" use a targeted delete in ClickHouse. TTL is for keeping storage under control, with hours of slack.

Checking what TTL is doing

system.parts stores the minimum and maximum TTL key for each part, which tells you which parts are due and whether they were moved:

-- which active parts hold the oldest data, and when they expire
SELECT partition, name, rows, disk_name,
       delete_ttl_info_min, delete_ttl_info_max
FROM system.parts
WHERE database = 'default' AND table = 'events' AND active
ORDER BY delete_ttl_info_min
LIMIT 20;

If delete_ttl_info_max is well in the past for many active parts, TTL merges are not keeping up. Check the merge load, disk space and the two pool limits above before forcing anything.

Changing TTL on a large table

On a small table ALTER TABLE ... MODIFY TTL is instant. On a table with terabytes it is not, because of one setting: materialize_ttl_after_modify is on by default and applies the new TTL to old data right after the ALTER. That application runs as a mutation over existing parts, and on a big table it can rewrite most of them, competing with inserts and merges for disk and CPU.

-- change the rule without rewriting every existing part right away
SET materialize_ttl_after_modify = 0;
ALTER TABLE events MODIFY TTL event_time + INTERVAL 6 MONTH DELETE;

-- later, in a quiet window, apply it to old parts
ALTER TABLE events MATERIALIZE TTL;

-- follow the mutation
SELECT mutation_id, command, parts_to_do, is_done, latest_fail_reason
FROM system.mutations
WHERE table = 'events' AND NOT is_done;

Key takeaways

ClickHouse TTL Data retention MergeTree
Work with us

ClickHouse disks filling up with old data?

We design ClickHouse retention with TTL and partitioning, set up hot and cold storage tiers and change TTL rules on large tables without overloading merges.

Get in touch More from the blog