Get icon
Query icon
Assert icon
Set icon
Queries icon
Sleep icon
Loop icon
If icon
Fail icon
Log icon
Webhook icon

Backfill a New ClickHouse Materialized View Month by Month

Add a ClickHouse materialized view to a live table and backfill its history month by month with no gaps or double counts, verified against the source.

Categories
Data

A new ClickHouse materialized view only sees rows inserted after it exists, and POPULATE can miss rows written while it runs. This flow follows the backfill method from the ClickHouse docs: the view starts at a cutoff a few minutes ahead, and the history before it is rebuilt one month at a time.

How it works

  1. The Webhook trigger starts a run, for example from the CI job that releases the view.
  2. plan picks the cutoff on the ClickHouse clock, or reuses the one saved in the KV store. no_rows_after_cutoff stops if source rows are already past it.
  3. create_view creates the target, an empty staging copy and the view, filtered to rows at or after the cutoff. Two checks confirm the view has this cutoff and the target is partitioned by month.
  4. wait_for_cutoff sleeps until live rows flow through the view.
  5. backfill loops over each earlier month. It builds the month in staging with the view's query, compares it to the source, then swaps it in with REPLACE PARTITION, safe to repeat, or ATTACH PARTITION for the cutoff month, which already holds live rows. The month is then checked and marked done.
  6. final_check compares source and target for every past month and the staging table is dropped.

What you get

  • History and live rows in one view, every source row counted once.
  • Re-runs skip finished months and keep the first cutoff.
  • A failed run with the numbers, instead of a silent mismatch.

Who it's for

  • Data engineers adding rollups to live ClickHouse tables.

Why orchestrate this with Kestra

The backfill is ordered DDL and checks that must survive a restart. Kestra keeps the cutoff and each month's progress in the KV store and stops on the first mismatch.

Prerequisites

  • A ClickHouse source table and a target partitioned by toYYYYMM.
  • A user allowed to create tables and views and to run ALTER TABLE ... PARTITION.

Secrets

  • CLICKHOUSE_USERNAME, CLICKHOUSE_PASSWORD: the ClickHouse login.
  • CLICKHOUSE_BACKFILL_WEBHOOK_KEY: the webhook key.

Quick start

  1. Add the secrets and set url and the table names in variables.
  2. Put your query in view_query, keeping __FILTER__ in its WHERE.
  3. Execute the flow and read the summary log.

How to extend

  • Add an errors task that alerts on a mismatch.
  • Turn variables into inputs to backfill several views.

Links

See How

New to Kestra?

Use blueprints to kickstart your first workflows.