Repairing metric rollups
This page applies to ClickHouse deployments only. SQLite and DuckDB were never affected.
Earlier releases wrote the tags of a metric in a different key order from one insert to the next. ClickHouse compares a Map in the order its entries were written, so {'a':'1','b':'2'} and {'b':'2','a':'1'} were two values, and the rollup tables stored one series as many rows that never merged (issue #448 (opens in a new tab)). On a small installation metric_points_1h held 58 times and metric_points_1d 470 times the rows it needed, and both grew by hundreds of megabytes a day.
The current release fixes this in three places, with no action on your side:
- the backend writes tags in key order,
- the five rollup views sort tags themselves (startup migrations
0123to0127), so an older backend still running during a rolling deploy cannot split a rollup, - the two reads that took the whole tag map as a series identity (the
rateaggregation past 6 hours, and the series budget of client metrics) now sort it, so rows that are already stored read correctly.
Growth stops with the upgrade. Rows that were already split stay until their TTL, and that is what the opt-in repair on this page is for.
| Table | Split rows expire after | Repaired |
|---|---|---|
metric_points | 7 days | no, expires on its own |
metric_points_1m | 30 days | no, expires on its own |
metric_points_1h | 1 year | yes |
metric_points_1d | never | yes, the last year |
metric_histograms | 7 days | no, expires on its own |
metric_histograms_1h | 90 days | yes |
metric_histograms_1d | 2 years | yes, the last year |
The steps
- Upgrade every backend instance to the current release and let it start once, so that the startup migrations make the rollup views sort their tags. The repair refuses to run before that.
- Check how many rows are split (below). With few of them, stop here.
- Set
METRIC_ROLLUP_REPAIR=trueand restart the backend, outside your peak hours. - Follow the log lines or the metrics (Follow the progress). The first lines are the scan; nothing is changed before
pass_started. - Wait for
metric rollup repair: complete, METRIC_ROLLUP_REPAIR can be unset. The worker has ended by then. - Check the result (below), then set
METRIC_ROLLUP_REPAIR=falseor remove it. It takes effect at the next restart, and no restart is needed for it.
Nothing else has to be stopped. Ingest, dashboards and alerts keep running during the repair.
Check whether you need it
Compare the rows a table holds with the rows it would hold with sorted tags:
SELECT
count() AS stored_rows,
uniqExact(project_id, name, recorded_at, mapSort(tags)) AS needed_rows,
countIf(tags != mapSort(tags)) AS unsorted_rows
FROM metric_points_1d;Run it for metric_points_1h too. On a table with hundreds of millions of rows the query takes minutes: run it from clickhouse-client, or a month at a time by adding WHERE toYYYYMM(recorded_at) = 202611. When unsorted_rows is 0, or the difference is not worth the disk it costs you, leave the repair off: charts and alerts are correct either way.
Run the repair
Set one variable on the backend and restart it:
METRIC_ROLLUP_REPAIR=trueThe variable is read once, at startup. true (or 1) turns the repair on; false, any other value, or no value leaves it off.
A pass starts at startup. It scans the last year of the four tables, today first and going back a day per query, then works through every partition that holds unsorted rows, the newest first. Rows older than a year are left as they are: they read correctly, and only keep the disk they use. When a pass leaves nothing behind, the worker logs metric rollup repair: complete, METRIC_ROLLUP_REPAIR can be unset and ends. When a pass fails or skips a partition, it runs again an hour later, and at every restart. Leaving the variable set costs one scan of the four tables per start.
With several backend instances you can set the variable on all of them. The instance that runs a pass holds a PostgreSQL advisory lock, and the others log another instance is running it and look again in an hour.
What a pass does to one partition
- It builds the merged rows of the partition's unsorted rows in a scratch table, one day of data per
INSERT. - It renames the scratch table to
<table>_tagrepair_<partition>_<first day>. That name is the record that the merged rows are complete, and of the first day they cover. ALTER TABLE ... MOVE PARTITIONputs the merged rows into the rollup table in one step.ALTER TABLE ... DELETE IN PARTITIONremoves the unsorted rows from that first day on, as a background mutation the worker polls.- It moves once more, checks that the staging table is empty, and drops it. A staging table that still holds rows is never dropped: the pass ends with
merged rows are still in <table>and the next one takes the partition up again.
Every query the worker sends to a rollup table reads one day of it, so none of them runs into the five minutes after which the ClickHouse connection ends a query.
Every step can be repeated, so a backend that is stopped or crashes at any point is picked up by the next pass without a row lost or counted twice. Do not drop a _tagrepair_ table by hand while unsorted rows remain in its partition: the next pass would merge them a second time.
The worker refuses to start while a rollup view does not sort its tags, because the procedure is only safe when no new unsorted row can appear.
What it costs
- Disk. The delete rewrites every part that holds unsorted rows, and ClickHouse reserves 1.1 times a part's size while it does. A partition is skipped, with a warning, unless its disk has twice the size of the partition's largest part free. Object storage (ClickHouse Cloud, an S3 disk) reports no limit, so nothing is skipped there. Free space, or add a volume, and the next pass takes it up. Space comes back a few minutes after a partition is done, when ClickHouse removes the old parts.
- I/O. Merging and rewriting compete with ingest and dashboard queries. There is no throttle; start it outside your peak hours.
- Double counting, briefly. Between steps 3 and 4 a partition holds both the merged rows and the originals. Averages, minima, maxima, percentiles and rates read the same during that time. The
sumandcountaggregations of ranges longer than 72 hours read up to twice their value for those series, until the delete of that partition finishes.
How long it takes
Time goes into three things: the scan at the start of a pass, merging a partition's days, and the delete that rewrites its parts. The move is instant.
On a small installation, 2.26 million split rows in six partitions were merged into 376,000 in 7.5 seconds on a 4 vCPU machine, and metric_points_1h went from 32.8 MB to 6.0 MB.
On a large one (ClickHouse Cloud, a 4 vCPU backend) 876 million split rows in 18 monthly partitions took about an hour of worker time:
| What | Rows | Time |
|---|---|---|
Scan of metric_points_1h | 557 million unsorted, 8 partitions | 7 min 56 s |
Scan of metric_points_1d | 310 million unsorted, 8 partitions | 5 min 12 s |
Scan of metric_points_1h after its repair | 4 million unsorted left | 13 s |
One month of metric_points_1h | 120 million merged into 1.8 million | 6 min 10 s: 2 min 42 s merging, 3 min 27 s delete |
One month of metric_points_1d | 105 million merged into 226,000 | 4 min 17 s: 1 min 28 s merging, 2 min 48 s delete |
One month of metric_histograms_1h | 4.35 million merged into 38,000 | 20 s |
A day of 4 to 8 million split rows merged in 3 to 9 seconds. No insert failed or was delayed while it ran.
Stopping and resuming
To stop the repair, set METRIC_ROLLUP_REPAIR=false and restart the backend. Set it to true again and restart to go on. Both are safe at any moment:
- A partition that was being merged starts over. Its scratch table is replaced.
- A partition whose merged rows were complete is taken up where it was, logged as
partition_resumed. Its staging table<table>_tagrepair_<partition>_<first day>stays in the database in the meantime; leave it alone. - A delete that was already running goes on in ClickHouse without the worker and finishes by itself.
- A pass that starts again scans again, which is the time in the table above.
One state is worth avoiding: a partition stopped after its move and before its delete was issued reads double (see What it costs) until the repair goes on. The delete is issued once the worker has counted the rows to remove, which follows the partition's last batch_merged line by up to a minute on a large partition, and delete_running shows it is under way. So stop while days are still being merged or after delete_running has appeared, and when you have stopped in between, resume soon.
ClickHouse Cloud and replicated tables
The repair runs on ClickHouse Cloud, where the rollups are SharedMergeTree tables, as it does on a single server. Two things differ there, and the worker allows for both:
- A read can miss a write of a moment ago, because another replica answered it. The counts that decide something (the merged rows written, the unsorted rows left after a delete, whether the staging table is empty) are read with
select_sequential_consistency = 1. The setting has no effect on a plainMergeTree. - The staging table is dropped only once it is empty. If the move ran on a replica that had not seen every merged row yet, the rows left behind are moved in the next attempt; after five attempts the pass ends and keeps the table.
On replicated tables (ReplicatedMergeTree, SharedMergeTree) MOVE PARTITION adds the rows to the destination and removes them from the source in two steps. A ClickHouse server that crashes exactly between the two can leave merged rows in both tables. Traceway's own migrations create plain AggregatingMergeTree tables, where the move is one transaction. Take a backup first if your tables are replicated. The repair is tested on a single server (ClickHouse 24.8 and 26.8) and has been run on ClickHouse Cloud; it is not tested on a self-managed ReplicatedMergeTree cluster.
Follow the progress
Every step is one log line that starts with metric rollup repair: followed by the event and key=value pairs:
metric rollup repair: scan_running table=metric_points_1h day=2026-07-14 position=135/367 rows=5100000
metric rollup repair: table_scanned table=metric_points_1h partitions=14 rows=8200000 took_ms=5210
metric rollup repair: pass_started partitions=31 rows=14300000
metric rollup repair: batch_merged table=metric_points_1h partition=202609 batch=2026-09-03 position=3/30 rows_in=288000 rows_out=4800 took_ms=358
metric rollup repair: delete_running table=metric_points_1h partition=202609 parts_to_do=4 elapsed_ms=30021
metric rollup repair: partition_done table=metric_points_1h partition=202609 position=1/31 rows_in=8640000 rows_out=144000 stage_ms=9320 move_ms=8 delete_ms=41765 took_ms=51097
metric rollup repair: pass_finished partitions_done=31 partitions_skipped=0 rows_in=14300000 rows_out=250000 took_ms=412504| Event | Written |
|---|---|
scan_running | Every 30 seconds while a table is scanned: the day it has reached, going back from today, and the unsorted rows found so far |
table_scanned | Once per table at the start of a pass: partitions and unsorted rows found |
pass_started | Once per pass: the total work |
batch_merged | After each day of a partition is merged into the scratch table |
partition_resumed | When a partition an earlier run left staged is taken up again, with the first staged day as since |
delete_running | Every 30 seconds while a partition's delete runs, with the parts still to rewrite |
partition_done | When a partition is finished, with the time each step took |
partition_skipped | Warning: a partition was left for a later pass, with the reason |
pass_finished / pass_failed | End of a pass, with totals; pass_failed is a warning and carries error |
With self-monitoring on, the same lines are log records of the monitoring project, and every pair is also an attribute named rollup_repair.<key>. In Logs, filter by rollup_repair.event = partition_done to see partitions finishing, or add rollup_repair.table = metric_points_1h to follow one table. The numbers are attributes too, so rollup_repair.took_ms can be charted from the same page. Each pass is also a task named retention.metric_rollup_repair under Tasks, and a failed pass is an issue.
The metrics are listed under Metric rollup repair in the metric reference. traceway.rollup_repair.rows_pending and partitions_pending fall to 0 as a pass advances.
Check the result
After complete, the last year holds no unsorted row and no staging table is left:
SELECT count() FROM metric_points_1h
WHERE tags != mapSort(tags) AND toDate(recorded_at) >= today() - INTERVAL 1 YEAR;
SELECT name FROM system.tables
WHERE database = currentDatabase() AND (name LIKE '%\_tagrepair\_%' OR name LIKE '%\_tagbuild');The first returns 0 for each of the four tables, the second no row. pass_finished carries the totals of the last pass (rows_in split rows merged into rows_out), and partitions_skipped=0.
Charts read the same as before. To see it, compare the count of a metric per day over more than 72 hours, before and after: the numbers are equal. A day at twice its neighbours means its partition is between the move and the delete, which ends when the repair goes on.
When a pass does not finish
A pass that fails writes pass_failed with the error, then stopped, retrying in 1h0m0s, and with self-monitoring on it is an issue in the monitoring project. Nothing has to be undone: the next pass, an hour later or at the next restart, takes it from there.
| Message | What it means |
|---|---|
<view> does not sort tags, so rows of <table> cannot be merged safely | The startup migrations 0123 to 0127 have not run on this database. Start the current release once, and check the view in system.tables. Nothing was changed |
i/o timeout on a query | One query ran past the five minutes the connection allows. Each query reads one day of one table, so that day is very large or ClickHouse is overloaded. The next pass goes on from the partitions that are left |
N partitions were skipped / partition_skipped | Not enough free disk to rewrite the partition's parts. Free space or add a volume; the next pass takes them up |
the mutation made no progress for 30m0s | A delete stalled, usually on a full disk. The worker has killed it. Check the free space and system.mutations |
the mutation keeps failing: <reason> | ClickHouse refuses the delete, with its own reason. The worker has killed it |
N unsorted rows are left after 3 deletes | Something still writes unsorted rows: an older backend, or a rollup view that was changed by hand |
N merged rows are still in <table> after 5 moves, the table is kept | The staging table could not be emptied into the rollup. Nothing is lost: the merged rows are in that table, and the next pass moves them |
staging table <name> is not named <partition>_<first day> | A table whose name starts with <table>_tagrepair_ was not made by this worker. Rename or drop it if it is yours |
another instance is running it | Not an error: this instance waits and looks again in an hour |
Do it by hand
The worker is the supported way. If you would rather run the statements yourself, these are the ones it runs, for one partition of metric_points_1h. The backend must already be on the current release, so that the views sort.
-- 1. the partitions with unsorted rows
SELECT _partition_id, count() FROM metric_points_1h
WHERE tags != mapSort(tags) GROUP BY _partition_id ORDER BY _partition_id;
-- 2. merged copies of one partition's unsorted rows
CREATE TABLE metric_points_1h_byhand_202609 AS metric_points_1h;
INSERT INTO metric_points_1h_byhand_202609
(project_id, name, recorded_at, tags, min_val, max_val, sum_val, count_val)
SELECT project_id, name, recorded_at, mapSort(tags) AS sorted_tags,
minMergeState(min_val), maxMergeState(max_val), sumMergeState(sum_val), countMergeState(count_val)
FROM metric_points_1h
WHERE _partition_id = '202609' AND tags != mapSort(tags)
GROUP BY project_id, name, recorded_at, sorted_tags;
-- 3. put them in, 4. remove the originals, 5. clean up
ALTER TABLE metric_points_1h_byhand_202609 MOVE PARTITION ID '202609' TO TABLE metric_points_1h;
ALTER TABLE metric_points_1h DELETE IN PARTITION ID '202609' WHERE tags != mapSort(tags) SETTINGS mutations_sync = 2;
DROP TABLE metric_points_1h_byhand_202609;Run the INSERT exactly once per partition. metric_points_1d takes the same statements. The histogram tables group by their dimension columns as well (release, env, os, os_major, client, client_major, form_factor, device_class, network, country, view) and merge with sum(cnt), sum(total), min(min_val), max(max_val), sum(zero_cnt), sumMap(buckets.1, buckets.2), sum(if(weight_squares > 0, weight_squares, cnt * 1000)).