# The Hitchhiker's Guide to Getting Aggregates Out of ClickHouse *March 14, 2026* ClickHouse can compute a running aggregate — total orders, total spend, last active date — correctly and fast. But it has no native way to emit that aggregated data out. Not a change event. The actual computed result, pushed downstream, automatically. You have to work around its architecture to get it out. This post is about that workaround, and a respectful question for the ClickHouse team: why isn't this a first-class feature? --- *The Hitchhiker's Guide to the Galaxy has this to say about streaming data pipelines:* *"Don't Panic."* *It then goes on for several thousand pages about why you should probably panic a little, actually.* --- Okay. So I need to stream customer profiles out of ClickHouse into Kafka. Every time a payment comes in, downstream systems need the full picture: how many orders has this customer placed, how much have they spent lifetime, what categories do they buy. Live. Within seconds. So merchants can say things like "give a coupon to anyone who's spent over ₹5,000 with me" and have it actually work in real time. I have the data in ClickHouse. I need it in Kafka. How hard can this be. I asked Claude. Claude said 10 minutes. I, like Zaphod Beeblebrox confidently piloting the Heart of Gold directly into a star, believed it completely. That was my first mistake. ## Attempt 1: The Obvious Thing ClickHouse has two features that seem made for exactly this. First: [Materialized Views](https://clickhouse.com/docs/en/sql-reference/statements/create/view#materialized-view). SQL that fires automatically every time rows are inserted — like a trigger, but for aggregations. Write your SELECT, ClickHouse runs it on every insert, stores the result somewhere. No polling. No cron. No application code. It just *happens*. Second: the [Kafka table engine](https://clickhouse.com/docs/en/engines/table-engines/integrations/kafka). A fake table that when written to, actually pushes rows to a Kafka topic. The Sirius Cybernetics Corporation would have called this "a friend." They would have been wrong, but in this specific case, it genuinely is one. Put them together. MV fires on insert → aggregates → writes to Kafka engine → message lands in topic. Perfect. Elegant. I was already mentally ordering lunch. ```sql CREATE MATERIALIZED VIEW push_profile_on_payment TO kafka_profiles AS SELECT merchant_id, customer_id, count() AS order_count, sum(amount) AS total_spent FROM events WHERE event_type = 'payment_success' GROUP BY merchant_id, customer_id; ``` I had a test customer — `cust-456` — with 30 orders and ₹9,200 in lifetime spend. I placed one more order for ₹350. Checked Kafka. ```json { "customer_id": "cust-456", "order_count": 1, "total_spent": 350.00 } ``` Hm. That's 1 order. Not 31. That's ₹350. Not ₹9,550. I ran the same query directly in ClickHouse: `SELECT count(), sum(amount) FROM events WHERE customer_id = 'cust-456'`. `31 rows. ₹9,550.` ClickHouse *knew*. It had the answer. It just didn't tell Kafka. It was, as Marvin the Paranoid Android once said about the entire history of the universe, "deeply correct and entirely useless." Lunch was cancelled. ## Why ClickHouse Can't Stream Aggregated Data Okay. I need to figure out what's going on. Let me think through this. ClickHouse doesn't store data the way a normal database does. When you insert rows, it doesn't update an existing file. It writes a brand new immutable compressed chunk to disk — called a *part*. Think of it as a sealed envelope. Every insert: a new envelope dropped on a pile. So after 30 orders, the `events` table on disk doesn't have one tidy row per customer. It has parts — multiple sealed envelopes scattered across disk, each holding some rows from some moment in time: | part | customer_id | rows | amount | |------|-------------|------|--------| | p1 | cust-456 | 12 | ₹3,800 | | p2 | cust-456 | 10 | ₹3,100 | | p3 | cust-456 | 8 | ₹2,300 | These parts merge in the background — on ClickHouse's own schedule, not yours. When you run a SELECT query, ClickHouse opens all the envelopes, joins everything together, and computes the aggregate on the fly. That's why the query returned the right answer. The read path sees all 30 orders across all three parts. Now. The Materialized View. The MV is not a query. It's a trigger. It fires when rows are inserted — and it only sees the envelope being inserted right now. Not the old envelopes. Not the merged state. Just what just arrived. ```mermaid flowchart LR subgraph disk["On disk — the MV has never heard of these"] p1["p1: 12 orders · ₹3,800"] p2["p2: 10 orders · ₹3,100"] p3["p3: 8 orders · ₹2,300"] end subgraph now["New insert — all the MV sees"] p4["order 31 · ₹350"] end p4 --> mv["MV fires"] mv --> kafka["order_count=1 · total=₹350 ❌"] ``` So when the MV ran `count()` on insert, it counted exactly one row. The one that just arrived. The 30 orders in older parts? Completely invisible. As invisible as the total perspective vortex to someone who genuinely doesn't care about their place in the universe. This is not a bug. This is the *point*. Processing only the incoming block at insert time is what makes ClickHouse inserts fast at billions of rows. But it means **aggregation is a read-time operation in ClickHouse, not a write-time operation**. The complete, correct aggregate only exists when you query. Not during an insert. Not after an insert. When you explicitly ask. I tried `AggregatingMergeTree`. It stores partial aggregation states per part that combine during background merges — surely the MV writes partial states, they merge, cumulative answer appears? No. Those states only finalize at query time via `finalizeAggregation()`. The insert trigger still only sees the new rows. There is no hook that carries the fully-merged state at write time. That hook does not exist in ClickHouse. I had four browser tabs of docs open, a half-written Slack message, and a deepening respect for ClickHouse's architecture combined with a deepening problem with my original task. ## The Shape of a Solution — and an Immediately New Problem The Guide would have said: *"When you can't do the thing at write time, do it at read time. Obviously."* I'd figured out that a [Refreshable Materialized View](https://clickhouse.com/docs/en/sql-reference/statements/create/view#refreshable-materialized-view) — new in ClickHouse 23.12, MVs that run on a timer instead of on insert — was the only realistic path. Insert-time MVs were structurally out. A scheduled query that runs the full aggregation and pushes to Kafka would finally see all the parts. Except. Without any scoping, that's a full table scan every 5 seconds. Every customer. Every merchant. Every order in history. Recomputed on a timer. At production data volumes, this is not a query. This is a small disaster with a cron attached. I was also building a whole separate Kafka consumer in my head — one that polls ClickHouse, deduplicates profiles, republishes. Its own service. Its own deploy. Its own on-call rotation. I had signed up for a segmentation feature. I was now apparently signing up for a small data platform. I talked to Boris — a ClickHouse expert who has clearly seen people do exactly this many times before, and was politely not laughing. He asked: why are you scanning the whole table? Scan only the customers who changed. Oh. ## Record Who Changed, Aggregate Them Later The insight is obvious once someone says it. Don't aggregate at insert time — that's impossible. Don't scan everything at read time — that's expensive. Record *which customers* changed, then aggregate only those. The Infinite Improbability Drive of database design: route around the constraint rather than through it. **Step 1 — a tiny staging table. Just IDs and timestamps:** ```sql CREATE TABLE recently_changed ( merchant_id String, customer_id String, changed_at DateTime DEFAULT now() ) ENGINE = ReplicatedMergeTree() ORDER BY (merchant_id, customer_id, changed_at) TTL changed_at + INTERVAL 10 MINUTE DELETE; ``` A lightweight MV writes to it on every payment event. No aggregation — just a customer ID and a timestamp. This is exactly what MVs are good at: writing something small and fast at insert time. ```sql CREATE MATERIALIZED VIEW track_changed TO recently_changed AS SELECT merchant_id, customer_id FROM events WHERE event_type = 'payment_success'; ``` **Step 2 — the refreshable MV, now scoped:** ```sql CREATE MATERIALIZED VIEW customer_profile_snapshot REFRESH EVERY 5 SECOND ENGINE = Kafka('kafka:9092', 'customer-profiles', 1, 'JSONEachRow') AS SELECT merchant_id, customer_id, count(DISTINCT order_id) AS order_count, sum(final_amount) AS total_spent, min(created_at) AS first_order_date, max(created_at) AS last_order_date, groupUniqArray(category) AS purchased_categories, countIf(payment_mode = 'COD') AS cod_order_count FROM events WHERE (merchant_id, customer_id) IN ( SELECT merchant_id, customer_id FROM recently_changed WHERE changed_at >= now() - INTERVAL 1 MINUTE ) GROUP BY merchant_id, customer_id; ``` The `WHERE IN` is everything. ClickHouse uses the IDs from `recently_changed` as a filter, reads the full history for only those customers across all parts, and produces the correct cumulative aggregate. Without touching anyone else's data. Without scanning the universe. ## How It All Fits Together ```mermaid sequenceDiagram participant App as Backend participant CH as events participant RC as recently_changed participant RMV as Refreshable MV (5s) participant K as Kafka App->>CH: payment_success · cust-456 · ₹350 CH-->>RC: MV writes (cust-456, now()) Note over RMV: 5 seconds later RMV->>RC: who changed in the last 60s? RC-->>RMV: cust-456 RMV->>CH: read all events for cust-456 CH-->>RMV: 31 orders · ₹9,550 ✓ RMV->>K: full profile ✓ ``` What lands in Kafka: ```json { "customer_id": "cust-456", "order_count": 31, "total_spent": 9550.00, "avg_order_value": 308.06, "first_order_date": "2025-03-01", "last_order_date": "2026-03-14", "purchased_categories": ["footwear", "apparel"], "cod_order_count": 4 } ``` 31 orders. ₹9,550. Correct. I stared at this for a moment longer than was professionally necessary. Latency: 5–10 seconds. Fine for segmentation. If two orders land in the same window, one combined message, no racing updates. The `recently_changed` table stays tiny because the TTL purges it every 10 minutes. The separate polling consumer I was building in my head? Gone. Downstream just needs deduplication. The Slack message got shorter. I sent it. Lunch happened at 4pm. ## This Is a Workaround. A Good One, But Still. Let me be honest about what this is. We are routing around ClickHouse's architecture to avoid spinning up a Flink cluster. An extra staging table, a scoped refreshable MV, TTL management, interval tuning. It works. Marvin would grudgingly acknowledge it works. But it exists because something native doesn't. ClickHouse already has every piece: the data, the aggregation, the Kafka engine, refreshable MVs. The one missing piece: *when this aggregate changes, emit the updated result automatically.* That's aggregate CDC — change-data-capture at the aggregate level. ClickHouse supports CDC for raw rows. It has no native concept of "the aggregate for this key just changed, push the new snapshot downstream." The architectural reason is clear and honest. MergeTree's design means merges happen on the engine's schedule. A fully consistent aggregate only exists at read time. There are no "aggregate state changed" events — only "new rows inserted" events. That's the tradeoff that makes the engine fast. It's the right tradeoff. But the question, asked respectfully and with genuine curiosity toward a team that has built something remarkable: **Should ClickHouse support this natively?** The hypothetical SQL: ```sql -- this does not exist yet, but should it? CREATE STREAMING AGGREGATE customer_profiles ON events GROUP BY customer_id EMIT TO Kafka(...) ON CHANGE WITHIN 5 SECONDS; ``` ClickHouse has every piece. The wiring just isn't there. Anyone building near-real-time analytics on ClickHouse — segmentation, fraud signals, live leaderboards, customer profiles — eventually needs aggregated results to flow somewhere. Right now, those teams are either building the workaround above, or running a streaming processor whose entire job is to re-query ClickHouse and re-publish. The second option is, as the Guide might put it, *mostly pointless*. Is aggregate streaming on the roadmap? Or is the official position that ClickHouse is an analytics database and streaming belongs in a dedicated processor? Either answer is fine — I'd just like to know. Because the answer shapes how a lot of teams should be thinking about their architecture. If you're from the ClickHouse team, or you've found a cleaner approach: I'd genuinely like to hear it. You know where to find me. I'll be here, re-reading the parts documentation. *Don't Panic.* --- *Thanks to Boris for the dirty-IDs pattern. The `WHERE IN` scoping idea turned a full table scan into a targeted read and made this whole approach actually usable.* *And to the ClickHouse team: the database is genuinely wonderful. This post is a feature request dressed as a war story. You've built something Zaphod Beeblebrox would use — if he could be bothered to read the docs.* --- > "I'd far rather be happy than right any day." > > — Zaphod Beeblebrox