AlgoViz

ClickHouse

medium 25 min

ClickHouse is a column-oriented SQL database for analytics.

Video lesson · Chapter 1 of 5

Dinner orders arrive in a batch

0:00 / 3:23

ClickHouse in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

ClickHouse stores each column of a table separately, sorted by a key you choose and compressed. A query reads only the columns it names. A small index in memory tells it which ranges of rows cannot match, so they are skipped.

It is open source under the Apache License 2.0, and also sold as a managed service, ClickHouse Cloud. You can run it as one program on a laptop or as a cluster with shards and replicas.

Why it exists

A dashboard asks for a few columns over very many rows: requests per country for the last week. A row store must read every whole row. A column store reads a fraction of the bytes, and processes them in blocks that suit the processor.

The price is in writing. Data should arrive in batches, old rows are not changed in place, and there is no index that finds one row at once. So ClickHouse sits beside the transactional database, not instead of it.

A short history

  1. 2009

    Work starts inside Yandex as an experiment: can reports be computed in real time from raw data that keeps arriving?

  2. 2016

    ClickHouse is released as open source.

  3. 2018

    Cloudflare describes HTTP analytics for 6 million requests a second on a 36-node ClickHouse cluster.

  4. 2021

    ClickHouse, Inc. is announced in September with the development team moving over from Yandex.

  5. 2024

    The paper describing the system's design appears in the Proceedings of the VLDB Endowment, volume 17.

Words to know

Part
An immutable directory with one inserted or merged batch, sorted by the key.
Merge
A background job that joins several parts into one larger part.
Granule
The smallest range of rows that is read, 8,192 rows by default.
Sparse primary index
One entry per granule, kept in memory. It is not unique.
Sorting key
The ORDER BY of the table: the physical order of rows inside a part.
Partition
A group of parts, often one month, that can be dropped at once.
Materialized view
Here: a trigger that transforms each inserted block into another table.
Keeper
The coordination service that stores what replicas must agree on.

How it works

Step through the idea, or press Play.

Step 1 of 3

Batch. Thousands of rows become one sorted, compressed part

Understand it

Start here

The spice stall with long drawers

Imagine a spice stall. Every order names how much pepper, cumin, paprika and salt was sold. Instead of keeping whole order slips, the trader keeps one long drawer per spice, with one card per order, always in the same sequence.

One long drawer per spice
Order 1Pepper 2Cumin 5Paprika 1Salt 4One order

Changing one old card is slow, because the drawers are packed. Adding a new tray is quick.

The product

What you get

Facts checked November 2026

TopicFact
LicenceApache License 2.0
ReleasesYear and month, such as 26.10. Some are LTS, such as 26.3 and 26.8
FormsServer, command line tool, in-process library (chDB), managed cloud
InterfacesHTTP on 8123, native protocol on 9000
Main table engineMergeTree and its family
CoordinationClickHouse Keeper (Raft), protocol compatible with ZooKeeper
SQL
CREATE TABLE hits(    site_id     UInt32,    ts          DateTime,    country     LowCardinality(String),    path        String,    user_id     UInt64,    latency_ms  UInt32 CODEC(T64, ZSTD(1)),    INDEX idx_user user_id TYPE bloom_filter GRANULARITY 4)ENGINE = MergeTreePARTITION BY toYYYYMM(ts)ORDER BY (site_id, ts)TTL ts + INTERVAL 13 MONTH DELETE;
Read it from the bottom: rows are kept 13 months, ordered by site and time, and grouped in monthly partitions. The skip index may help rare users, so measure it.

Inside

From an insert to a part

Events on their way to a dashboard

Collectors send events to a log. A batch writer inserts them into one ClickHouse server, where each insert becomes a small part, a background merge makes a large part, and a query from a dashboard reads the parts.
The log absorbs bursts. The writer turns many events into few inserts.

What one insert does

  1. 1

    Split by partition

    Rows for different months go to different parts. An insert that covers many partitions makes many parts and is atomic only within each.

  2. 2

    Sort

    Rows are ordered by the sorting key.

  3. 3

    Compress by column

    By default LZ4 for small parts and ZSTD(3) for parts from 100 MiB. Codecs such as Delta can be set for a column.

  4. 4

    Write a directory

    Small parts keep all columns in one file (compact). Larger ones use a file per column (wide, from 10 MiB by default).

  5. 5

    Publish

    The part becomes visible. Merges will replace it later.

The shape resembles an LSM tree: sorted runs on disk, joined in the background. One difference is that an insert writes a sorted part directly and there is no level structure to look up one key.

Why one insert per row fails

