How to Scale K-Means Clustering with just ClickHouse SQL
K-Means clustering can be implemented entirely in ClickHouse SQL by computing centroids incrementally with avgForEachState aggregate states stored in an AggregatingMergeTree table, fed by a Materialized View over a Null-engine table. Each iteration is a single INSERT INTO SELECT that assigns every point to its nearest previous centroid via L2Distance, so memory stays bounded and the work scales across a cluster. Querying pre-aggregated centroids is over 1700x faster than a raw GROUP BY on 100M rows. Clustering 170M NYC taxi rides takes under 3 minutes, versus over 100 minutes and 90GB of RAM with scikit-learn on the same resources.
Related posts
- How we scaled raw GROUP BY to 100 B+ rows in under a second
ClickHouse mediumAdept
ClickHouse Cloud's parallel replicas feature spreads a single GROUP BY query across every core of every node in a service, with no pre-aggregation or data reshuffling. In the benchmark, 100 billion rows were aggregated in 414 ms at about 1.45 TB/s, compared with 16.6 s on a single 89-core node. The speedup rests on ClickHouse's execution model. Each pipeline stream scans a non-overlapping set of part ranges and builds mergeable partial aggregation states in one of 30+ specialized hash table variants, so any core or node can process any subset of rows and the partial results merge correctly. The post also covers memory behaviour by aggregate function, the reproducible benchmark setup, and how runtime scales vertically (more cores per node) and horizontally (more nodes).
- Using Materialized Views in ClickHouse
ClickHouse mediumAdept
ClickHouse materialized views act as insert-time triggers that write the result of a SELECT into a target table, letting expensive aggregations be precomputed. On a 1B-row Wikistat dataset, a SummingMergeTree-backed view cuts a top-projects query from 15 seconds to 3 ms, and AggregatingMergeTree with *State()/*Merge() combinators handles min/max/avg the same way. The same mechanism supports compacting history (with source-table TTL), validating and filtering rows via a Null-engine source table, routing invalid data to separate tables, and transforming columns. Practical guidance: keep views per table to around ten or fewer, still GROUP BY at query time since merges are asynchronous, avoid FINAL on large tables, and only aggregate for storage when it reduces rows by roughly 10x.
- How Klaviyo uses a 192-node ClickHouse cluster for real-time segmentation and personalization
ClickHouse mediumAdept
Klaviyo replaced a Python-orchestrated segmentation engine built on MySQL and a large Cassandra cluster of pre-aggregated counters with a 192-node on-prem ClickHouse cluster. The cluster is sharded first by company ID and then by profile ID, and computes segment membership with a single query in about one second instead of over an hour. Time-based conditions appear in roughly 60% of segments and used to be reprocessed on a schedule. To avoid that wasted work, the team built an entity-attribute-value table via a materialized view with the property name in the sort key, so conditions can be pushed down at read time. Updates now run in two phases: a lightweight query finds affected profile-segment pairs, which are chunked onto a message queue for parallel workers that can scale independently.
- ClickHouse and The One Billion Row Challenge
ClickHouse mediumAdept
ClickHouse Local solves the One Billion Row Challenge (min/mean/max temperature per station from a 13GB text file) in about 20 seconds on an 8-core Hetzner VM, versus nearly 3 minutes for the Java baseline. Reading lines with LineAsString and splitting on ';' instead of using the CSV parser cut the time from 27.6s to 19.9s. Loading into a Memory table first, or precomputing aggregates with a Materialized View into an AggregatingMergeTree via a Null engine, makes later queries near-instant but costs 21–26s of load time, so neither beats the single-scan query end to end. ClickHouse SQL using randCanonical and a Box-Muller transform also generates the dataset 6.8x faster than the Java generator.
- Chaining Materialized Views in ClickHouse
ClickHouse mediumAdept
ClickHouse materialized views can be chained so that one view reads from a table populated by another, rather than having several views all read from the same Kafka engine table. Using the Wikimedia recent-changes stream, the walkthrough ingests raw events from Kafka into a MergeTree table and builds per-minute aggregation states (uniqState, sumState) in an AggregatingMergeTree. It then adds a 10-minute rollup view that reads those states with -MergeState combinators. The new view only picks up rows ingested after it is created, so older data has to be backfilled with an INSERT ... SELECT, and queries finish with -Merge combinators.