knaxuslearn · build · ship

Projects / Web analytics / Phase 4

Phase 4 of 4 · about 2.5 hours

A summary that keeps itself up to date

You end with a daily summary table fed by a materialized view, and three counts of the same data that match.

A dashboard that shows views per page per day does not need to scan millions of rows each time it loads. We can keep a small summary table and update it as events arrive.

Step 4.1: A materialized view (about 50 minutes)

A materialized view in ClickHouse is a trigger. Each time rows are inserted into web.events, it runs a SELECT over just those new rows and writes the result into a target table. The target uses SummingMergeTree, which adds up the hits of rows with the same sort key when it merges parts. We create both, then insert 100,000 events for 1 November:

CREATE TABLE web.daily_url_hits
(
    day  Date,
    url  String,
    hits UInt64
)
ENGINE = SummingMergeTree
ORDER BY (day, url);
CREATE MATERIALIZED VIEW web.daily_url_hits_mv TO web.daily_url_hits AS
SELECT toDate(event_time) AS day, url, count() AS hits
FROM web.events
GROUP BY day, url;
INSERT INTO web.events
SELECT
    toDateTime('2026-11-01 00:00:00') + intDiv(number * 86400, 100000) AS event_time,
    toUInt32(cityHash64(number, 9) % 50000) AS user_id,
    arrayElement(['/', '/pricing', '/docs', '/blog', '/signup', '/login', '/blog/clickhouse', '/docs/install'], 1 + cityHash64(number, 1) % 8) AS url,
    'IN' AS country,
    'mobile' AS device,
    toUInt32(100) AS duration_ms
FROM numbers(100000);
SELECT count() AS rows_in_target FROM web.daily_url_hits;
SELECT day, url, sum(hits) AS hits FROM web.daily_url_hits GROUP BY day, url ORDER BY day, url LIMIT 5;
┌─rows_in_target─┐
│              8 │
└────────────────┘
┌────────day─┬─url──────────────┬──hits─┐
│ 2026-11-01 │ /                │ 12585 │
│ 2026-11-01 │ /blog            │ 12607 │
│ 2026-11-01 │ /blog/clickhouse │ 12536 │
│ 2026-11-01 │ /docs            │ 12443 │
│ 2026-11-01 │ /docs/install    │ 12384 │
└────────────┴──────────────────┴───────┘

The target table has only eight rows: one per URL for that day. It was filled by the insert, and we did nothing else.

The view summarises each new batch as it arrives.

Step 4.2: Does the summary match? (about 20 minutes)

Never trust a summary you did not check. Add up the hits in the summary and compare them with a count over the real events:

SELECT sum(hits) AS views_from_summary FROM web.daily_url_hits;
SELECT count() AS views_from_events FROM web.events WHERE event_time >= '2026-11-01 00:00:00';
┌─views_from_summary─┐
│             100000 │
└────────────────────┘
┌─views_from_events─┐
│            100000 │
└───────────────────┘

Step 4.3: Insert again, and always sum (about 25 minutes)

We insert the same 100,000 events again, then check both counts:

INSERT INTO web.events
SELECT
    toDateTime('2026-11-01 00:00:00') + intDiv(number * 86400, 100000) AS event_time,
    toUInt32(cityHash64(number, 9) % 50000) AS user_id,
    arrayElement(['/', '/pricing', '/docs', '/blog', '/signup', '/login', '/blog/clickhouse', '/docs/install'], 1 + cityHash64(number, 1) % 8) AS url,
    'IN' AS country,
    'mobile' AS device,
    toUInt32(100) AS duration_ms
FROM numbers(100000);
SELECT sum(hits) AS views_from_summary FROM web.daily_url_hits;
SELECT count() AS views_from_events FROM web.events WHERE event_time >= '2026-11-01 00:00:00';
┌─views_from_summary─┐
│             200000 │
└────────────────────┘
┌─views_from_events─┐
│            200000 │
└───────────────────┘

Both say 200,000. A caution: after the second insert, the summary table holds up to 16 rows until a background merge combines them. Always read it with sum(hits) and GROUP BY, as we did, and never trust a plain row count of a SummingMergeTree table.

Step 4.4: Exact and approximate counting (about 20 minutes)

Counting distinct values exactly needs memory proportional to the number of values. ClickHouse offers cheaper estimates. Compare:

SELECT uniqExact(user_id) AS exact_users, uniq(user_id) AS estimated_users, uniqHLL12(user_id) AS rough_users FROM web.events;
┌─exact_users─┬─estimated_users─┬─rough_users─┐
│       50000 │           50000 │       49369 │
└─────────────┴─────────────────┴─────────────┘

uniq is a good estimate that uses little memory. uniqHLL12 is rougher but smaller still, and here it is about 1% off. Pick exact when the count is an invoice and approximate when it is a dashboard.

Step 4.5: Three counts that agree (about 20 minutes)

Count the events with count(), with the row counts that ClickHouse keeps in its parts, and by adding up per-country groups:

SELECT
    (SELECT count() FROM web.events) AS from_count,
    (SELECT sum(rows) FROM system.parts WHERE database = 'web' AND table = 'events' AND active) AS from_parts,
    (SELECT sum(c) FROM (SELECT count() AS c FROM web.events GROUP BY country)) AS from_groups;
┌─from_count─┬─from_parts─┬─from_groups─┐
│    2200000 │    2200000 │     2200000 │
└────────────┴────────────┴─────────────┘

All three give 2,200,000: our 2,000,000 events, plus the 200,000 added in Phase 4.

Phase 4 done

We started with a site that leaves millions of traces. You now have a table that stores them in columns, answers questions by scanning only what it needs, explains itself through EXPLAIN, keeps a summary up to date on every insert, and agrees with itself three ways.