parts per second=rows per secondrows per insert2,0001=2,0002,00020,000=0.1\text{parts per second} = \frac{\text{rows per second}}{\text{rows per insert}} \qquad \frac{2{,}000}{1} = 2{,}000 \qquad \frac{2{,}000}{20{,}000} = 0.1
An assumed 2,000 rows a second. Row by row, merges can never keep up. Batches of 20,000 make one part every ten seconds.

The numbers that protect merges

Setting or adviceValueEffect
Recommended batchAt least 1,000 rows, ideally 10,000 to 100,000Fewer, larger parts
Recommended rateAbout one synchronous insert a secondMerges keep up
parts_to_delay_insert1,000 active parts in a partitionInserts are slowed
parts_to_throw_insert3,000 active parts in a partition"Too many parts" error
The error is a message about your insert pattern or your partitions. Raising the limit hides it.

Writes

Asynchronous inserts and safe retries

When many small clients cannot batch, the server can do it. With async_insert the server collects rows in a buffer and writes one part when the buffer is large or old enough. The current documentation lists it as on by default, with wait_for_async_insert = 1, so the answer comes after the flush. Earlier releases had it off, so check your server.

Many clients, one part

With waiting turned off, the answer comes before the part is written: an error or crash can lose rows without the client knowing.

Safe pipeline

  • Retry the identical batch: the same rows in the same order
  • Replicated tables keep a deduplication log of recent blocks
  • Plain MergeTree needs non_replicated_deduplication_window above 0
  • Put an event id in the row, so duplicates can be found

Not safe

  • Fire and forget for data you bill from
  • Retrying with a different batch boundary
  • Assuming the primary key is unique
  • One insert spread over 400 daily partitions

Reads

Granules and the sparse index

The index holds the key of the first row of every granule. For 100 million rows that is about 12,208 entries, small enough to stay in memory. A query that filters on the first key column finds the granules by binary search. Then whole granules are read, because there is no entry for a single row.

Entries in the index

⌈100,000,0008,192⌉=12,208\left\lceil \frac{100{,}000{,}000}{8{,}192} \right\rceil = 12{,}208
A granule may hold fewer rows when rows are large, because of a limit in bytes. The estimate decides nothing about disk: it shows why the index always fits.

What a query skips

EXPLAIN indexes = 1 shows how many parts and granules survive each step.

ORDER BY (site_id, ts): who benefits?

FilterIndex useRemedy if it is common
site_id = 7ExcellentNone
site_id = 7 and last weekExcellentNone
last week, all sitesPartition pruning, weak insideA rollup by day
user_id = 99NoneSkip index if values cluster, a projection, or another table in that order
Put the columns you filter by most first, and prefer fewer distinct values before more. Partitioning is for managing data, such as dropping a month, and not the first tool for speed.

Bytes read by a total

109 rows×40 columns×8 B=320 GB109×2×8 B=16 GB10^9 \text{ rows} \times 40 \text{ columns} \times 8\,\text{B} = 320\,\text{GB} \qquad 10^9 \times 2 \times 8\,\text{B} = 16\,\text{GB}
An assumed table. Two of forty columns is 5% of the bytes, before compression and skipping.

Summaries

Materialized views and rollups

In ClickHouse an incremental materialized view is a trigger on insert. It runs its query on each new block and writes the result to a target table. It does not see rows that were there before, nor later changes to a joined table. The target uses an engine that adds partial results together during merges.

SQL
CREATE TABLE hits_per_minute(    site_id UInt32,    minute  DateTime,    hits    SimpleAggregateFunction(sum, UInt64),    users   AggregateFunction(uniq, UInt64))ENGINE = AggregatingMergeTreeORDER BY (site_id, minute);CREATE MATERIALIZED VIEW hits_per_minute_mv TO hits_per_minute ASSELECT site_id, toStartOfMinute(ts) AS minute,       count() AS hits, uniqState(user_id) AS usersFROM hits GROUP BY site_id, minute;-- Always aggregate again: partial rows may not be merged yetSELECT minute, sum(hits) AS hits, uniqMerge(users) AS usersFROM hits_per_minuteWHERE site_id = 7 AND minute >= now() - INTERVAL 1 HOURGROUP BY minute ORDER BY minute;
uniq is approximate, and its state can be merged across minutes. A plain count of users per minute cannot be added up to users per hour.

Four relatives of MergeTree

  • ReplacingMergeTree

    Keeps the latest row per sorting key, when a merge happens. Use FINAL or argMax for exact answers.

  • SummingMergeTree

    Adds numeric columns of equal keys during merges.

  • AggregatingMergeTree

    Merges stored aggregate states, such as distinct users.

  • CollapsingMergeTree

    A row with sign -1 cancels an earlier row with sign 1.

