Intermediate

Materialization 101

Master the merge logic that turns change events into durable, queryable tables across warehouses, lakes, and caches.

Materialization readiness tracker

Track how close each readiness checklist is to production-ready materialization in a single view.

0 of 0 readiness checks complete (0%)

    Choose the right pattern for the job

    Materialization strategies compared
    Pattern How it works Best for
    Mutable table (upsert/delete) Apply change events directly to a target table using merge logic. Serving layer caches, feature stores, operational analytics.
    Streaming merge Continuous ingestion job (dbt incremental, Snowpipe, Flink) performs row-level MERGE as events arrive. Low-latency marts where freshness is minutes, not hours.
    Append-only with views Store each event as a row, surface latest state via window functions. Auditable fact tables, debugging, ad-hoc comparisons.
    Incremental batch Land CDC events in stages, then run scheduled merge statements. Warehouses that favor batch execution or have strict cost controls.

    Build idempotent merge logic

    1. Stage events in a temporary table keyed by primary key and log position.
    2. Deduplicate to one row per key by ordering on the source log position (LSN/SCN/binlog position) — not ts_ms. ts_ms is a millisecond processing time (the commit time is source.ts_ms) and is not unique per key, so same-millisecond changes can tie and apply out of order; use the log position as the primary sort, with a within-transaction ordinal (Debezium source.sequence, or the row index) as the secondary key. If a position can repeat for a key (Oracle SCN, MySQL multi-row events), compare the (position, ordinal) pair. Keep ts_ms out of ordering entirely.
    3. Merge updates and inserts using the latest event per key (the MERGE cookbook has per-warehouse templates).
    4. Apply deletes as delete markers (a deleted flag plus the delete’s log position) so a late, older update cannot bring the row back. Physically removing the row is safe only when nothing can replay older events; see purging markers safely.
    5. Record the processed offset so restarts can resume safely.
    6. Publish metrics: rows inserted, updated, deleted, skipped duplicates.

    When duplicates land, the last change wins rule keeps results stable. Do not rely on arrival order or timestamps; rely on the source log position.

    Capture merge SQL in version control and tag it with the connector version it expects. This makes rollbacks trivial when envelope changes introduce new columns.

    SQL templates you can adapt

    Snowflake MERGE
    -- staging.orders_src must already be deduped to ONE row per order_id
    -- (latest by log position, e.g. LSN/SCN) before this MERGE runs.
    -- Deletes are kept as delete markers (deleted = TRUE plus the delete's
    -- position), so a replayed older update cannot resurrect the row. Readers
    -- filter deleted = FALSE; amount/status are NULL on a delete, so those
    -- columns must be nullable. Assumes src.lsn is unique per change for a key;
    -- if it can repeat, compare the (lsn, seq) pair as in /partitioning/#recon.
    -- If you add source_lsn to an existing table, backfill it first: a NULL
    -- source_lsn makes tgt.source_lsn < src.lsn NULL, so the row is silently
    -- never updated. Or compare COALESCE(tgt.source_lsn, -1) < src.lsn.
    MERGE INTO analytics.orders tgt
    USING staging.orders_src src
      ON tgt.order_id = src.order_id
    WHEN MATCHED AND tgt.source_lsn < src.lsn THEN UPDATE SET
      amount = src.amount,
      status = src.status,
      deleted = (src.op = 'd'),
      source_lsn = src.lsn,
      processed_ts_ms = src.ts_ms  -- metric only, never used for ordering
    WHEN NOT MATCHED THEN
      INSERT (order_id, amount, status, deleted, source_lsn, processed_ts_ms)
      VALUES (src.order_id, src.amount, src.status, (src.op = 'd'), src.lsn, src.ts_ms);
    

    Untested: not run in Snowflake (the guard logic was run as PostgreSQL MERGE).

    Why source_lsn and a delete marker, and what makes a position safe to compare: Making Sinks Bulletproof.

    BigQuery change-applier
    -- Full rebuild from the retained event history in staging. The delete is kept
    -- as a delete marker (deleted = TRUE plus its position), exactly as in the
    -- incremental targets above and below, so readers filter deleted = FALSE and
    -- nothing that later re-applies older events can resurrect a deleted key.
    -- amount/status are NULL on a delete, so those columns must be nullable.
    CREATE OR REPLACE TABLE analytics.orders AS
    SELECT
      order_id,
      amount,
      status,
      (op = 'd') AS deleted,
      lsn AS source_lsn
    FROM (
      SELECT *,
             -- order by log position (authoritative commit order); seq is the
             -- within-transaction ordinal for changes that share a position
             ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY lsn DESC, seq DESC) AS rnk
      FROM staging.orders_src
    )
    WHERE rnk = 1;
    

    Untested: not run against a live BigQuery project. Check it against your own schema before use.

    dbt incremental model
    -- models/orders.sql. Written for Snowflake, BigQuery and PostgreSQL 15+
    -- adapters that support incremental_strategy='merge'. The target needs
    -- order_id, amount, status (nullable), deleted and source_lsn (never NULL).
    {{
      config(
        materialized='incremental',
        incremental_strategy='merge',
        unique_key='order_id'
      )
    }}
    
    with source_events as (
      select order_id, amount, status, op, lsn, seq
      from {{ source('cdc', 'orders') }}
      {% if is_incremental() %}
      -- Bound the scan by the source log position already applied. It is >=, not >:
      -- re-reading the changes at the high-water position is harmless (the guard
      -- below drops them) and keeps a different key's change that shares that
      -- position. The same key at the same lsn is dropped by the strict guard, so
      -- if one key can have two changes at one position, store the ordinal and
      -- compare the pair. A strict
      -- bound is not safe if changes can land in this table out of order: the
      -- late row has a lower lsn than max(source_lsn) and is skipped for good.
      -- var('lsn_lookback') subtracts a margin (default 0) to re-read further back.
      where lsn >= (
        select coalesce(max(source_lsn), 0) - {{ var('lsn_lookback', 0) }}
        from {{ this }}
      )
      {% endif %}
    ),
    
    ranked as (
      select order_id, amount, status, op, lsn,
             -- order by log position (authoritative); seq is the within-transaction
             -- ordinal for changes that share a position
             row_number() over (
               partition by order_id
               order by lsn desc, seq desc
             ) as rnk
      from source_events
    ),
    
    latest as (
      select order_id, amount, status, op, lsn
      from ranked
      where rnk = 1
    )
    
    -- The delete is not filtered out here. It becomes a delete marker row:
    -- deleted = true plus the delete's position, so a replayed older update
    -- cannot bring the key back. Readers filter deleted = false.
    select
      l.order_id,
      l.amount,
      l.status,
      (l.op = 'd') as deleted,
      l.lsn as source_lsn
    from latest l
    {% if is_incremental() %}
    -- The version guard. Keep a change only if the key is new or the change is
    -- later in the log than the row already stored. A replay carries the same
    -- position it had the first time, so it is dropped here.
    left join {{ this }} t
      on t.order_id = l.order_id
    where t.order_id is null
       or t.source_lsn < l.lsn
    {% endif %}
    

    Untested: not run against a live warehouse. Two limits to know. The guard is evaluated before dbt issues the merge, so it assumes one run at a time per model (two concurrent runs can race). It also assumes lsn is a single number that is unique per change for a key; if it can repeat, or is a tuple (MySQL file and position, SQL Server LSNs), store the ordinal alongside it and compare the pair as in Making Sinks Bulletproof, and bound on a loader-assigned load id instead of lsn. Do not use incremental_predicates for the guard: it goes into the merge’s ON clause, so a row that fails it is treated as new and inserted again.

    Keep history when you need it

    • Add valid_from and valid_to columns around each change.
    • Close the previous version when a new update arrives.
    • Expose current rows via a view that filters on valid_to IS NULL.

    This pattern powers SCD Type 2 tables without losing the benefits of CDC freshness.

    Handle late-arriving and out-of-order events

    • Track a watermark timestamp in your staging table to bound your replay budget; which version of a row wins is decided by log position, never by that timestamp.
    • Store raw envelopes for N days so you can reprocess with updated merge logic.
    • Document how to reconcile when the source database is manually patched (backfills, deletes).

    Late arrivals are usually replayed by ops teams—make the procedure idempotent so you can run it twice without fear.

    Operational guardrails

    Validate inputs
    • Reject events that miss primary keys or required columns.
    • Track schema version and fail fast on incompatible changes.
    Observe merge latency
    • Alert when staging tables age beyond the expected SLA.
    • Keep a backlog gauge so you know when to scale compute.
    Disaster recovery
    • Retain staging data long enough to replay the last full window.
    • Store checkpoints (offset, batch id, timestamps) beside the target table.

    Combine these runbooks with automated smoke tests that upsert and delete a synthetic record daily. The job should fail if materialization drifts.

    Data quality checks before publishing

    1. Compare row counts between source and target using time-bounded windows.
    2. Verify key uniqueness and detect primary-key churn with a duplicate audit query.
    3. Validate soft deletes by ensuring delete markers propagate to downstream marts within SLA.

    Embed these checks in orchestration (Airflow, Dagster, dbt) so they run on every deploy and after infrastructure maintenance.

    Verification playbooks

    Pre-prod regression

    • Run fixtures that upsert, delete, and reinsert entities to validate merge branches.
    • Backfill a 1-hour slice from production CDC into staging and diff row-level hashes.
    • Exercise late-arrival and out-of-order scenarios before promoting SQL changes.

    Production spot checks

    • Schedule canary merges on synthetic ids with deterministic payloads.
    • Export change event samples weekly and replay them against a shadow environment.
    • Rotate on-call owners through a monthly verification drill to keep docs fresh.

    Treat verification as part of the deployment pipeline—pair SQL reviews with a matching verification checklist so no merge ships without evidence that the materialized view still behaves.

    Materialization readiness scorecard

    Align the data platform, analytics, and ops teams on what “ready for production” means before turning on the CDC materialization job.

    0 of 4 ready (0%)

    Checklist before promoting to production
    Workstream Ready when… If not, take this step
    Warehouse tables exist with primary keys, clustering, and partitioning that match the envelope design. Provision tables with the final schema and run dry-run merges against staging data.
    Incremental jobs have retries, alerting, and offset checkpointing wired up. Add idempotent retries, persist offsets with the job metadata, and document restart steps.
    Snapshot-to-stream cutover plan is rehearsed with clear checkpoints and rollback triggers. Run a timed rehearsal in staging, log each checkpoint, and confirm revert instructions are executable.
    Analytics owners sign off on data quality thresholds and downstream dashboards include freshness indicators. Review metrics with stakeholders, add freshness badges to dashboards, and capture acceptance criteria in a doc.

    Materialization Knowledge Check

    Test your understanding of upsert patterns and materialization strategies.

    Q1

    What is the purpose of a MERGE statement in CDC materialization?

    Q2

    What is the difference between a 'current state' table and a 'history' table in CDC materialization?

    Q3

    Why is idempotency important when materializing CDC events?

    Q4

    What is log compaction in Kafka, and how does it relate to CDC materialization?

    Q5

    What challenge does handling 'late-arriving' events present in CDC materialization?

    0/5 correct

    Further resources

    Progress 0% No progress yet
    Progress is stored locally in this browser.