Materializing Projections on Existing Billion-Row Tables

Backfill projections one partition at a time, with a kill switch ready.

· 7 min read
Cover illustration for “Materializing Projections on Existing Billion-Row Tables”
ClickHouse Projections · December 2, 2026 · 7 min read · 1,644 words

Materializing projections on existing billion-row tables is a data-rebuilding operation. Old data must receive the new layout without overwhelming the resources serving live traffic. A smooth rollout depends on understanding the backfill, budgeting its cost, and controlling its progress with the care of a live migration.

Why adding a projection to a live MergeTree table is not a simple ALTER

A successful ADD PROJECTION statement can give false comfort. It defines the projection for parts written afterward, but old parts stay uncovered until an explicit materialization step runs. Adding a row-store index may suggest otherwise, but this change needs a physically separate, re-sorted or pre-aggregated layout stored in each data part. Until old data has that layout, the optimizer may fall back to a full primary-key scan on those parts without reporting an error. The query still returns correct results at pre-projection speed, so a successful schema change is not evidence of a completed rollout.

What the materialization pass actually does to a billion-row table

MATERIALIZE PROJECTION registers a mutation for the background merge machinery to process. The work happens part by part. For each existing data part, the engine reads the source data, builds the projection’s other layout, and writes it beside the original data. Across a billion-row table, this is a full pass over the data needed by the projection. The amount of work depends on what the projection includes and what it must produce.

A normal, or re-sort, projection reads all the columns it covers and writes a full copy in a different order. Its purpose is a different read path. If the projection covers all columns, the resulting copy roughly doubles storage for the covered dataset. Covering fewer columns narrows the data that must be read and written, but the operation still builds a re-sorted copy of those columns.

An aggregate projection does different work after reading its source columns. It applies the GROUP BY and writes the reduced result. That distinction changes the storage estimate substantially. Its output is typically a small fraction of the source size, depending on how much the grouping reduces the row count. A compact result does not mean the source can go unread, however, because the engine still has to build those aggregates from the existing data.

Partitioning provides a way to divide this work. Consider an events table with one partition for each month. The IN PARTITION clause lets materialization work on just one month out of the full history, though it still works through that partition’s parts. Progress is visible through system.mutations, including the remaining parts and whether the mutation has completed or stalled. This gives an operator both a bounded unit of work and a way to follow it.

By default, materialization runs asynchronously, so the command returns while the background work is still running. The mutations_sync setting changes that behavior, with mutations_sync = 2 blocking until materialization is fully complete across all parts. On a billion-row table, that can keep a connection open for a long time and is rarely appropriate in production.

What the backfill costs in I/O, storage, and write amplification

Materialization reads every byte of every column it covers in existing parts and writes the projection data back. Those reads and writes compete with live queries and ongoing ingestion on the same disks or object-storage throughput budget. Capacity that looks spare when traffic is low may be needed by queries when traffic rises.

A re-sort projection covering all columns approximately doubles storage for the covered dataset, so that headroom needs to exist before materialization begins. A table that already uses most of the disk leaves little room for that copy. An aggregate projection is usually far smaller because its footprint follows the reduced result. The relevant estimate is therefore how much the aggregation compresses the logical result.

LZ4 favors fast decompression on hot query paths, while ZSTD offers higher compression ratios at greater CPU cost. The latter is more appropriate for cold or archive-tier projection data, where storage savings may outweigh the extra processing cost. Codec choice thus affects both the materialization work and the queries that follow it. Choosing the smaller stored representation is not automatically the same as choosing the better layout for frequent reads.

New inserts must maintain the projection as well as the main table’s data, which adds ongoing write work. Automatic maintenance removes the need for a separate application pipeline, but it does not make that maintenance free. A projection’s cost-benefit case must therefore include the workload after the mutation finishes. The backfill is temporary, while the write amplification persists.

Operational controls for running the backfill without disrupting production

Diagram: Partition-by-Partition Backfill Sequence. Visualizes: Show the recommended step-by-step operational sequence for safely materializing a projection on a live billion-row table.

