Part 08 / Topic 2 of 7
Incremental loads and watermarks
Re-fetching everything every night stops scaling the week the customer's history outgrows the rate limit. An incremental sync fetches only what changed, by remembering a watermark — the highest updated_at (or id) already loaded:
# examples/01_incremental_sync_with_a_saved_watermark.py
import json, pathlib, tempfile
STATE = pathlib.Path(tempfile.mkdtemp()) / "state.json"
SOURCE = [{"id": f"S-{2000+i}", "updated_at": f"2025-04-{i+1:02d}"} for i in range(8)]
def sync(source, target):
watermark = json.loads(STATE.read_text())["watermark"] if STATE.exists() else ""
# Strict ">" can miss rows that share the watermark value but commit later.
# In production use ">=" (or an overlap window) and rely on an idempotent upsert to absorb repeats.
new = [r for r in source if r["updated_at"] > watermark]
for r in new:
target[r["id"]] = r
if new:
STATE.write_text(json.dumps({"watermark": max(r["updated_at"] for r in new)}))
return len(new)
target = {}
print("run 1 loaded:", sync(SOURCE[:5], target))
print("run 2 loaded:", sync(SOURCE[:5], target), "(nothing new)")
print("run 3 loaded:", sync(SOURCE, target), "(only the 3 newer rows)")
print("watermark now:", json.loads(STATE.read_text())["watermark"], "| target rows:", len(target))
# run 1 loaded: 5
# run 2 loaded: 0 (nothing new)
# run 3 loaded: 3 (only the 3 newer rows)
# watermark now: 2025-04-08 | target rows: 8
Two rules carry the whole design:
- Save the watermark only after the data is safely loaded. Saved first + failed load = those rows are skipped forever, silently.
- Fetch with
>=(or a small overlap window) and let the idempotent upsert absorb the repeats. The strict>in the demo can miss rows that share the watermark timestamp but committed later — the comment in the code is load-bearing.
🧪 Quick quiz
- What is a watermark in an incremental sync?
Show the answer
The highest updated_at (or id) already loaded, saved so the next run fetches only newer rows. Run 2 loaded 0 rows and run 3 loaded only the 3 newer ones. (verified against the example output above)
- When should the watermark be saved?
Show the answer
After the data is safely loaded. Saving it first would skip rows forever if the load then failed.
Done here? The practice set for Part 8 — 4 exercises with solutions — is on the part page.