Postgres has been my go-to database for almost all of my personal projects. Things changed when I joined my current workplace. We use a mix of data stores there, and ClickHouse is one of them. Luckily I’ve got to work on it a lot. It was my first time with a columnar database; before this I’d mostly used either an RDBMS or NoSQL databases.
ClickHouse is ridiculously fast at what it’s built for, i.e. data aggregations. But it also has a bunch of behaviours that surprised me coming from Postgres. Some of them cost us real money before I understood them. These are the ones that stood out:
- Deleting stuff doesn’t actually delete it
- The query cache can straight up lie to you
- One busy replica scales up all of them
FINALlooks easy but it’ll hurt you- Your sort key matters way more than you think
- Separate compute isn’t really that separate
But before we get into them, there’s one thing you kinda need to know first, because it explains pretty much everything that’s coming.
Okay so first, parts never change
In Postgres, when you do an UPDATE or a DELETE, the rows basically get changed in place. Old versions hang around for a bit until vacuum comes and cleans them up, but the table you query is pretty much the table you changed.
ClickHouse doesn’t work like that at all. (I’m talking about the MergeTree family of engines here, which is what almost everyone uses anyway.)
- Every
INSERTwrites a new chunk of data to disk called a part, and once it’s written, that’s it, it never changes. - Inside a part, rows are sorted by the table’s
ORDER BYkey and stored column by column. - Rows are grouped into granules of 8,192 rows, and the primary index only keeps one entry per granule, not one per row.
- In the background, ClickHouse keeps merging small parts into bigger ones, and it decides when that happens, not you.
So yeah, a part is never edited. If something needs to change, ClickHouse just writes a new part and throws the old one away later. Keep this in the back of your head, because quirks 1, 2 and 4 all come from this one thing.
1. Deleting stuff doesn’t actually delete it
We had a big table holding many copies of each row, one for every version of a tenant’s data. Most of it was old versions that nobody read anymore. I wanted to delete them, to save storage costs. In Postgres that’s a DELETE and a vacuum. In ClickHouse it turned into a week-long rabbit hole.
Your rows are just hidden, not gone
When you run a normal DELETE FROM in ClickHouse, you get what’s called a lightweight delete:
DELETE FROM events
WHERE tenant_id = 42 AND version_id < 230;
And here’s the thing, it doesn’t actually remove anything lol. It just writes a small hidden column called _row_exists that marks those rows as deleted, and every query after that filters them out. The rows only really go away when the part they live in gets rewritten, either by a merge or a mutation.
I figured it would at least make queries faster, since there’s less data to read now, right? So I measured it. We had two tenants copied from the same source, both with the same ~4.36M rows. On one of them I deleted about 18% of the rows (788k) with a lightweight delete, and left the other one alone. Then I ran the same queries on both, before any merge had kicked in:
| Query | Untouched | Deleted, not merged yet |
|---|---|---|
| Totals by category | 68.4 ms | 72.8 ms (+6%) |
| Daily trend | 68.9 ms | 82.2 ms (+19%) |
| Source breakdown | 68.4 ms | 80.9 ms (+18%) |
| Top users | 118.1 ms | 127.7 ms (+8%) |
| Latest items list | 60.5 ms | 76.4 ms (+26%) |
The deleted version was slower somehow lol. Rows read were the same on both (~4.36M), and bytes read were about 2% higher, because ClickHouse now also has to read the deletion mask and apply it. A granule only gets skipped if every single row in it is deleted, and our deleted rows were scattered all over the place among the live ones, so nothing got skipped.
So when does the merge actually happen?
Whenever ClickHouse feels like it. This in particular really annoyed me to be honest. Merges aren’t scheduled. The merge selector picks runs of similar-sized parts in the same partition, and a few settings made it worse for us:
| Setting | Our value | What it meant |
|---|---|---|
max_bytes_to_merge_at_max_space_in_pool | 150 GiB | A part near or above this size never gets merged again |
exclude_deleted_rows_for_part_size_in_merge | 0 | A part that’s 90% deleted still counts at full size for merge choices |
min_age_to_force_merge_seconds | 0 | Nothing forces old parts to merge, ever |
Most of our old data sat in 50–150 GiB parts. Small recent parts merged quickly and dropped their deleted rows. The big old ones stayed masked more or less indefinitely. Deleted, still on disk, still billed. Like imagine thinking you’ve done cost optimisations only to see the needle not moving on the bills 😭
Fine, how do I actually delete stuff?
Okay to be fair, ClickHouse does have hard deletes. It’s just that every option costs you in a very different way:
| Method | What it does | When disk is freed | Cost |
|---|---|---|---|
DELETE FROM ... WHERE (lightweight) | Marks rows as deleted | After a merge | Cheap now; the rewrite comes later, or never |
ALTER TABLE ... DELETE WHERE (mutation) | Rewrites every affected part without the rows | When it finishes | Rewrites every part containing a matching row. For us, nearly the whole table |
ALTER TABLE ... APPLY DELETED MASK | Rewrites parts that carry a deletion mask | When it finishes | Same rewrite, but only for masked parts |
ALTER TABLE ... DROP PARTITION | Removes a whole partition (metadata operation) | Instantly | Almost free, but only if the whole partition is garbage |
| TTL | Deletes rows by age during merges | As merges happen | Based on time, not “keep the latest 3 versions” |
DROP PARTITION is the dream, but our partitioning ruled it out. The table was partitioned by a hash of the tenant ID, so every partition had live and dead versions from a bunch of tenants all mixed together. Drop one, and you take live data down with it. Not great.
Mutations had their own fun surprises too:
- The table only allowed one mutation per replica at a time (
max_number_of_mutations_for_replica = 1), so everything just sat in a queue behind whatever was already running. - A
DELETEwithout a partition filter goes through every part of the table, even the ones that can’t possibly have matching rows. One of ours was on track to take ~90 minutes, and almost all of that was just checking parts that had nothing to delete. AddingIN PARTITIONbrought it down to a few minutes. KILL MUTATIONdoesn’t roll anything back. Whatever it already rewrote stays rewritten. So yeah, no undo button.
What we ended up doing
What finally worked was doing the whole thing the other way around. Instead of deleting the 90%+ we didn’t want, we copied the small bit we did want into a staging table and swapped it in:
-- 1. copy only the versions we keep into a staging table with the same structure
INSERT INTO events_staging
SELECT * FROM events
WHERE _partition_id = '16' AND (tenant_id, version_id) IN (SELECT ... FROM versions_to_keep);
-- 2. verify row counts and checksums per version, then atomically swap the partition
ALTER TABLE events
REPLACE PARTITION ID '16' FROM events_staging;
REPLACE PARTITION just throws the old parts away whole, so you get your disk back a few minutes later (after old_parts_lifetime). You only read and write the 3–10% you’re keeping, instead of rewriting everything. The catch is you have to stop writes to that partition while you’re copying, because anything that lands mid-copy just gets lost. Thankfully our local test caught this one.
Looking back, the real lesson is to design for DROP PARTITION from day one. If old data lands in its own partitions (by date, or by version), cleaning it up is just a quick metadata operation instead of a background job that runs for days. And even better, just don’t write data you’ll need to delete later. Our final fix was literally to stop copying unchanged rows into every new version.
2. The query cache can straight up lie to you
ClickHouse has a query cache that stores the final result of a SELECT. You turn it on with use_query_cache = 1, and if the same query comes in again, it just hands back the stored result without reading any data.
The thing that got me is that it never gets invalidated when the data changes. Inserts, merges, deletes, even replacing the table’s data entirely, none of it touches the cache. ClickHouse’s own docs literally call it “transactionally inconsistent”. An entry only stops being served when:
- its TTL runs out (
query_cache_ttl, 60 seconds by default), - it gets evicted because the cache is full,
- someone runs
SYSTEM DROP QUERY CACHE(or... TAG 'x') on each server, since the cache is per server, - a query bypasses it with
enable_reads_from_query_cache = 0, which recomputes the result and overwrites the entry, - the server restarts.
And that’s pretty much it.
Why would anyone build it like this??
My first reaction was honestly “wait, what’s even the point of a cache that can be wrong?” But it’s on purpose, and it kinda makes sense once you think about how analytical tables behave. They’re changing all the time, with pipelines inserting every few seconds and parts merging constantly. If every write wiped the cached results for its table, a busy table’s cache would basically never get a hit. And working out exactly which results an insert affects would make every single write slower.
Fun fact, MySQL actually tried it the other way. Its old query cache did invalidate on every write, and under heavy writes it caused so much contention that it got deprecated and then removed completely. ClickHouse just went the other way.
And for analytics, slightly stale data is usually totally fine. A total over millions of rows barely moves in a minute, and getting the number from 30 seconds ago in 2 ms is a way better deal than recomputing it in 1.5 s.
The other caches are fine though
This is where the whole “parts never change” thing really pays off. ClickHouse has a bunch of caches, and the query cache is the only one that can go stale:
| Cache | What it stores |
|---|---|
| Primary index cache | The sparse sort-key index |
| Mark cache | Where each granule sits inside the column files |
| Query condition cache | Which granules a WHERE condition matched before |
| Filesystem cache | Data from object storage, kept on local SSD |
| Uncompressed cache | Decompressed blocks |
| Query cache | Final query results |
Every cache except the last one stores data that’s tied to a specific part. And since a part never changes, its cached data can never be wrong. When the data changes, new parts show up, and the cache entries for the old parts just stop getting used and get evicted eventually. The query cache is the odd one out because it stores a result, and a result depends on whichever parts happened to exist when it was computed.
A few more gotchas
- It’s per replica. With N replicas behind a load balancer, a repeat query only hits the cache if it lands on the same server as the first one, which is roughly 1/N of the time for scattered traffic.
- The default limits are pretty small: 1 GiB, 1,024 entries, and 1 MiB per result, per server. They’re server settings though, so you can bump them up.
- Non-deterministic functions blow up. If a query uses
now()ortoday()with the cache on, it just fails by default (query_cache_nondeterministic_function_handling = 'throw').
Hacking your own invalidation
Since you can’t really delete entries, the trick is to change the key instead. query_cache_tag is part of what makes two queries count as “the same”, so if you stick the data version in the tag, new data gets new cache entries and the old ones just quietly expire:
SELECT source, count()
FROM events
WHERE tenant_id = 42 AND version_id = 241
GROUP BY source
SETTINGS
use_query_cache = 1,
query_cache_tag = 'tenant:42:rev:57', -- bump the revision when data changes
query_cache_ttl = 600; -- the backstop
In the end we parked this idea though. Our app already had its own versioned cache in front of ClickHouse, and adding a second, inconsistent cache underneath it just wasn’t worth the risk of someone seeing stale numbers right after hitting refresh.
3. One busy replica scales up all of them
Okay, this one hurt the most money-wise.
We run ClickHouse Cloud with a few replicas and vertical autoscaling, and our load is super spiky. Like 20% at 10:00, 100% for a few minutes at 10:30, and then back down again. I expected the busy replica to just get bigger. Nope. Here’s what actually happens:
- Autoscaling resizes all the replicas together. One replica gets hot, and all of them scale up.
- Scaling up actually replaces the replicas. New, bigger ones spin up next to the old ones, and then the old ones go away. Over a month, the whole set got swapped out again and again. And every swap starts with cold caches (the local SSD cache starts empty), so queries actually get slower right after scaling up, which is exactly when you need them to be fast. Kinda ironic.
- It stays big for hours. After a short burst, our logs showed the cluster sitting at the larger size for hours before it finally scaled back down.
Over a month, all of this really added up:
| Metric | Value |
|---|---|
| vCPU actually used vs provisioned | Under a third of what we paid for |
| Time spent at maximum size | Most of the month |
| Time at maximum size while mostly idle | Close to half the month |
| Scale-ups | Several per day |
So for almost half the month, we were paying for the biggest cluster while using well under half of it. And the weird part? Cutting our average load barely changed the bill. Since the cluster stayed big for so long after every spike, only the peaks decided what we paid.
And bigger machines didn’t even help
And to make it even worse, there was a max_threads = 4 limit on the database user, so every query was capped at 4 threads no matter how big the replica was. So scaling a replica all the way up didn’t make any single query faster. It just made room for more queries to run at the same time.
Which is a pretty good argument for scaling out instead of up. ClickHouse Cloud has horizontal autoscaling too (it was still in beta when we looked at it), which adds and removes whole replicas of a fixed size. You can’t use it together with vertical autoscaling though. We replayed a month of our real CPU usage through a model of both, and fixed-size replicas that scale by count came out noticeably cheaper. They also spent less time maxed out at peaks, because the replica count could go past our old vertical ceiling.
We also looked at compute-compute separation, where you run separate services for dashboards, ad-hoc analysis, ingestion pipelines and so on, all on the same shared storage. That one actually came out more expensive on its own, because each service keeps its own minimum size and holds onto its own spikes for hours. It’s great for isolation, but don’t expect it to save you money by itself.
4. FINAL looks easy but it’ll hurt you
ReplacingMergeTree is the usual pick when you only want to keep the latest version of each row. But since parts are immutable, deduplication only happens during merges. Until a merge happens, multiple versions of the same row just sit there side by side, and a plain SELECT gives you all of them.
The easy fix is to slap FINAL on it:
SELECT * FROM accounts FINAL WHERE account_id IN (...);
FINAL deduplicates at read time, which means it merges the matching data in memory on every single query. On a wide table, that gets expensive really fast. Our top FINAL query was an account lookup that read some big map columns, and it was our most frequent cause of memory-limit failures. CPU spiked every time it ran.
What worked better was picking the latest version ourselves using just the narrow columns, and then fetching the wide columns only for those rows:
-- tie-break same-second versions by insert block (from the part name), then row position
SELECT account_id,
argMax(revision_id, (updated_at, toUInt64(splitByChar('_', _part)[3]), _part_offset)) AS latest
FROM accounts
WHERE account_id IN (...)
GROUP BY account_id;
This gave back exactly the same rows as FINAL on real lookups, and ran in about 135 ms instead of 240 ms, with less CPU too. Those extra tie-breakers matter btw. If two versions get written in the same second, you need a deterministic winner, and FINAL picks whichever one was inserted last, so this query has to do the same.
5. Your sort key matters way more than you think
In Postgres, you can pretty much just add an index later for whatever query you need. In ClickHouse, the ORDER BY key is the primary index, and it’s sparse, with one entry per 8,192-row granule. If your WHERE doesn’t line up with the start of the sort key, ClickHouse ends up reading everything.
A few things I learned the hard way here:
- Forgetting one filter can be really, really bad. Our big table was sorted by
(tenant_id, version_id, ...), and once I forgot the version filter in a query. It read every stored version of that tenant’s data, which came to 292 GiB for a single query 💀 - Push every filter you can into
PREWHERE. On our biggest dashboard, adding the date range to the innerPREWHERE(date was part of the sort key) took data read from 213 GiB down to 16 GiB across its views, and CPU from 626 s to 137 s, with the exact same results. - An
ORcan turn off index skipping. One branch of a condition couldn’t use the date filter, and because of theOR, ClickHouse stopped skipping granules on both branches. Splitting it into aUNION ALLof two properly filtered reads fixed it. - Scan once, aggregate many ways. We had three charts reading the same rows, so we squashed them into one query with
GROUPING SETS ((region, source), (region, device), (region, browser)). The p90 wait went from 31 s to 3.2 s. - Column width matters more than row count. A
SELECT *over wide text columns doesn’t just slow down that one query. It also fills up the disk and mark caches with stuff nobody else needs, and kicks out what other queries were using.
6. Separate compute isn’t really that separate
At one point I was running a big cleanup and didn’t want it to slow down the dashboards. Coming from MongoDB, my first instinct was “just run it on a separate node”. ClickHouse Cloud has compute-compute separation, so I thought cool, problem solved.
Well, mostly, but not for writes. You can send a DELETE from a second service, but the background work it kicks off (mutations, merges) can run on any read-write service that shares the storage, including the one serving customers. Read-only services don’t do any background work at all. To really fence it off, you’d have to turn off background merges on the main service, which is way too big a change for one cleanup.
What did help was workload scheduling. You tag queries with a workload setting, give each workload a CPU weight, and send background mutations to their own workload using mutation_workload. That, plus small partition-scoped deletes run during off-peak hours, got us most of the way there.
Stuff I wish someone had told me earlier
- Design your partitions around how you’ll delete data. If cleaning up old data can’t be a
DROP PARTITION, it’s gonna be a background rewrite of your whole table. - Don’t store what you don’t need. Every row you write, you’ll eventually pay to read, merge and delete.
- Tag every query with
log_comment, and give each service its own user. If every service shares one user and nothing is tagged, figuring out “who’s eating all the CPU?” turns into an archaeology project. - Get comfy with
system.query_log(including the rotatedquery_log_Ntables, which you can query throughmerge('system', '^query_log')). It tells you rows read, bytes read, memory and CPU for every query. Almost everything in this post started from there. - Watch the peaks, not the averages, especially if you’re on autoscaling.
- Rate-limit your own fan-out. Our worst overload wasn’t even a bad query. It was one dashboard firing 60 requests at once, each split into ~25 monthly queries, which took the cluster from ~5 busy cores to ~68 in under a minute.
Even with all of this, ClickHouse is still one of the most impressive pieces of software I’ve worked with. Once you accept that parts never change, and that merges happen on ClickHouse’s schedule and not yours, most of these quirks start to make sense. It’s just that they tend to make sense after the bill shows up haha.
