
ClickHouse implements data-changing ALTER queries as mutations: asynchronous background processes that rewrite entire MergeTree data parts, and once submitted, a mutation cannot be rolled back. That irreversibility makes the naive approach—applying a breaking schema change and shipping matching code in the same release—unsafe for clusters that must stay online under continuous ingestion. The expand-and-contract pattern (also known as parallel change) splits a breaking change into reversible steps: add the new structure, keep both shapes synchronized, switch reads, and only then remove the old structure. This playbook maps each phase to concrete ClickHouse operations, from metadata-only column additions through partition-bounded backfill mutations to version-flagged read cutover and a final column drop. It is written for engineers operating MergeTree-family tables with rolling application deployments, and it treats the golden rule of backward compatibility as the organizing constraint throughout.

In ClickHouse an ALTER that changes table data (e.g., adding a column with a default, UPDATE or DELETE) is implemented as a mutation. A mutation is not executed inline; instead it is queued and run by the background merge process that powers all *MergeTree families. The key properties are:
SELECT therefore sees a mix of mutated and untouched parts, giving only partial visibility of the change 【1†clickhouse.com/docs/reference/statements/alter】.INSERTs: rows inserted before the mutation submission are subject to the mutation; rows inserted after are not. Inserts are never blocked 【1†clickhouse.com/docs/reference/statements/alter】.KILL MUTATION can stop further processing, but any parts already rewritten remain in their mutated state 【2†clickhouse.com/docs/reference/statements/alter】. The mutation continues even after server restarts, so the only way to “undo” it is to apply another mutation that compensates for the change.These characteristics create a fundamental constraint: a single, breaking schema change cannot be applied in one step without risking permanent data loss or inconsistent query results. Because the data‑rewriting DDL is one‑way, each phase of a migration must be non‑destructive—it must leave the existing table usable for both old and new application versions. The expand‑and‑contract (parallel change) pattern satisfies this requirement by decomposing a breaking change into reversible sub‑steps: add the new column, keep both shapes synchronized, switch reads, and finally drop the old column. This staged approach preserves availability and correctness while respecting ClickHouse’s mutation model.

A reliable expand‑and‑contract migration hinges on two non‑negotiable principles that order every step of the process.
1. Golden rule – backward‑compatible migration
A schema change must never break the version of the application that is still running. The migration is considered complete only after the old binary has been stopped and the new binary is deployed. In practice this means the DDL must succeed while the current service continues to read and write; the new code can be rolled out later, once the data layout is stable.
2. Compatibility‑first during rolling or blue‑green deployments
When a cluster is upgraded incrementally, both the old and the new service versions coexist. Every intermediate schema state therefore has to be safe for both versions simultaneously.
MergeTree parts and are irreversible【source2】【source3】.These constraints force a strict sequencing:
The pattern’s canonical five‑phase deployment structure reflects these principles:
By keeping every intermediate state compatible with both service versions, the expand‑and‑contract playbook guarantees that a cluster can stay online, ingest continuously, and recover from any step without relying on unavailable mutation rollbacks.

Operation – ALTER TABLE <tbl> ADD COLUMN <new> <type> DEFAULT <expr>
ClickHouse treats this as a metadata‑only ALTER: the statement finishes in microseconds, propagates instantly through Keeper on SharedMergeTree, and does not rewrite any existing data parts【source】. The default expression is stored in the table definition and is evaluated only when a part is read for the first time or when new rows are written, so current rows and running queries remain untouched【source】.
Choosing Nullable
Nullable<T> adds a companion UInt8 null‑map beside the actual column. This extra column consumes additional storage and must be scanned on every access, which typically degrades query performance. The official schema‑design guide therefore recommends avoiding Nullable unless the business logic truly distinguishes between “empty” and “NULL”. In most cases a sentinel default (e.g., an empty string, 0, or a known placeholder) provides the same semantics with lower overhead【source】.
Why not rename in this phase
A RENAME COLUMN changes the column name in metadata instantly, but any still‑running code that references the old name will fail immediately. Moreover, on heavily‑ingested tables the rename operation has been observed to hang indefinitely (e.g., ClickHouse v24.9.2.42), especially when inserts continue during the rename. In three of four attempts the rename succeeded; the fourth stalled and could not be killed without a server restart【source】. The safe practice is to avoid rename until the cut‑over phase, when all versions are ready to use the new name.
Deliverable of Phase 1
By confining the change to a metadata‑only ADD COLUMN with a prudent default (and, when possible, a non‑nullable type), the expand step establishes a stable foundation for the subsequent back‑fill and read‑cutover phases.

