Published Nov 22, 2026 · 19 min read
What Part Merging Taught Us About ClickHouse
Heavier spans, not more of them, pushed ClickHouse merges past replica memory. Failed merges were retried forever, and more memory only made the merges bigger. A walk through parts, merges and the 6 GiB merge cap that fixed it.
Our ClickHouse cluster once spent up to half of its CPU on work that never finished, but nothing crashed. Inserts still landed and dashboards still loaded, only slower. Underneath, ClickHouse was trying to merge the same pieces of one table again and again. Each attempt ran out of memory, was killed, and went back into the queue a minute later.

The red bars are CPU spent on merges that failed. For two weeks they were the largest share of the cluster. They drop to almost nothing on the day we changed one table setting.
The cause was not in ClickHouse. It was a default in our internal Go framework that copied every HTTP response body into a trace span.
ClickHouse At FeedMe
ClickHouse is our shared warehouse for data that arrives fast and is read in aggregate. Two groups write to it: the platform team, with logs and traces from every service, and product teams, with their own event and audit data.
Observability
Logs and traces from every service, and from point-of-sale devices, kiosks and kitchen display screens, land in ClickHouse. Grafana and HyperDX read them from there. The path from a service to a table is short:
service (OpenTelemetry SDK)
| spans and logs over OTLP
v
collector layer
| batched inserts
v
ClickHouse: otel_traces, ... (kept 180 days)
The otel_traces table comes from ClickStack’s default schema. Every span becomes one row. We set its TTL to 180 days, because compliance needs that much history, so every day of data stays on disk for half a year before ClickHouse drops it.
The ClickStack schema docs list every column and index, and the ClickHouse exporter README covers how the exporter creates and fills the tables.

The trace table is the largest thing we store. For weeks, otel_traces took 75 to 91 GiB of disk per day, for about 1.4 to 1.5 billion spans. Then, within a few days, it nearly doubles, to 176 GiB on its worst day.
The blue line is the span count. In the same days it rises only about 15%, and it stays up after the bytes come back down. So the trace table did not get many more spans, but it got heavier ones.
Self-Service
Product teams own tables in the same warehouse, through a schema repository. A team writes the table definition as a .sql file and opens a pull request. CI lints it, a reviewer approves it, and a pipeline applies it to development and then production. Nobody files a ticket with the platform team, and every table change has a history in git. Our business data is the thing competitors cannot copy, so we want it where teams can query it.
frame, Our Go Framework
Most of our Go services are built on frame, an internal framework. It bundles the things every service needs: a Gin web server, MongoDB and Redis clients, a message queue, cron jobs, structured logging, and OpenTelemetry. A service built on frame gets a span for every HTTP request without writing any tracing code.
Two pieces of frame touched every HTTP request. The controller wrapper copied the incoming body, and the response middleware copied the outgoing one. Each copy went onto the request’s span as an event, so one HTTP call produced one span carrying up to two copies of its payload:
client request
|
v
controller wrapper -- body under 1 MiB? --> copy to span event "request"
|
v
handler builds the response
|
v
response middleware -- body under 1 MiB? --> copy to span event "response"
|
v
client response
span: GET a restaurant's full menu
event "request" body = what the client sent (empty for a GET)
event "response" body = what we sent back (the whole menu as JSON)
The Menu Service
Menu service stores and serves the menu of every restaurant on FeedMe. It serves three kinds of callers:
+--> back office: restaurants create and edit menus
menu service ----+--> customers: ordering pages load a restaurant's menu
+--> internal: other services read menus, for example
to push them to delivery platforms
Most of the traffic comes from customers. When someone opens a restaurant’s ordering page, the page asks menu service for the restaurant’s full menu. The menu comes back as one JSON document, which can be as small as 57 bytes or as big as 5.6 MB, depending on the restaurant. The menus stored in spans, those under 1 MiB, averaged about 324 KB.
Menu service is part of an ongoing effort to rewrite our NestJS services in Go, on frame. The Go version first ran as a canary: a second deployment that serves a share of live requests next to the old one. Then, over two days, the Go deployment took over the full-menu requests. It brought frame’s tracing with it, so every full menu it served now went into a span.