Run ADD PROJECTION first so that new parts get the projection as they are written. Then verify the definition on a small or oldest partition before extending the operation across the table. This creates a limited first test of both the intended layout and the backfill’s effect on production. There is no need to commit the entire history at once.

For the monthly events table, materialize one partition using the partition-scoped form of MATERIALIZE PROJECTION. Follow that mutation in system.mutations until it completes, watching the remaining parts and any sign that progress has stopped. At the same time, observe I/O use and query latency so that completion is not the only success criterion. Once work on the partition is done, spot-check query plans against it. A finished mutation establishes that the work ended, while the plan check establishes whether the intended queries can benefit.

Prepare the stop procedure before starting the backfill. Keep a KILL MUTATION query ready, and use mutation monitoring throughout. A part that never advances can signal a corrupt or oversized part, so stalled progress needs investigation rather than an assumption that the table is simply large. Partition-scoped work makes that response more manageable. Pausing or killing the current mutation does not discard progress on partitions already completed.

If the first partition puts too much pressure on live traffic, reduce the competition before proceeding. The number of background merge threads and the merge speed limits can be lowered while materialization runs. The trade-off is a longer maintenance window. That is often the right exchange for a live table. The goal is to complete the backfill while preserving service, rather than to make the mutation consume every available unit of I/O.

Continue one partition at a time when traffic is low, staying clear of peak ingestion and scheduled merges. Before moving on, use the previous partition’s completion, resource impact, and query-plan checks to judge whether the next step is appropriate. After all partitions finish, use EXPLAIN on representative queries to verify that the optimizer selects the projection. That final check closes the gap between having the layout on disk and having the intended read path in use.

What a successful projection delivers once the backfill is complete

The payoff should connect to the original query problem. If the projection was added because an important class of queries needed a different sort order, success means those queries can move from the primary-key scan to that order. Once all parts contain the projection, the optimizer selects it automatically when its layout would produce a faster result. No application-level rewrite is required to request it. Selection remains a cost-based choice, however, rather than a promise that every query will use the projection.

Aggregate projections offer a distinct route to faster queries. A dashboard that would otherwise process billions of source rows can read pre-aggregated results instead. The reduction in rows processed can be orders of magnitude, depending on the grouping and the query. Conceptually, this resembles a star-tree or pre-aggregation index, with work performed before the dashboard request arrives. The latency benefit of this reduction in query work varies by workload.

There is also a maintenance benefit after rollout. Unlike a separately maintained serving table, a projection stays consistent with new inserts through the main table’s write path. The application does not need extra logic, a separate pipeline, or reconciliation to propagate those inserts. The distinction is important when comparing approaches, because automatic consistency and free maintenance are not the same claim.

Where projections fit in a broader schema-evolution and cost-optimization strategy

A projection fits a specific kind of requirement. It is appropriate when the same table needs a different sort order or a simple pre-aggregation, but not when the job requires transformations, joins across tables, or a physically separate destination. Those needs belong with materialized views or separate serving tables.

A data-skipping index should be compared with a re-sort projection before the projection is chosen. Indexes such as minmax, bloom filter, and token bloom skip granules on secondary predicates without duplicating the underlying data. Projections instead re-sort or pre-aggregate data to provide an alternative read path. The two approaches are complementary. Their resource costs follow from that difference, so the choice starts with how the query needs to find its rows.

The infrastructure decision follows from the same reasoning. Monitoring mutations, throttling merges, sequencing partitions, and handling stalled parts are operational work rather than query-design work, and a managed layer can take on that burden. With compute and storage separated, temporary compute can support the rebuild without making a larger compute allocation permanent. The projection still needs storage for its output.

For teams that would rather not run heavy rebuilds on the hardware serving live traffic, ObsessionDB is one managed option with compute and storage separated. It lets that work run without the replica-duplication step that usually makes this kind of change slow to provision.

The engineer’s responsibility is still to connect the query benefit to the operational cost. A new sort order or pre-aggregated result has value only if the existing data receives it and production can absorb the work required. Partition-scoped execution, mutation monitoring, and query-plan checks make that transition tractable. Billion-row projection backfills belong in the category of live migrations.

More in ClickHouse Projections