Late and missing data
Part of the free LogicWiz Data Engineering course, Module 6: Batch pipelines. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is Friday, 6 June. Tess checks 3 June against the store's own report, and the warehouse is $17.55 short. No job failed. You search the files and find order 1016. It was placed on 3 June at 12:10, but the store's export missed it that night and sent it two days later, in the 5 June file, still stamped with its 3 June time. Your job read that row and threw it away.
You'll learn to
- Explain why a strict watermark skips a row that arrives late
- Catch late rows with a lookback and a newer-wins merge
- Measure lateness, then backfill a date range safely
- Plan a large backfill around the tightest limit
Learn
The row arrived. The job threw it away.
Open the 5 June file and order 1016 is right there. So the row did arrive. Why is it not in the warehouse?
Every row has two times. One is when the change happened: its updated_at, 3 June at 12:10. The other is when the row arrived: the night of 5 June. Usually they are the same day. For 1016 they are two days apart.
Your job uses a strict watermark. On night 5 it asks for rows with updated_at above 2025-06-04 23:17:28. A watermark only looks forward. Anything that lands behind it is skipped, without a word.
A strict watermark, night by night
import duckdb
duckdb.sql("CREATE TABLE orders (order_id INT PRIMARY KEY, status VARCHAR, updated_at TIMESTAMP)")
watermark = '1900-01-01 00:00:00'
for day in ['2025-06-01', '2025-06-02', '2025-06-03', '2025-06-04', '2025-06-05']:
batch = f"""
SELECT DISTINCT order_id, status, updated_at
FROM read_csv_auto('landing/orders/{day}*.csv')
WHERE updated_at > TIMESTAMP '{watermark}'
"""
n = duckdb.sql(f"SELECT COUNT(*) FROM ({batch})").fetchone()[0]
duckdb.sql(f"INSERT OR REPLACE INTO orders {batch}")
watermark = str(duckdb.sql("SELECT MAX(updated_at) FROM orders").fetchone()[0])
print(day, 'loaded', n, '| watermark now', watermark)
print('order 1016 loaded?', duckdb.sql("SELECT COUNT(*) FROM orders WHERE order_id = 1016").fetchone()[0] == 1)
Each night reads its file(s) and keeps the rows above the watermark. INSERT OR REPLACE is DuckDB's upsert on the primary key. The 5 June file has 11 rows, but only 10 are loaded, and the last line prints False.
What happened on 5 June
| Night | Watermark before | Rows in file(s) | Rows loaded |
|---|---|---|---|
| 3 June | 2025-06-02 21:31:17 | 14 (7 + the retry) | 7 |
| 4 June | 2025-06-03 23:31:17 | 8 | 8 |
| 5 June | 2025-06-04 23:17:28 | 11 | 10: order 1016 skipped |
| order 1016's updatedat | 2025-06-03 12:10:25 | below the watermark |
Read the last two rows together. The job compared 2025-06-03 12:10:25 with a watermark of 2025-06-04 23:17:28 and threw 1016 away. Unless 1016 changes again, it never reaches the warehouse.
Late data is normal
It is tempting to call 1016 bad luck. It is not. Rows show up after newer rows have loaded all the time:
- an export fails and is sent again the next day;
- a phone is offline and sends its events the next morning;
- a long transaction commits after the job has read the table (the race of Lesson 6.2);
- a partner sends files when they get round to it.
In every case the row's own time is older than its arrival. So plan for late data in every incremental pipeline. The simulator below shows the fix you are about to build.
Incremental loads on a timeline: a late row arrives below the watermark and is skipped, then a lookback window reaches back and catches it.
Run the late night once with the lookback off: the late row is skipped. Then turn the lookback window on and run it again.
Look back, then merge
Stop reading strictly above the watermark. Read from the watermark minus a lookback window, say two days: WHERE updated_at > watermark - INTERVAL 2 DAY. A late row that falls inside the window is caught.
The price: every run rereads rows it already loaded. That is harmless only if the load is idempotent. So a lookback always travels with a merge on the key (Lesson 6.3): a reread row updates itself to the same values instead of being added again.
One more guard. Only replace a row when the incoming version is newer: incoming.updated_at > current.updated_at. Then a reread of an old version can never overwrite a newer one. Call it newer wins.
Night 5, strict and with a lookback
A timeline of the first days of June: the 5 June file holds ten rows that changed on 5 June and order 1016, which changed on 3 June; a strict read above the watermark misses 1016, and a read from the watermark minus two days covers it.
The 5 June file. Ten of its rows changed on 5 June. One, order 1016, changed on 3 June at 12:10 and is only arriving now.
A strict read. Night 5 asks for rows above the watermark, 4 June at 23:17. The ten rows are inside the amber window. Order 1016 is to the left of it: skipped.
A two-day lookback. Now night 5 asks for rows above the watermark minus two days: 2 June at 23:17. The green window reaches back over order 1016, so all 11 rows are read.
The axis is the day of June: 3 is midnight at the start of 3 June. A row is read when its updated_at falls inside the bottom bar.
Lookback plus a guarded merge
import duckdb
duckdb.sql("CREATE TABLE orders (order_id INT PRIMARY KEY, status VARCHAR, updated_at TIMESTAMP)")
watermark = '1900-01-01 00:00:00'
for day in ['2025-06-01', '2025-06-02', '2025-06-03', '2025-06-04', '2025-06-05']:
batch = f"""
SELECT DISTINCT order_id, status, updated_at
FROM read_csv_auto('landing/orders/{day}*.csv')
WHERE updated_at > TIMESTAMP '{watermark}' - INTERVAL 2 DAY
"""
n = duckdb.sql(f"SELECT COUNT(*) FROM ({batch})").fetchone()[0]
duckdb.sql(f"""
INSERT INTO orders {batch}
ON CONFLICT (order_id) DO UPDATE
SET status = excluded.status, updated_at = excluded.updated_at
WHERE excluded.updated_at > orders.updated_at
""")
watermark = str(duckdb.sql("SELECT MAX(updated_at) FROM orders").fetchone()[0])
print(day, 'loaded', n, '| watermark now', watermark)
print('order 1016 loaded?', duckdb.sql("SELECT COUNT(*) FROM orders WHERE order_id = 1016").fetchone()[0] == 1)
print('rows:', duckdb.sql("SELECT COUNT(*) FROM orders").fetchone()[0])
Night 5 now loads all 11 rows and 1016 is there. The table still holds one row per order (29 orders placed from 1 to 5 June): the merge made the rereading safe. The last line of the ON CONFLICT is the newer-wins guard.
The trap: a lookback without a merge is a duplicate machine. Rereading two days with a plain append inserts those two days again every night. And a merge without the newer-wins guard can go backwards: if a reread brings an older version of an order, WHERE incoming.updated_at > current.updated_at is what keeps the newer one.
How far back?
Two days worked for order 1016. Is two days right? Measure, do not guess.
For every landed row, compare when it arrived (its file's date) with when it happened (updated_at). The biggest gap you see, plus a margin, is your window.
Too short, and late rows still slip through. Too long, and every run rereads, and pays for, days of data. Daily batch jobs often use one to three days.
Measure lateness
-- staging.landed_orders: every landed row with the date its file arrived
SELECT file_date - updated_at::DATE AS days_late,
COUNT(*) AS rows_seen
FROM staging.landed_orders
GROUP BY file_date - updated_at::DATE
ORDER BY days_late;
SELECT file_name, order_id, updated_at
FROM staging.landed_orders
WHERE file_date - updated_at::DATE > 0;
Subtracting two dates in Postgres gives a number of days. 67 rows arrived the day they changed; one, order 1016, arrived two days late. A two-day lookback covers everything seen so far; three days gives a margin.
A whole week is wrong: the backfill
A lookback handles normal lateness. Sometimes that is not enough: a partner resends a whole week, or you fix a bug in a transform and have to rebuild a month.
Rerunning the pipeline for a range of past dates is called a backfill.
If each daily run is idempotent, a backfill is easy: the daily job in a loop over the dates, or one delete of the range followed by one insert, in a transaction. If the daily job is not idempotent, a backfill doubles everything it touches. One more reason idempotency came first.
Here is the backfill that repairs Tess's number. It rebuilds 3 to 5 June.
Backfill 3 to 5 June in one transaction
-- Before: built on the night 1016 was missing
SELECT order_date, revenue
FROM dw.daily_revenue
WHERE order_date BETWEEN DATE '2025-06-02' AND DATE '2025-06-06'
ORDER BY order_date;
BEGIN;
DELETE FROM dw.daily_revenue
WHERE order_date BETWEEN DATE '2025-06-03' AND DATE '2025-06-05';
INSERT INTO dw.daily_revenue
SELECT o.order_ts::DATE, SUM(i.qty * i.unit_price)
FROM orders AS o
JOIN order_items AS i ON i.order_id = o.order_id
WHERE o.order_ts >= TIMESTAMP '2025-06-03' AND o.order_ts < TIMESTAMP '2025-06-06'
GROUP BY o.order_ts::DATE;
COMMIT;
-- After
SELECT order_date, revenue
FROM dw.daily_revenue
WHERE order_date BETWEEN DATE '2025-06-02' AND DATE '2025-06-06'
ORDER BY order_date;
The range filter on order_ts is written as >= start AND < day after end. That form is safe for timestamps; the trap of this lesson shows why BETWEEN is not.
Before and after the backfill
| orderdate | Before | After |
|---|---|---|
| 2025-06-02 | 415.80 | 415.80 (outside the range, untouched) |
| 2025-06-03 | 532.32 | 549.87 (1016 is back) |
| 2025-06-04 | 607.44 | 607.44 (rebuilt, same value) |
| 2025-06-05 | 1382.02 | 1382.02 (rebuilt, same value) |
| 2025-06-06 | 582.09 | 582.09 (outside the range, untouched) |
3 June gained $17.55: the missing order. Rebuilding a day that was already right gives the same number. That is idempotency doing its job.
A year of days: do the sums first
Next month a partner will resend a whole year. The daily job takes 6 minutes. Work it out before you start:
- One day at a time: 365 x 6 = 2,190 minutes, which is 36.5 hours.
- Four at a time: ceil(365 / 4) = 92 waves. 92 x 6 = 552 minutes, about 9.2 hours.
- Eight at a time: 46 waves, 276 minutes, 4.6 hours.
So you run days side by side, but only up to the tightest limit in the chain: the runs the scheduler allows at once, the queries the warehouse runs at once, the connections or API calls the source can spare. Parallel runs finish sooner, but they use about the same compute.
Wall time for 365 days of a 6-minute job
Bars show the hours a one-year backfill takes at concurrency 1, 4 and 8, and at 16 requested runs that a warehouse limited to 8 concurrent queries still runs 8 at a time.
Each bar is the wall time of the whole backfill. Look at the amber bar: past the warehouse's limit, more runs only add queued queries (and timeouts). Raise the real limit, with a larger or multi-cluster warehouse, or accept the wall time.
Plan the waves
import math
from datetime import date, timedelta
def waves(start, end, concurrency, limits=()):
"""Split the days into waves of at most min(concurrency, *limits) days, oldest first."""
width = min((concurrency, *limits))
days, d = [], date.fromisoformat(start)
while d <= date.fromisoformat(end):
days.append(d.isoformat())
d += timedelta(days=1)
return [days[i:i + width] for i in range(0, len(days), width)]
plan = waves('2025-01-01', '2025-12-31', concurrency=16, limits=(8,))
print(len(plan), 'waves; the first:', plan[0][0], 'to', plan[0][-1])
print('wall time:', len(plan) * 6, 'minutes =', round(len(plan) * 6 / 60, 1), 'hours')
print('work:', 365 * 6, 'minutes; check:', math.ceil(365 / 8) == len(plan))
Sixteen requested runs against a limit of 8 give 46 waves and 276 minutes. Oldest first is the safe order when a day depends on the one before (running totals, SCD type 2). Newest first is for when people need the recent days back quickly.
Two writers, one day
One more thing before the backfill starts. The nightly job will still run while it does.
Delete-then-insert is safe to repeat. It is not safe to run twice at the same moment. Say the backfill and the nightly job both rebuild 3 June. Each one deletes the rows it can see, then inserts 14 lines. If they overlap, neither sees the other's new lines, so neither deletes them. Both commit: 28 lines, and no error.
Step through it below. Postgres runs each statement against the rows that were committed when the statement began. That default mode is called READ COMMITTED.
The overlap that doubles a day
The backfill deletes and reinserts 3 June; the nightly job starts its delete before the backfill commits, waits, finds nothing visible to delete, then inserts the day again, so both inserts survive.
The backfill starts. It deletes the 14 old lines of 3 June and inserts 14 new ones. Nothing is committed yet, so nobody else can see either change.
The nightly job starts. Its
DELETEsees the 14 old lines, but the backfill holds a lock on them. It waits.The backfill commits. The nightly
DELETEwakes up. The old lines are already gone, and the new lines were not there when its statement began. It deletes nothing.The nightly job inserts its own 14 lines and commits. Both inserts survive: 28 lines, no error. Each job was idempotent on its own.
Read each step top to bottom: the backfill is on the left, the nightly job on the right, the table in the middle. Each step adds the next messages.
Remember: safe to repeat is not safe to overlap. Allow one writer per day: take a lock named after the day as the first statement, give the table a one-slot pool in the scheduler, or use a table format that notices the clash and makes the loser retry.
Numbers to remember
| Name | Value | What it is |
|---|---|---|
| Lookback for a daily batch | often 1 to 3 days | Size it from measured lateness plus a margin, and alert on anything later |
| dbt lookback | updatedat (select max(updatedat) from {{ this }}) - interval '3 days' | With a uniquekey, an incremental model does exactly lookback plus merge |
| Airflow maxactiverunsperdag | 16 | Default cap on runs of one DAG at once (maxactiveruns on a DAG) |
| Airflow maxactivetasksperdag | 16 | Default cap on running tasks of one DAG |
| Airflow defaultpool | 128 slots | Pools cap tasks across DAGs. A one-slot pool per table means one writer at a time |
| Airflow 3 airflow backfill create | --max-active-runs, --run-backwards, --reprocess-behavior | Sets the width, runs recent days first, and says what to do with days that already ran (none, failed or completed). Lesson 9.3 has more |
| Snowflake MAXCONCURRENCYLEVEL | 8 | Queries a warehouse runs at once. The rest queue |
| Postgres isolation level | default READ COMMITTED | Under REPEATABLE READ the second writer fails with could not serialize access due to concurrent update instead of doubling the day |
| pgadvisoryxactlock(hashtext('factsales/2025-06-03')) | first in the transaction | A lock named after the partition: the second writer waits for the first |
| Delta ConcurrentAppendException | raised to the losing writer | The table format detects two writers on one partition, so the loser retries |
| "Watermark" in streaming | Spark Structured Streaming, Flink | The same word for a different thing: how long to wait for late events (Module 15) |
The story needs the first row. The rest are the limits and the locks you will look up when you plan a real backfill.
What changed at SwiftKart
The nightly orders load now reads from the watermark minus two days and merges on order_id, and only a newer version may replace a row. Order 1016 is in, and 3 June shows $549.87.
A lateness report runs every morning. Anything later than the window raises an alert, and a person repairs it with a backfill. Backfills run in waves sized to the tightest limit, with one writer per day.
All of this still trusts updated_at. Some of the store's tables have no updated_at at all. And no watermark can see a row that was deleted. Lesson 6.5 is about capturing every change.
In one line
A late row lands behind a strict watermark, so reread a lookback window sized from measured lateness, merge so only newer versions win, and backfill date ranges with idempotent loads.
Interview corner
How do you handle late-arriving data in a batch pipeline?
I measure how late data really arrives, then reread a lookback window (say two or three days below the watermark) on every run and merge on the key, so rereads are harmless and only newer versions win. Rows later than the window raise an alert, and I repair them with a backfill of the affected dates.
What is a backfill, and what must be true before you run one?
A backfill reruns the pipeline for a range of past dates, after a bug fix or a resent source. Each daily run must be idempotent (delete-then-insert or merge by date), otherwise the backfill duplicates data. I also check the cost, run it in a quiet window, and tell the people who use the affected tables.
You must backfill two years of a daily job that takes 6 minutes per day. How do you plan and run it?
First the arithmetic: 730 days x 6 minutes is 73 hours of work, so it needs parallelism. I find the tightest limit (spare source connections, the warehouse's concurrent-query limit, the orchestrator's max_active_runs) and size the waves to it: at 8 at a time it is ceil(730 / 8) = 92 waves, about 9.2 hours. Each day must be idempotent and no two writers may touch the same partition, so I pause the nightly job for those dates or take a per-partition lock. I run oldest first if days depend on each other, on a separate warehouse, after a dry run, and reconcile counts per day at the end.
How do you choose the lookback window?
From data: compare each row's arrival time with its event or update time, look at the distribution, and take the normal worst case plus a margin. Then I monitor lateness, because a window that was right last year can be wrong after the source changes.