ClickHouse
medium 25 minClickHouse 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
| site | time | ms |
|---|---|---|
| 7 | 10:02 | 40 |
| 3 | 10:01 | 25 |
| 7 | 10:00 | 31 |
| 3 | 10:03 | 60 |
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
| second | new | merged | active |
|---|---|---|---|
| 1 | 2,000 | 200 | 1,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
criticalEach insert makes a part. Merges fall behind until inserts are rejected.
Wrongfor e in events: client.insert('hits', [e])Rightfor batch in chunks(events, 50_000): client.insert('hits', batch)Partitioning by a fine key
criticalEvery partition has its own parts. A partition per customer or hour makes far too many.
WrongPARTITION BY (customer_id, toHour(ts))RightPARTITION BY toYYYYMM(ts)ORDER BY (customer_id, ts)Trusting the primary key to be unique
majorMergeTree stores duplicates. Replacing engines remove them at an unknown time.
WrongSELECT sum(amount) FROM payments_latestRightSELECT sum(amount) FROM payments_latest FINALAdding up distinct users
majorThe same person in two minutes is counted twice.
WrongSELECT sum(users) FROM per_minuteRightSELECT 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.