AlgoViz

ClickHouse

medium 25 min

ClickHouse is a column-oriented SQL database for analytics.

See it run

Batches become parts, parts merge, queries skip. See the cost of each choice.

Operations

Insert a batch

Four rows arrive unsorted in one insert.

Step 1 of 5

The batch

sitetimems
710:0240
310:0125
710:0031
310:0360

One insert, 4 rows

Rows arrive in any order.

Step 1: The batch

def insert(rows):    for month, group in by_partition(rows):        group.sort(key=sorting_key)        part = {c: compress(col) for c, col in columns(group)}        publish(month, part)
Work
1 part per partition
Watch out for
Tiny inserts
4 single inserts
4 parts

The part never changes after it is published.

In the real world

The same clickhouse doing real jobs. Pick one and step through it.

A service inserts one row for each request, 2,000 a second.

Step 1 of 3

First second

secondnewmergedactive
12,0002001,800

Above 1,000: inserts are slowed

2,000 parts appear. Assume merges remove 200 a second.

Step 1: First second

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • One row per insert

    critical

    Each insert makes a part. Merges fall behind until inserts are rejected.

    Wrong
    for e in events:    client.insert('hits', [e])
    Right
    for batch in chunks(events, 50_000):    client.insert('hits', batch)
  • Partitioning by a fine key

    critical

    Every partition has its own parts. A partition per customer or hour makes far too many.

    Wrong
    PARTITION BY (customer_id, toHour(ts))
    Right
    PARTITION BY toYYYYMM(ts)ORDER BY (customer_id, ts)
  • Trusting the primary key to be unique

    major

    MergeTree stores duplicates. Replacing engines remove them at an unknown time.

    Wrong
    SELECT sum(amount) FROM payments_latest
    Right
    SELECT sum(amount) FROM payments_latest FINAL
  • Adding up distinct users

    major

    The same person in two minutes is counted twice.

    Wrong
    SELECT sum(users) FROM per_minute
    Right
    SELECT uniqMerge(users_state) FROM per_minute

Interview tips

  • How to explain it

    • Columns stored apart and sorted.
    • Inserts make parts, merges join them.
    • Queries skip granules and columns.
  • Design order

    • Write the main query.
    • Choose ORDER BY from its filters.
    • Choose PARTITION BY from deletion.
  • Reach for it when

    • Events are appended.
    • Totals over very many rows.
    • Fresh dashboards.
  • Choose something else when

    • Rows change all day.
    • One row by id is the query.
    • Transactions span tables.