Changes

Updates, deletes and transactions

You wantToolKnow this
Forget old dataTTL or DROP PARTITIONCheap: whole parts go
Delete some rowsDELETE FROMBy default rows are masked by a mutation, and removed by later merges
Update a few rowsUPDATE with patch partsFor up to about 10% of a table. Needs block number columns enabled
Rewrite a columnALTER TABLE ... UPDATEHeavy mutation that rewrites parts
Keep the latest stateReplacingMergeTree with a versionDuplicates remain until a merge
Several tables atomicallyAnother databaseTransactions across statements are experimental
One insert into one partition as one block is atomic. If your design needs many row updates a second, the fact belongs in an OLTP store.

Why FINAL exists

Before the merge, a plain SELECT shows both. FINAL merges at query time and costs more.

Growth

Shards, replicas and Keeper

Two shards, two replicas each

A client sends a query to a Distributed table. It asks replica A of each of two shards. Within a shard, parts are copied from replica A to replica B. Three Keeper nodes hold the names of parts.
Shards split the data. Replicas copy it. Keeper holds what all replicas must agree on, not the rows. Only one arrow per shard is drawn.
  1. 1

    Replication

    Asynchronous and multi-master: an insert may go to any replica and is copied later. By default the insert waits for one replica only, so losing that server can lose the newest rows. insert_quorum waits for more.

  2. 2

    Sharding

    A Distributed table stores nothing. It sends a query to every shard and combines partial results. With replicated tables below it, set internal_replication to true; the default is false.

  3. 3

    Keeper

    Three nodes of ClickHouse Keeper tolerate one failure. If Keeper is unavailable, replicated tables become read-only. See consensus in practice: etcd.

  4. 4

    Separated storage

    ClickHouse Cloud uses SharedMergeTree: data in object storage, and compute that can be added without copying parts. Self-hosted clusters use ReplicatedMergeTree.

Operations

What to watch, and joins

Watch

  • Active parts per partition (system.parts)
  • Merges and mutations in progress
  • Replication queue and read-only replicas
  • Slow queries and memory (system.query_log)
  • Disk space: merges need room to write

Guard

  • Set memory, time and row limits for each user
  • Keep dashboards on rollups, not on raw rows
  • Separate ad-hoc users from the product
  • Back up to object storage: replicas copy mistakes

How to bring names to facts

Joins work and have several algorithms, but a denormalized table is cheaper at query time. LowCardinality(String) makes repeated text small.

Decide

When to choose it, and when not

Choose it when

  • Many rows, few columns, totals and groups
  • Answers in seconds or less while data keeps arriving
  • Facts are appended and rarely changed
  • Logs, metrics, product analytics, ad clicks

Do not when

  • You fetch or update one row by id
  • You need transactions over several tables
  • The data fits comfortably in PostgreSQL
  • Search ranking is the product: use Elasticsearch

Neighbours

ChoiceBetter whenWeaker when
TimescaleDBTime series beside relational data, full SQL transactionsVery large scans over many columns and teams
A cloud warehouseBatch reports, many teams, no servers to runUser-facing dashboards with many small queries
FlinkWindows and alerts while events flowAsking a new question about last year
Files with an embedded engineOne analyst, one machineConstant ingestion and many users
ClickHouse often stands behind Kafka, as in ad click aggregator and metrics monitoring.

Cost is processor time for queries, disk for compressed columns and room for merges, plus the people who run Keeper, upgrades and schema changes. Managed services charge for compute and storage separately. Test with your own data: compression and speed depend on the sorting key.

Summary

The whole topic in one minute.

ClickHouse wins analytics by reading less: only the needed columns, only the granules that can match, and compressed. The sorting key is the most important choice you make.

Insert in batches or let asynchronous inserts build them, because every insert makes a part. Treat rows as facts that do not change. Retries need deduplication, replicas lag, and Replacing tables remove duplicates at an unknown time. Use rollup tables for dashboards and drop old partitions to forget.

  • Columns are stored apart, sorted and compressed, so totals read few bytes.
  • Every insert makes a part. Batch, or let asynchronous inserts batch.
  • The sparse index has one entry per 8,192 rows and enforces no uniqueness.
  • Choose ORDER BY from your filters and PARTITION BY from how you delete.
  • Merges happen at an unknown time, so aggregate again or use FINAL.
  • Replication is asynchronous, and Keeper is a dependency.

Sources