Write a dbt incremental model for an events table that processes only new rows
The fct_events model on dbt-snowflake (default incremental strategy merge) reads stg_events, which grows by about 5 million rows a day. Make it incremental.
Requirements:
- the first run builds the whole table from
stg_events; - every later run reads only rows whose
loaded_atis newer than whatfct_eventsalready holds; - an event re-delivered with the same
event_idupdates its row instead of adding a duplicate.
{{ config(
materialized='incremental',
unique_key='event_id'
) }}
select
event_id,
user_id,
event_type,
event_ts,
loaded_at
from {{ ref('stg_events') }}
-- your code here: limit later runs to new rowsWrite the implementation, then say what --full-refresh does and when you need it.
Wrap the filter in {% if is_incremental() %} — where loaded_at > (select max(loaded_at) from {{ this }}). The first run and --full-refresh skip it and build everything — a costly rerun needed after a logic change; unique_key merges a re-sent event.
- Filtering on
{{ this }}withoutis_incremental(), which breaks the first build - Leaving out
unique_key, so re-delivered events append as duplicates - Changing model logic without
--full-refresh, leaving old rows computed the old way
- Why does the filter compare
loaded_atrather than the event timeevent_ts? - What does
on_schema_changedo when you add a column to an incremental model?
Wrap the watermark filter in is_incremental(). The macro returns true only when the model is materialized as incremental, its table already exists and the run is not a --full-refresh. So the first run builds the whole table, and later runs read only rows newer than the maximum in {{ this }} — the model's own relation in the current environment.
{{ config(
materialized='incremental',
unique_key='event_id'
) }}
select
event_id,
user_id,
event_type,
event_ts,
loaded_at
from {{ ref('stg_events') }}
{% if is_incremental() %}
-- only rows loaded since the last run
where loaded_at > (select max(loaded_at) from {{ this }})
{% endif %}unique_key='event_id' turns the append into an upsert: on dbt-snowflake the default strategy is merge, so a re-delivered event updates its row. Without unique_key the same merge behaves like append, and a re-delivery adds a duplicate.
dbt run --full-refresh --select fct_events recreates the table from scratch: is_incremental() returns false and the filter is skipped. It is expensive — the whole source is read again — but required after a change to the model's logic; otherwise old rows stay computed the old way and new ones the new way.
The filter uses loaded_at, not event_ts: an event can arrive late carrying an old event time, and a filter on event_ts would skip it.