knaxuslearn · build · ship

Projects / Web analytics

ClickHouse · about 10 hours · 4 phases

Build a web analytics backend in ClickHouse

When we run a website, every click leaves a trace: who came, from where, to which page, and for how long. A busy site produces millions of these events a day, and the questions never stop. Which pages are popular, how fast is the site in each country, how many different visitors came yesterday? A normal database that stores one row at a time and reads whole rows starts to struggle. In about 10 hours we will build the answer ourselves in ClickHouse, a database made for exactly this: a table of two million events, queries that scan it in a blink, a look at how it avoids reading what it does not need, a running summary that updates itself, and a check that three different counts agree.

You work in four phases of about 2.5 hours each. Every phase ends with something you can run and see. By the end you will have:

  • an events table that you understand down to the files it creates,
  • two million events loaded in a few seconds, and what they cost on disk,
  • analytics queries for pages, days, countries and the slowest visitors,
  • an explanation, read from the database itself, of why one query reads 2 of 136 blocks and another reads all 245,
  • a summary table kept up to date by a materialized view,
  • three counts of the same data that must match.

You only need to know SQL basics: SELECT, WHERE, GROUP BY.

The four phases

  1. A table, and the files behind it

    You end with an events table, eight rows in it, and a clear picture of what a part is.

    • 1.1 Create the table25 min
    • 1.2 Five events20 min
    • 1.3 Look inside25 min
    • 1.4 Many small inserts25 min
    • 1.5 Merging25 min
  2. Two million events

    You end with two million events, and a table of how many bytes each column takes.

    • 2.1 Generate and load40 min
    • 2.2 What it costs on disk30 min
    • 2.3 Partitions25 min
  3. Questions and the sparse index

    You end with five analytics queries, and a plan that shows why one is cheap and one is not.

    • 3.1 The most visited pages25 min
    • 3.2 Days and countries30 min
    • 3.3 Shares15 min
    • 3.4 Why one query is cheap40 min
    • 3.5 Why one query is not25 min
    • 3.6 The counts behind it15 min
  4. 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.

    • 4.1 A materialized view50 min
    • 4.2 Does the summary match?20 min
    • 4.3 Insert again, and always sum25 min
    • 4.4 Exact and approximate counting20 min
    • 4.5 Three counts that agree20 min

Start with the setup →