The menu service’s daily spans dropped from 33 to 46 million to 15 to 22 million, because the traffic moved and some of it went quiet. But each full-menu span now carried the whole menu. The menu service sent half as many spans, and the trace table doubled in bytes.
This is the jump in the trace table chart earlier. The days the Go deployment took over the full-menu requests are the days otel_traces went from about 90 GiB a day to as much as 176 GiB. The menu service’s own spans fell by half, and the table’s total span count, across all services, rose only about 15%. The menu bodies were the largest share of the new bytes, about 60%. Most of the rest was real traffic growth in other services. Every full-menu span was stored as a row hundreds of times wider than a normal span, and those wide rows are what ClickHouse then had to merge.
How ClickHouse Stores A Table
Heavier spans would only cost disk if ClickHouse wrote each row once and left it alone, but it does not.
Parts
Every INSERT into otel_traces writes a new part. A part is a directory on disk with one file per column, and the rows inside it are sorted by the table’s sort key: service name, then span name, then time. Once a part is written, ClickHouse never changes it.
The collector layer sends spans in batches, so each insert carries thousands of spans and makes one part. Our trace table created about 9,000 new parts every hour.
On disk, the table is a directory of parts, and each part is a directory of column files (simplified):
otel_traces/
part_1/ one part, written by one INSERT
columns.txt column names and types
count.txt number of rows
primary.idx sparse index on the sort key
Timestamp.bin one data file per column,
ServiceName.bin compressed, rows in sort-key order
SpanName.bin
SpanAttributes.bin
Events.Attributes.bin span event attributes (the bodies)
...
part_2/
part_3/
... about 9,000 new parts every hour
The ClickHouse docs on table parts cover the on-disk layout in more detail.
Merges
Thousands of small parts are slow to read. A query has to open every part that might hold matching rows, and ClickHouse also limits how many parts a table may hold. So ClickHouse runs merges in the background. A merge reads several parts, merge-sorts their rows by the sort key, writes one bigger part, and deletes the inputs once the new part is safe on disk.
inserts --> [p1] [p2] [p3] [p4] [p5] [p6] [p7] [p8] ...
\ | | / \ | | /
merge merge
| |
[ p1-4 ] [ p5-8 ]
\ /
merge again ...
|
[ p1-8 ] ... up to ~150 GiB per part
Each row is rewritten several times as its part climbs from small to large. For our trace table, every byte inserted was written about seven times in total. That made merging the largest steady cost of the table, larger than inserts or queries. When we measured it, the trace table alone used about 70% of all merge time on the cluster.
A component called the merge selector decides which parts to merge and how big a merge may be. When the server has free merge threads and disk space, it allows merges up to about 150 GiB of input, the default for max_bytes_to_merge_at_max_space_in_pool. That check looks at threads and disk, not memory. The ClickHouse docs on merges describe the process step by step.
What A Merge Holds In Memory
A merge streams its input parts instead of loading them whole. It reads a block of rows from each input part, merges those blocks, writes the result, and moves on to the next blocks. The block size is set by merge_max_block_size, which defaults to 8,192 rows. So the memory a merge needs grows with three numbers:
memory ~ row width x parts merged at once x 8,192 rows per block
The ClickHouse docs give their own example: rows of 100 KB, merging 10 parts, need about 8 GB of RAM. For a normal span this is small. Our spans averaged about 1 KB before the bloat. Ten parts of 1 KB rows need about 80 MB. Nobody thinks about merge memory at that size.
The menu service’s full-menu spans change the numbers. The table is sorted by service name first, so in every part, the menu service’s spans sit next to each other. When a merge reaches that stretch of the sort key, every block it reads from every part is full of menu bodies:
324 KB x 8 to 14 parts x 8,192 rows = 21 to 37 GB
For large merges, ClickHouse uses a vertical merge. It merges the sort key columns first, then each remaining column one at a time, which should keep only one column in memory. That did not save us, because the heavy data was all in one column. Span event attributes, where the bodies sat, are stored in a column called Events.Attributes. Almost every merge that failed was a vertical merge, and almost every one died while reading that column.
The Limit
A ClickHouse replica stops any work that would push its memory past 90% of its RAM. Our replicas had 32 GB, so the limit was 28.8 GiB. That limit is for the whole replica. Merges, inserts, queries and caches all share it.

