Caricamenti incrementali che puoi rilanciare
Quando una tabella è troppo grande per ricostruirla a ogni esecuzione, carica solo le novità: le righe successive all'ultima già presente nella destinazione, il suo high-water mark. I job possono essere rilanciati, quindi il caricamento deve essere anche idempotente: una seconda esecuzione non cambia nulla.
INSERT INTO fct_events
SELECT r.*
FROM raw_events r
WHERE r.occurred_at >= (SELECT MAX(occurred_at) FROM fct_events) - INTERVAL '3 days'
AND NOT EXISTS (SELECT 1 FROM fct_events f WHERE f.event_id = r.event_id);
Tre giorni di margine recuperano gli eventi arrivati in ritardo; il controllo sulla chiave rende innocua la loro
rilettura. Per riprendere anche le righe corrette, cancella la finestra e reinseriscila, oppure fai un MERGE su
event_id.
La trappola. Un watermark sull'ora dell'evento, senza margine, non carica mai un evento che arriva con un orario
precedente al watermark, e un INSERT senza controllo sulla chiave raddoppia la finestra a ogni rilancio. Nessuno dei
due problemi genera un errore: ogni tanto ricostruisci tutto da zero, confronta chiave per chiave con un FULL JOIN e
allarga la finestra se i risultati divergono. Solo un full refresh elimina le righe cancellate alla sorgente.
In dbt. materialized='incremental' con unique_key='event_id'; il filtro va dentro {% if is_incremental() %} e
legge la destinazione come {{ this }}. Le strategie merge e delete+insert sostituiscono le righe della finestra,
append le duplica; microbatch rielabora giorni interi, con un lookback; --full-refresh ricostruisce tutto.
La trappola
WITH fct_events(event_id, occurred_at) AS (VALUES (1, TIMESTAMP '2026-06-28 09:00'), (2, TIMESTAMP '2026-06-29 18:30'), (3, TIMESTAMP '2026-06-30 08:15')), raw_events(event_id, occurred_at) AS (VALUES (2, TIMESTAMP '2026-06-29 18:30'), (3, TIMESTAMP '2026-06-30 08:15'), (4, TIMESTAMP '2026-06-29 22:10'), -- late: sent by a phone that was offline (5, TIMESTAMP '2026-06-30 11:40')) SELECT r.event_id, r.occurred_at FROM raw_events r WHERE r.occurred_at > (SELECT MAX(occurred_at) FROM fct_events) ORDER BY r.event_id;
| event_id | occurred_at |
|---|---|
| 5 | 2026-06-30 11:40:00 |
La correzione
WITH fct_events(event_id, occurred_at) AS (VALUES (1, TIMESTAMP '2026-06-28 09:00'), (2, TIMESTAMP '2026-06-29 18:30'), (3, TIMESTAMP '2026-06-30 08:15')), raw_events(event_id, occurred_at) AS (VALUES (2, TIMESTAMP '2026-06-29 18:30'), (3, TIMESTAMP '2026-06-30 08:15'), (4, TIMESTAMP '2026-06-29 22:10'), -- late: sent by a phone that was offline (5, TIMESTAMP '2026-06-30 11:40')) SELECT r.event_id, r.occurred_at FROM raw_events r WHERE r.occurred_at >= (SELECT MAX(occurred_at) FROM fct_events) - INTERVAL '3 days' AND NOT EXISTS (SELECT 1 FROM fct_events f WHERE f.event_id = r.event_id) ORDER BY r.event_id;
| event_id | occurred_at |
|---|---|
| 4 | 2026-06-29 22:10:00 |
| 5 | 2026-06-30 11:40:00 |