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:
- DELETE is the default action.
TTL event_time + INTERVAL 1 YEARon its own means delete. - Moves and recompression work on whole parts. All rows of a part must satisfy the expression before the part is moved or recompressed; deletes can remove individual rows.
- Column TTL has limits. It cannot be used on key columns, on columns whose subcolumns are part of the sorting or partition key, or on
ALIASandEPHEMERALcolumns. When every value of a column in a part has expired, ClickHouse removes that column's file from the part. - Use deterministic expressions. The documentation warns that TTL should depend only on column values; things like
now()orrand()inside the expression give unpredictable results.
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;
- Separate the rule from the rewrite. With
materialize_ttl_after_modify = 0, theALTERonly saves the new rule and existing parts are not rewritten at that moment;MATERIALIZE TTLapplies it to them later, when you choose. - Cheaper materialization.
materialize_ttl_recalculate_onlymakesMATERIALIZE TTLonly recalculate TTL metadata; for tables with only row TTL andttl_only_drop_partsenabled it then drops fully expired parts instead of rewriting them. - Watch it like any mutation. Track
parts_to_doandlatest_fail_reasoninsystem.mutations. Our guide to stuck ClickHouse mutations covers what to do when one stops moving. - Disk headroom. Rewriting a part needs room for the new copy before the old one is removed. On a nearly full disk, plan for the largest parts, not the average.
- Clusters.
ON CLUSTERapplies the change on every shard at once, so the rewrite load hits the whole cluster together. In our experience it is safer to start with one shard and watch merges and replication queues before rolling out. - Removing TTL.
ALTER TABLE ... REMOVE TTLdrops the rule; rows already deleted are of course not coming back, so take a backup before shortening retention on data you may need.
Key takeaways
- TTL deletes, moves, recompresses or aggregates data during merges, not at the moment it expires; queries can see expired rows in between.
merge_with_ttl_timeout(4 hours by default) and the TTL merge pool limits decide how fast expired data actually goes.- Partition by the TTL column and enable
ttl_only_drop_partsso expired data is dropped by whole parts instead of rewritten. - Use
DELETE WHEREfor per-type retention andGROUP BY ... SETfor rollups, listing every column you care about. - On large tables set
materialize_ttl_after_modify = 0beforeMODIFY TTLand runMATERIALIZE TTLdeliberately, one shard at a time.