Query-based or log-based CDC: pick the capture first
Change data capture means moving only the rows that changed since the last load. There are two ways to find them. Query-based capture asks the source for rows whose updated_at is newer than the last run; it is simple, but it misses hard deletes and depends on every write updating that column. Log-based capture reads the database transaction log, for example with Debezium, and sees every insert, update and delete in order, at the cost of running and monitoring a connector.
This tutorial starts after capture. It assumes a changes table in BigQuery with one row per change and an operation code, which is what a log-based connector produces and what a query-based extract can be shaped into. The apply step is the same either way, and it is where most of the correctness problems are.
1. Create the target and the changes table
Use a dedicated dataset, here cdc_demo, in the same location as your Airflow connection expects. The changes table records what happened (op is I, U or D), when it happened in the source (change_ts), a sequence number to order changes with the same timestamp, and when the row landed in BigQuery (_loaded_at). The target holds the current state of each customer.
create table if not exists cdc_demo.customers_changes (
customer_id int64 not null,
email string,
status string,
op string not null, -- 'I', 'U' or 'D'
change_ts timestamp not null, -- commit time in the source
change_seq int64 not null, -- orders changes with the same change_ts
_loaded_at timestamp not null -- when the row landed in BigQuery
)
partition by date(_loaded_at);
create table if not exists cdc_demo.customers (
customer_id int64 not null,
email string,
status string,
updated_at timestamp not null,
updated_seq int64 not null
);2. Load the table once
The first load is a one-time full copy: export the source table, load it into BigQuery, and insert it into the target with the snapshot time as updated_at. Record that snapshot time. Changes committed after it are applied by the incremental step; changes before it are already in the snapshot. With log-based capture, start the connector before taking the snapshot so no change falls between the two.
insert into cdc_demo.customers (customer_id, email, status, updated_at, updated_seq)
select customer_id, email, status, timestamp '2026-11-01 00:00:00+00', 0
from cdc_demo.customers_snapshot;3. Apply each batch with one idempotent MERGE
The MERGE takes the changes that landed in one load window, keeps only the latest change per customer, and applies it. Three guards make it safe. Picking the latest change per key stops a batch with several updates to one customer from failing or applying them in the wrong order. Comparing change_ts and change_seq with the target stops an older, late-arriving change from overwriting a newer one. And because a rerun of the same window finds the target already at that version, it changes nothing.
Deletes are applied as deletes here. If reports need to know a customer existed, add an is_deleted column and update it instead; that is the usual choice for analytics.
merge cdc_demo.customers as t
using (
select * except (rn)
from (
select *,
row_number() over (
partition by customer_id
order by change_ts desc, change_seq desc
) as rn
from cdc_demo.customers_changes
where _loaded_at >= timestamp('{{ data_interval_start }}')
and _loaded_at < timestamp('{{ data_interval_end }}')
)
where rn = 1
) as s
on t.customer_id = s.customer_id
when matched
and s.op = 'D'
and (s.change_ts > t.updated_at
or (s.change_ts = t.updated_at and s.change_seq >= t.updated_seq)) then
delete
when matched
and s.op != 'D'
and (s.change_ts > t.updated_at
or (s.change_ts = t.updated_at and s.change_seq > t.updated_seq)) then
update set email = s.email, status = s.status,
updated_at = s.change_ts, updated_seq = s.change_seq
when not matched and s.op != 'D' then
insert (customer_id, email, status, updated_at, updated_seq)
values (s.customer_id, s.email, s.status, s.change_ts, s.change_seq);4. Schedule it with Airflow
The DAG runs the MERGE once per hour for the window Airflow assigns to that run. max_active_runs=1 keeps windows applied in order, and because each run is tied to its own window, a failed hour can be cleared and rerun, or a range backfilled, without touching other hours. This uses Airflow 2.10 with the Google provider and a google_cloud_default connection that can run jobs in the dataset.
Add a check after the MERGE before anyone depends on the table: the row count against the source, or a row-level comparison of a sample of keys. A MERGE that runs without errors can still be applying the wrong window.
from datetime import datetime, timedelta
from airflow import DAG
from airflow.providers.google.cloud.operators.bigquery import BigQueryInsertJobOperator
with DAG(
dag_id="customers_cdc",
start_date=datetime(2026, 11, 1),
schedule="@hourly",
catchup=False,
max_active_runs=1,
template_searchpath=["/opt/airflow/sql"],
default_args={"retries": 2, "retry_delay": timedelta(minutes=5)},
) as dag:
BigQueryInsertJobOperator(
task_id="merge_customers",
location="EU",
configuration={
"query": {
"query": "{% include 'merge_customers.sql' %}",
"useLegacySql": False,
}
},
)The dbt incremental alternative, and when to choose each
If the changes table is already a dbt source, an incremental model with the merge strategy does the same job inside dbt, and Airflow, or any scheduler, only runs dbt build. It is simpler when the team already works in dbt. Two limits to know: dbt merge does not delete rows, so keep deletes as an is_deleted flag, and it does not compare versions with the existing row, so a late, older change can overwrite a newer one unless you filter for it.
Choose the hand-written MERGE when hard deletes or strict ordering matter, or when the apply step must run outside dbt. Choose the dbt model when soft deletes are fine and you want lineage, tests and documentation in one project.
{{ config(
materialized='incremental',
unique_key='customer_id',
incremental_strategy='merge'
) }}
select customer_id, email, status, op = 'D' as is_deleted,
change_ts as updated_at, _loaded_at
from (
select *,
row_number() over (
partition by customer_id order by change_ts desc, change_seq desc
) as rn
from {{ source('cdc', 'customers_changes') }}
{% if is_incremental() %}
where _loaded_at > (select max(_loaded_at) from {{ this }})
{% endif %}
)
where rn = 1