The blue line is the largest merge that finished in each 3-hour window. Within two days it doubled, from about 11 GiB to 22 GiB. That is close to the ceiling once everything else on the replica takes its share. Merges that needed more never finished, so they never appear on the blue line, but they appear as the orange bars. Failed merges went from almost none to about 650 every 3 hours in less than a week. A failed merge is killed, and the memory it used is released.
Retries Assume Bad Luck
Merges fail for ordinary reasons. A replica restarts in the middle of one. A large query takes memory at the same moment. A retry is the right answer to failures like these, because the next attempt runs under different conditions.
Our tables run on SharedMergeTree, the engine ClickHouse Cloud uses in place of MergeTree. When a merge fails, SharedMergeTree puts it back in the queue. The next attempt starts within about a minute, often on another replica. The wait between attempts is capped by max_postpone_time_for_failed_replicated_merges_ms, 60 seconds, and no counter ever gives up. This behavior has been reported since 2020 in ClickHouse issue #16838.
A retry only helps when the failure was bad luck, but ours was not. The retried merge had the same input parts, the same rows and the same memory need. It failed the same way, every time:
selector picks parts --> merge runs ~36 min --> hits the memory limit
^ |
| killed, work lost
| |
+------------- back in the queue, <= 60 s <----+
The median failed attempt ran for 36 minutes and reached 24 GiB before it was killed. At the worst point, 116 different merges were failing and being retried. On average each was retried 18 times, and the worst one 218 times. In under four days, failed merges used 1,358 CPU-hours. All 169,549 merges that worked in the same period used 57.
That is the red area in the chart at the top of this post. At its peak, failed merges used 47% of the cluster’s CPU.
The failed retries also hurt everything around them. Days that should have been merged down to 5 to 17 parts sat at 47 to 85. More parts meant slower reads, and the CPU left for queries and inserts shrank.
We found the repeated failures in system.part_log, which records every merge attempt with its input parts. Hashing the sorted list of input parts gives each merge an identity, and a merge that appears many times is a merge that keeps failing:
SELECT cityHash64(arraySort(merged_from)) AS merge_id,
count() AS attempts,
round(sum(duration_ms) / 3600000, 1) AS hours
FROM clusterAllReplicas(default, system.part_log)
WHERE table = 'otel_traces' AND event_type = 'MergeParts' AND error != 0
GROUP BY merge_id
ORDER BY attempts DESC
LIMIT 10
Why More Memory Did Not Help
Before we understood any of this, we gave the cluster more memory. It was a move to stop the bleeding. Queries and inserts were slowing down for every team on the warehouse, and more memory was the fastest lever we had, and it seemed to work.

The red line is the replica memory limit, the blue line is the largest merge that finished each hour, and the orange bars are failed merges.
With 56 GB replicas, failures fell from about 650 every 3 hours to about 5, and latency recovered. But the upscale never sat right with us. It added about $2,500 a month, it did not explain why a table with barely more spans needed so much more memory, and the biggest merges simply grew to 36 to 42 GiB, right up under the new limit.
We then cut the memory back to 32 GB to save cost, hours before the first payload fix landed. The heavy days still had to merge, and their large merges needed more than the new 28.8 GiB limit. Failures climbed to 60 to 70 an hour, and CPU sat at 100%. The ClickHouse Cloud autoscaler read that load as demand and scaled up to 48 GB. The blue line rose with the limit, and merges kept failing for two more weeks.
More memory moves the limit, and the merges follow it. Shrinking a cluster while the bad data is still on disk leaves that data failing to merge, retry after retry.
Fix One: Stop Writing Heavy Spans
The first problem was new data. Every hour, the Go menu service wrote more menu bodies into the trace table.
We stopped the bleeding in the collector layer first, because it sits in front of ClickHouse and we could change it within minutes. A transform rule cut every span event attribute from the Go menu service to 1 KiB before it reached the table. It took effect within the hour:

