# Materialization 101

> Translate CDC change events into reliable warehouse tables with upsert, delete, and history-friendly patterns.

Canonical page: <https://sandgraal.github.io/letstalkcdc/materialization/>

> **Known errata for this page (2)**
>
> - **Corrected: reconcile by log position, not a timestamp** (updated 2026-10-09)
>
>   Several examples ordered or reconciled changes by a timestamp or left them unguarded. The snapshotting page's warehouse MERGE had no version guard, so a replay or an overlapping snapshot chunk could overwrite a newer row, and its "no primary key" advice said to dedupe on a hash plus the latest timestamp. The errata page said to reconcile snapshots using version columns or `op_ts`, and its soft-delete note suggested physical deletes where a delete marker is the safe choice. The dbt incremental model on the materialization page filtered deletes out before the target, so the deleted key's old row stayed, and had no incremental bound or guard; its BigQuery rebuild also dropped deletes instead of marking them. All now key the sink on the primary key and apply a change only if its source log position is greater than the one stored, keeping deletes as delete markers. Delivery stays at-least-once; none of this is end-to-end exactly-once.
> - **Corrected: what ts_ms is** (updated 2026-10-12)
>
>   The dedupe step called the envelope `ts_ms` a millisecond commit time. In the event envelope, `ts_ms` is when the connector processed the event, and the source commit time is `source.ts_ms`. The sentence now says so; the advice to keep it out of ordering is unchanged. The Snowflake MERGE is labelled as not run in Snowflake (its guard logic was run as a PostgreSQL MERGE).
>
> [See all corrections and caveats](https://sandgraal.github.io/letstalkcdc/errata/)

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

Compare Patterns Ship Quality Gates

## 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

| 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](https://sandgraal.github.io/letstalkcdc/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](https://sandgraal.github.io/letstalkcdc/deletes-stay-deleted/#purge).
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**

```sql
-- 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](https://sandgraal.github.io/letstalkcdc/partitioning/#recon).

**BigQuery change-applier**

```sql
-- 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**

```sql
-- 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](https://sandgraal.github.io/letstalkcdc/partitioning/#recon), 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%)

| Workstream | Ready when… | If not, take this step |
| --- | --- | --- |
| Target schema | 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. |
| Merge orchestration | Incremental jobs have retries, alerting, and offset checkpointing wired up. | Add idempotent retries, persist offsets with the job metadata, and document restart steps. |
| Backfill strategy | 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. |
| Stakeholder buy-in | 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?

A To combine multiple tables into one

B To apply inserts, updates, and deletes in a single atomic operation

C To compress data for storage

D To validate event schemas

Q2

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

A Current state shows only the latest row version; history preserves all versions over time

B History tables are always slower to query

C Current state tables don't use primary keys

D There is no meaningful difference

Q3

#### Why is idempotency important when materializing CDC events?

A It makes queries faster

B It ensures replaying or reprocessing the same event produces the same result

C It reduces network bandwidth

D It's only needed for batch processing

Q4

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

A It removes all old events after a time threshold

B It retains only the latest value for each key, effectively creating a changelog table

C It compresses events to save storage

D It sorts events by timestamp

Q5

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

A Late events always arrive corrupted

B Events may arrive out of order, requiring logic to reconcile older changes against newer state

C Late events can't be processed at all

D Late events only affect batch systems, not streaming

**0/5** correct

## Further resources

- [Event envelope](https://sandgraal.github.io/letstalkcdc/event-envelope/) for envelope field semantics feeding your merges.
- [Which row wins in your target](https://sandgraal.github.io/letstalkcdc/which-row-wins/) for the ordering and delete settings of BigQuery, Databricks, Hudi, Iceberg, Delta and Snowflake.
- [Offsets & replays](https://sandgraal.github.io/letstalkcdc/ops-offsets/) to keep staging tables consistent during rewinds.
- [Observability basics](https://sandgraal.github.io/letstalkcdc/observability/) to monitor merge throughput, freshness, and failure rates.
- [Testing a CDC pipeline](https://sandgraal.github.io/letstalkcdc/test-your-pipeline/) to prove these merges survive duplicates, reordering and replays.

---

CDC: The Missing Manual by Christopher Ennis (Let's Talk CDC), licensed under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Attribution is required.
