Overview
TTL (time to live) expressions delete, move or aggregate old data automatically as part of merges. Combined with storage policies (volumes on fast and slow disks, or object storage) you get hot/warm/cold tiers and bounded retention without external cron jobs.
Core concepts
- Table TTL:
TTL ts + INTERVAL 7 DAY DELETE(default action),TO VOLUME 'cold',TO DISK 's3',RECOMPRESS CODEC(ZSTD(9)),GROUP BY ... SET ...(roll up old rows). Column TTL resets a column to its default after a time. - TTL is applied during merges (and
MATERIALIZE TTL), not at the exact moment a row expires.merge_with_ttl_timeout(14,400 s = 4 h in the test server) controls how often a TTL-only merge is scheduled;ttl_only_drop_parts = 0by default, so parts are rewritten row by row. Withttl_only_drop_parts = 1and partitions aligned to the TTL, whole parts are dropped cheaply. - Storage policies are configured server-side (
storage_configuration: disks, volumes,move_factor). A table references a policy inSETTINGS storage_policy = '...'. - For simple retention by time, partitioning plus
DROP PARTITIONis faster and more predictable than row TTL (ch-partitions).
Worked example
CREATE TABLE ttl_t (ts DateTime, v String) ENGINE = MergeTree ORDER BY ts TTL ts + INTERVAL 7 DAY DELETE;
INSERT INTO ttl_t VALUES (now() - INTERVAL 30 DAY, 'old'), (now() - INTERVAL 10 DAY, 'old2'), (now(), 'fresh');
SELECT count() FROM ttl_t; -- 3: expired rows still visible, TTL runs on merge
OPTIMIZE TABLE ttl_t FINAL;
SELECT count(), any(v) FROM ttl_t; -- 1 | freshThe expired rows only disappeared after a merge was forced. On a busy table the regular merge schedule applies TTL eventually; do not use TTL as a hard guarantee of immediate deletion (for compliance use explicit deletes, ch-mutations).
Pitfalls and production notes
- TTL by
DELETErewrites parts; large tables benefit fromttl_only_drop_partswith time partitions. - Tiering to object storage trades latency for cost; test query speed on cold data.
- Policy changes (
ALTER ... MODIFY TTL) apply to old parts only after materialisation. - Backups and TTL interact: a restored backup brings expired data back until merges remove it (ch-backup-restore).
- Replicas apply TTL independently but identically, since the leader schedules merges (ch-replication-keeper).
Practice questions
- Why did
count()still return 3 right after the insert? - When is
DROP PARTITIONbetter than a row TTL? - What does
move_factorcontrol?
References
- ClickHouse documentation, Manage data with TTL; Using multiple block devices for data storage