Its spans went from 35 to 44 KB each to about 1.4 KB, and that day’s data shrank from 149 GiB to 105 GiB. The collector rule only covered one service, though, and it did not explain where the weight came from.
To find the source, we looked at where a span row keeps its data. One row in otel_traces has three places that can hold bytes:
one span row in otel_traces
ServiceName, SpanName, Timestamp, ... fixed columns, small
SpanAttributes key-value pairs on the span itself
Events.Attributes key-value pairs on each span event
Our first query measured SpanAttributes, key by key. The largest key was db.statement. The Redis instrumentation records each full Redis command there, values included, and the menu service wrote large values to Redis. That looked like the answer, but the query had never read Events.Attributes.
The backend team then read the frame code and found the response middleware, which wrote every response body into a response span event. When we measured both columns, Redis commands were about 5% of the menu service’s extra bytes, and the response bodies were about 95%. When you measure where the bytes are, measure every column, including the nested ones.
The fix shipped in frame. Response-body tracing became opt-in, and when a service turns it on, bodies are capped at 1 KiB. With it off, the middleware no longer buffers the response at all:
before: response middleware -- body under 1 MiB? --> span event "response"
after: response middleware -- tracing on? -- no --> nothing recorded
|
yes --> first 1 KiB --> span event
The menu service upgraded, and we removed the collector rule. Within days, the trace table’s bytes per row on disk fell from about 100 back to 62, its normal level.
The same release of frame added trace sampling, so a service can export only a share of its traces while still keeping the ones that fail. Sampling cuts how many spans we store but does not make a span lighter, so it works next to the body fix, not in place of it.
Shipping the fix did not end the incident:

Bytes per span (blue) were back to normal within a day. Failed merges (orange) kept coming for two more weeks, because the source fix only changed new rows. The heavy days were still on disk, and the selector kept building giant merges that no replica could hold. That needed a second fix, in the table.
Fix Two: Cap The Merge Size
The second problem was the data already on disk, and the fix was one table setting:
ALTER TABLE otel_traces
MODIFY SETTING max_bytes_to_merge_at_max_space_in_pool = 6442450944; -- 6 GiB
Why A Cap Ends The Endless Retries
The endless retries needed one thing to keep going: the merge selector had to keep picking the doomed merges. Every time it scheduled work, it looked at the parts in each day and chose merges up to the default bound of about 150 GiB of input. Every day, heavy or not, held parts that added up to 30 to 150 GiB. Those merges were inside the bound, so they were picked again and again.
The table setting replaces that bound for this one table. A merge whose input parts add up to more than 6 GiB is no longer a candidate at all:
merge input size
4 GiB 12 GiB 40 GiB 110 GiB
default bound picked picked picked picked (up to ~150 GiB)
6 GiB cap picked - - -
Capping the input size caps the memory, because on this table merge memory tracked merge size closely. In theory, a merge streams its rows, and its memory depends on the block size, not the total size. In practice, the merges that finished peaked at 2.1 to 2.9 times their output size. A 6 GiB merge needs at most about 17 to 22 GiB, which fits.
The setting applies at selection time. Merges that were already running kept going. The doomed ones among them failed one last time. When they came back to the queue, their inputs were over the cap, so the selector skipped them, and the retries stopped. No restart was needed, because the selector reads the table setting every time it schedules.
Choosing 6 GiB
We derived the cap from the merge log. First, how much memory a replica can give to merges:
replica memory limit 43.2 GiB
memory used by everything except merges - 21.8 GiB
----------
left for all running merges 21.4 GiB
Then we took every merge that had finished and asked how many would have gone over that 21.4 GiB budget, grouped by output size:
output size merges over the budget
<= 6 GiB 0 of 186
6 to 8 GiB 18%
8 to 10 GiB 50%
> 10 GiB 80%
We picked 6 GiB because it was the largest size where no merge went over the budget. We did not pick 8 GiB, because merges tend to grow right up to the cap, so the 18% that failed in that range would become the norm.
The Result

