A ClickHouse events table (MergeTree) takes about 2 billion rows a day, inserted in batches of roughly 50,000 rows every couple of seconds. Almost every query filters by user_id and a time range of a few days, and data older than 13 months must be removed. One teammate proposes PARTITION BY user_id (about 5 million users) so per-user queries open less data; another proposes PARTITION BY toStartOfHour(event_time). Choose the partition key and the ORDER BY for this table, and explain what goes wrong with each of the two proposals.
A partition is a data-management unit (drop, TTL), not an index, and merges never cross it. A user_id key splits each batch into thousands of parts; both keys yield thousands of partitions, past the docs' ~1000. Partition by month; ORDER BY (user_id, event_time).
- Using PARTITION BY as if it were an index for the most common filter
- Assuming merges will fold many small partitions together over time
- Choosing a partition key without counting how many parts each insert creates
- How does a monthly partition key make the 13-month retention cheap?
- What happens to an INSERT whose batch spans more than 100 partitions?
Why not user_id. Every 50,000-row batch holds thousands of different users, and an INSERT writes a separate part for each partition it touches. By default an insert that touches more than 100 partitions fails (max_partitions_per_insert_block); even without that limit parts multiply faster than they can be merged, and merges never combine parts of different partitions. Millions of partitions mean millions of directories and a slow start for every query.
Why not hourly. Thirteen months come to about 9,500 partitions — an order of magnitude above the "about a thousand" the docs name as the limit. Each partition merges on its own, so parts stay numerous, and a query over a few days opens hundreds of partitions.
What to pick. PARTITION BY toYYYYMM(event_time) — 13–14 partitions; an old month goes with ALTER TABLE … DROP PARTITION or TTL, no mutations. Speed comes from ORDER BY (user_id, event_time): the user filter hits the key prefix and time narrows the range inside it. The monthly key also prunes months outside the query range. No partitioning at all is also acceptable, but retention then relies on TTL cleaning data part by part.