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 = 0 by default, so parts are rewritten row by row. With ttl_only_drop_parts = 1 and 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 in SETTINGS storage_policy = '...'.
  • For simple retention by time, partitioning plus DROP PARTITION is 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 | fresh

The 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 DELETE rewrites parts; large tables benefit from ttl_only_drop_parts with 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

  1. Why did count() still return 3 right after the insert?
  2. When is DROP PARTITION better than a row TTL?
  3. What does move_factor control?

References

  • ClickHouse documentation, Manage data with TTL; Using multiple block devices for data storage

ch-partitions · ch-mutations · ch-backup-restore