One hour after the change, cluster CPU went from 35.8 to 17.5 of 36 cores. No merge picked under the cap has failed since. In the first half day, the table ran 21,303 merges with zero failures. The worst merge peaked at 17.1 GiB, inside the budget.
A few hours later, the autoscaler shrank the replicas from 48 GB to 36 GB on its own. The merge budget held, because the memory used outside merges fell with the RAM.
What The Cap Costs

Before the cap, each day merged down to 4 to 9 parts, and the largest part in a day reached up to 149 GiB. After the cap, each day settles at 25 to 35 parts, and no part is bigger than 6 GiB. The days in the middle are the heavy days, stuck partway: more parts than before, with parts too big to merge under the cap.
More parts per day means more parts in the table:

ClickHouse Cloud allows 10,000 active parts per table, and past that every INSERT fails. The trace table holds about 2,700 parts today and should level off near 5,600, about 56% of the limit, once the days before the cap age out of the 180-day TTL. A 3 GiB cap would have doubled that, which is why we did not go lower. We alert at 70% of the limit, and we estimate the extra parts slow queries by under 10%. That is the trade: every merge now fits in memory, and the table keeps more, smaller parts.
Why The Defaults Did Not Protect Us
Each of these defaults assumes something our trace table broke:
- Merge size, up to ~150 GiB of input. The selector checks threads and disk, not memory, so 324 KB rows turned routine merges into ones no replica could hold.
- Merge block, 8,192 rows. Sized for rows of a few KB. One block of menu bodies from each part held gigabytes.
- Merge memory soft limit. It stops new merges when memory is tight, but never swaps a merge that is too big for a smaller one.
- Retry forever. Right for failures that pass. Ours repeated exactly, because the inputs never changed.
- Autoscale on CPU and memory. Failed merges look like demand, and each resize stopped the merges in flight.
- One column for event attributes. All the bodies landed in
Events.Attributes, which every merge of a heavy day had to read.
These defaults are built for rows of similar, modest width, and none of them look at row width. The docs also say that memory reservation scheduling “is not supported for merges” yet. The soft-limit and retry behavior come from the ClickHouse source code, not the docs.
A few pointers from the ClickHouse docs would have helped us earlier:
- Do not force merges.
OPTIMIZE TABLE ... FINALignores the 150 GiB guard. It would have hit the same memory limit. - For wide rows, use a smaller merge block. The docs say lowering
merge_max_block_size“can reduce the amount of RAM required for a merge but slow down a merge”. We never tried it, and it is the first thing we would test next. - Own the trace schema. The observability guide says a raw body column “should compress well”, but unique JSON bodies do not. Our compression ratio fell from 17.4x to 13.0x.
The Main Lesson
A chain of defaults caused this, each reasonable on its own:
framework default copy every HTTP body into the span
exporter default one row per span, event attributes in one column
merge defaults merges up to ~150 GiB, 8,192 rows per block
retry default retry a failed merge forever
autoscaler read wasted CPU as demand
------------------------------------------------
result half the cluster's CPU spent on merges that
could never finish
What we do differently now:
- Count bytes, not rows. When a telemetry table grows, find which column the bytes are in before you blame traffic.
- Fix at the source, guard at the store. The framework fix stops the bodies. The merge cap protects ClickHouse from the next team that ships the same default.
- Do not resize while bad data is on disk. More memory moves the limit, and merges follow it. Less memory traps the heavy days.
- Derive limits from measurements. The 6 GiB cap came from the merge log, not a guess, and it held.
- Sample, and keep the errors. Sampling cuts how many spans you store, and the body fix cuts how heavy each one is, and you need both.
Cover image: the part merges diagram from the ClickHouse documentation, licensed under CC BY-NC-SA 4.0.