In the first deployment after the backfill mutation, the application must write every incoming row to both the legacy column set and the newly added column(s). Reads continue to target the old shape, so user‑facing queries remain unchanged while the new representation receives live traffic.
ClickHouse implements data‑changing ALTER operations as mutations that run asynchronously in the background. A mutation rewrites complete *MergeTree parts, but it does not block INSERT statements and is only partially ordered with them: rows present when the mutation is submitted are mutated, while rows inserted afterwards are never touched by that mutation 【source】(https://clickhouse.com/docs/reference/statements/alter)【source】. Consequently, the new column will be populated for historic rows by the backfill, but new rows will remain empty unless the application writes them explicitly. Skipping dual‑write would therefore produce a mixed schema where recent data lacks the new field, breaking downstream validation and any metric that depends on the new shape.
Write feature flag – introduce a configuration (e.g., a JSON list of target columns or a boolean per table) that tells the ingestion code whether to populate the legacy column, the new column, or both.
Dual‑write code path – when the flag is enabled, the INSERT statement includes both column sets, e.g.:
INSERT INTO events (id, ts, old_field, new_field) VALUES (...)
The same logic applies whether the write is executed directly or via an ingestion pipeline.
Flag transition – after the backfill mutation reports completion (via system.mutations) and verification steps pass, a subsequent deployment removes the legacy column from the flag, stopping the dual write.
If the pipeline uses an ingestion table together with materialized views that project data into analytical tables, the fan‑out to both shapes lives entirely in the ingestion layer. The ingestion table accepts raw payloads (often JSON) without requiring immediate schema changes; materialized views then write a transformed row to each target table, one with the old schema and one with the new schema 【source】(https://www.tinybird.co/blog/clickhouse-schema-migrations)【source】. This pattern lets upstream services emit new fields instantly while the ClickHouse schema evolves underneath.
NULL‑related exceptions.By honoring ClickHouse’s mutation semantics and using a controlled write flag, Phase 2 creates a safe, reversible bridge between the old and new schemas, paving the way for the read‑cut‑over that follows.

After the new column (or changed column) has been added to the table definition, the data itself must be populated. ClickHouse performs this step through mutations, which are asynchronous background jobs that rewrite whole MergeTree parts. The two primary mutation forms are:
| Command | Purpose |
|---|---|
ALTER TABLE tbl MATERIALIZE COLUMN new_col | Writes the column’s default expression into every part where the column is missing. |
ALTER TABLE tbl UPDATE new_col = expr WHERE … | Executes an arbitrary expression on selected rows; the result is stored in the new column. |
Both commands create entries in system.mutations. The table provides is_done, parts_to_do, and parts_to_do_names to monitor progress. Important caveat: even when parts_to_do = 0, a replicated mutation may still report is_done = 0 if a concurrent INSERT creates a new part that still needs mutation【{"cursor": 0, "id": 0}】. Setting mutations_sync = 1 forces the client to wait until the mutation is truly finished.
On the ReplicatedMergeTree family, ClickHouse automatically enables partition pruning for mutations when the filter references the partition key and the setting optimize_mutations_with_partition_pruning is on (default). This limits the rewrite to the affected partitions only【{"cursor": 1, "id": 2}】. For plain MergeTree tables, an explicit IN PARTITION clause must be added:
ALTER TABLE events UPDATE
processed = 1
WHERE event_date = '2024-09-01'
IN PARTITION '202409';
A typical monitoring loop looks like:
SELECT mutation_id, is_done, parts_to_do
FROM system.mutations
WHERE table = 'events' AND command = 'UPDATE';
Proceed to the next migration phase only when is_done = 1. If parts_to_do = 0 but is_done = 0, pause the rollout and wait for the ongoing INSERT to finish or run the mutation synchronously.
During a mutation, SELECT sees a mixture of mutated and unmutated parts. Consequently, applications must continue reading the old shape (or use a COALESCE(old_col, new_col)) until the mutation is confirmed complete. This “partial visibility” rule prevents transient mismatches between the two column versions【{"cursor": 0, "id": 3}】.
For multi‑terabyte tables, running a single mutation may be impractical. A safer pattern is to process one partition at a time:
DETACH PARTITION p FROM events;INSERT INTO events SELECT * FROM ingestion_table WHERE partition = p;new_col) during the insert.ATTACH PARTITION p TO events;Repeated for each monthly (or other) partition, this approach limits the “blast radius” of each backfill step and aligns with ClickHouse’s merge algorithm【{"cursor": 2, "id": 0}】.
Mutation statements should be idempotent: the expression must produce the same result when re‑run on already‑mutated rows. If a problem is detected, KILL MUTATION can stop the remaining work, but it does not restore parts that have already been rewritten. Therefore, design the backfill so that partially completed work does not corrupt downstream logic.
By bounding each mutation to a partition, actively monitoring system.mutations, and preserving read compatibility until completion, the backfill phase remains safe, observable, and rollback‑free—fulfilling the core invariant of the expand‑and‑contract migration pattern.

The second deployment introduces a read‑version flag that the application checks on every request. The flag can be scoped per‑tenant, per‑cohort, or even by a random percentage, so a single faulty cutover only affects a tiny slice of traffic. Flipping the flag is therefore a fast, reversible operation measured in seconds, providing an emergency rollback path without touching the underlying schema.
Shadow‑read workflow
“Shadow reads go a step further… you do not return the new result to the user. Instead, you compare the two results asynchronously and log any differences.” – Zero‑downtime database migrations1
Rolling the cutover
During the entire rollout dual writes remain active so that reverting the read flag instantly restores a fully consistent old view. The migration’s DDL steps are therefore a minor portion of the effort; the bulk of work lies in the observation, comparison, and coordination described here.
Only after the new read path has proven stable should the final phase be triggered to drop the old write path and eventually remove the obsolete column.
Feature‑flag orchestration (e.g., Redis‑backed lists) is a common mechanism to drive the read‑version flag and to coordinate the gradual ramp‑up across tenants or cohorts.2

The contract phase is the only truly destructive step in the expand‑and‑contract workflow. ALTER TABLE … DROP COLUMN removes the column from the table schema and deletes its physical files from every MergeTree data part. Because ClickHouse stores each column in its own set of files, the operation is essentially a fast file‑system delete plus a metadata update, completing almost instantly 【https://oneuptime.com/blog/post/2026-03-31-clickhouse-drop-columns/view】. After the statement succeeds, any query that still refers to the dropped column fails immediately, and the data is unrecoverable.
Soak period – Before issuing the drop, ensure that all rolling deployments have upgraded to a version that no longer reads or writes the old shape. The soak period gives the cluster time to confirm that no in‑flight queries or background mutations reference the column.
Dependency guards – ClickHouse enforces several safety checks:
DEFAULT or MATERIALIZED expression. Those objects must be dropped or altered first 【https://saturnsql.com/learn/clickhouse/how-to-drop-a-column-in-clickhouse】.ORDER BY (sort key) cannot be dropped at all; attempts will be rejected 【https://saturnsql.com/learn/clickhouse/how-to-drop-a-column-in-clickhouse】.Using DROP COLUMN IF EXISTS makes migration scripts idempotent and safe to re‑run, avoiding errors when the column has already been removed 【https://saturnsql.com/learn/clickhouse/how-to-drop-a-column-in-clickhouse】.
Version‑sensitive caveat – In ClickHouse versions where shared nested offsets are enabled, a DROP COLUMN <group> that targets a nested column group (e.g., address) is interpreted as a drop of the whole <group>.* set. The validation stage does not detect dependencies on the individual nested columns, so the drop silently destroys the group's data while leaving the table definition unchanged 【https://github.com/ClickHouse/ClickHouse/issues/114481】. Verify the behaviour on a non‑production replica before contracting any nested structures.
Deployment discipline – The contract phase must be performed in a dedicated deployment that contains only the DROP COLUMN statement (or a small set of unrelated, non‑breaking changes). Never bundle the drop with a new feature release; the production rollout should only proceed after the soak period confirms that all services operate with the new schema.
By treating the column drop as a deliberate, isolated step, you preserve the core principle of backward compatibility throughout the migration, while safely reclaiming storage once the old shape is fully retired.

account_id (metadata‑only)ALTER TABLE events
ADD COLUMN account_id UInt64 DEFAULT 0;
user_id values; reads of account_id on those parts return the column’s default (0) until backfilled.WRITE_ACCOUNT_ID). When the flag is on, every ingest pipeline writes both columns:INSERT INTO events (…, user_id, account_id)
VALUES (…, $user_id, $account_id) -- $account_id = map_user_to_account($user_id)
user_id is written, preserving the original behaviour.ALTER TABLE events
UPDATE account_id = map_user_to_account(user_id)
WHERE 1=1
IN PARTITION '2024-09';
IN PARTITION clause limits the rewrite to a single partition, allowing you to re‑run the mutation safely if a failure occurs【source 2】.system.mutations until is_done = 1 and verify that parts_to_do = 0【source 3】.SELECT count() FROM events WHERE partition = '2024-09') before and after to guarantee completeness.user_id.READ_ACCOUNT_ID). When enabled, query layers select account_id and ignore user_id.SELECT countIf(account_id != map_user_to_account(user_id)) AS mismatches
FROM events
WHERE event_date >= '2024-01-01';
ALTER TABLE events
DROP COLUMN IF EXISTS user_id;
account_id) and after confirming that no downstream service still depends on user_id.| Phase | Can be undone | How |
|---|---|---|
| 1 Metadata‑only add | ✅ | ALTER TABLE … DROP COLUMN account_id – no data loss |
| 2 Dual‑write flag | ✅ | Toggle flag off, redeploy old writer |
| 3 Backfill mutation | ✅ | Cancel or re‑run mutation; old user_id is still present |
| 4 Read flag | ✅ | Switch flag back; queries again use user_id |
| 5 Drop column | ❌ | Data removed permanently; only a fresh ADD COLUMN can recreate an empty column |
Bottom line: keep every breaking step compatible (phases 1‑4) and postpone the only irreversible operation (phase 5) to the very end. Each phase is independently deployable, letting you verify correctness before moving on to the next.
“Dual writes… Shadow reads … compare the two results asynchronously and log any differences.” – Zero‑downtime database migrations, thebackenddevelopers.substack.com/p/zero-downtime-database-migrations. ↩
“Feature flags are a common mechanism for controlling which database structures clients read from and write to during the expand and contract pattern.” – Expand and Contract Pattern for Database Schema Migrations, prisma.io/dataguide/types/relational/expand-and-contract-pattern. ↩