Part 08 / Stage 2
Pipelines
Goal: Turn one-off scripts into a pipeline that runs every day: incremental with a watermark, observable through run reports, and safe to re-run after any failure. Time: ~3 hours · Needs: Python 3.14+, the course venv
What you will learn
- Extract, transform, load as separate, testable steps
- Incremental loads and watermarks
- Backfills that do not hurt the source system
- Scheduling: cron and workflow orchestrators
- Run reports and alerts: row counts, freshness, failures
- Recovering from failure: re-running safely, partial loads
- Queues and event streams: when polling is the wrong shape
Topics in this part
Practice
Work in the course venv. Check each answer by running it; compare with solutions/ only after trying.
Exercise 1: Test one step alone
Take the lesson's transform(df) and write two pytest tests run from the script (as in Part 3): one proving duplicates are dropped, one proving statuses are normalised. No extract or load involved.
Show the solution to Exercise 1
# Exercise 1: the transform step tested on its own
import pathlib, re, subprocess, sys, tempfile, textwrap
code = textwrap.dedent('''
import pandas as pd
def transform(df):
df = df.drop_duplicates().copy()
df["status"] = df["status"].str.strip().str.lower().str.replace(" ", "_")
df["customer"] = df["customer"].str.strip()
return df[["shipment_id", "customer", "status"]]
def test_duplicates_dropped():
df = pd.DataFrame([{"shipment_id": "S-1", "customer": "A", "status": "Delivered"}] * 2)
assert len(transform(df)) == 1
def test_statuses_normalised():
df = pd.DataFrame([{"shipment_id": "S-1", "customer": " A ", "status": " in transit "}])
out = transform(df)
assert out.iloc[0]["status"] == "in_transit"
assert out.iloc[0]["customer"] == "A"
''')
folder = pathlib.Path(tempfile.mkdtemp())
(folder / "test_transform.py").write_text(code)
r = subprocess.run([sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", str(folder)],
capture_output=True, text=True)
print(re.sub(r" in \d+\.\d+s", "", r.stdout.strip().splitlines()[-1]))
Exercise 2: Watermark with overlap
Modify the lesson's sync to fetch with >= and prove with a run sequence that (a) rows sharing the watermark timestamp are re-fetched and (b) the idempotent target (a dict keyed by id) still ends with the right count.
Show the solution to Exercise 2
# Exercise 2: >= overlap re-fetches the boundary row; the upsert absorbs it
import json, pathlib, tempfile
STATE = pathlib.Path(tempfile.mkdtemp()) / "state.json"
def sync(source, target):
watermark = json.loads(STATE.read_text())["watermark"] if STATE.exists() else ""
new = [r for r in source if r["updated_at"] >= watermark] # overlap on purpose
for r in new:
target[r["id"]] = r # keyed: repeats are harmless
if new:
STATE.write_text(json.dumps({"watermark": max(r["updated_at"] for r in new)}))
return len(new)
# two rows share the same timestamp; one "commits late" and only appears in run 2's source
early = [{"id": "S-1", "updated_at": "2025-04-05"}, {"id": "S-2", "updated_at": "2025-04-05"}]
late = early + [{"id": "S-3", "updated_at": "2025-04-05"}] # same timestamp, seen later
target = {}
print("run 1 fetched:", sync(early, target))
print("run 2 fetched:", sync(late, target), "(re-fetches the 04-05 boundary, catches S-3)")
print("target rows:", len(target), "- no duplicates, nothing missed")
assert len(target) == 3
Exercise 3: A chunked backfill
Write backfill(source, target, chunk_days=2) over rows dated 2025-04-01..08 that loads in date chunks, checkpoints after each chunk (print it), and — when interrupted after the second chunk (simulate with an exception) — resumes from the checkpoint instead of restarting.
Show the solution to Exercise 3
# Exercise 3: a chunked backfill that resumes from its checkpoint
import json, pathlib, tempfile
CHECKPOINT = pathlib.Path(tempfile.mkdtemp()) / "backfill.json"
SOURCE = [{"id": f"S-{i}", "date": f"2025-04-{i:02d}"} for i in range(1, 9)]
CHUNKS = [("2025-04-01", "2025-04-02"), ("2025-04-03", "2025-04-04"),
("2025-04-05", "2025-04-06"), ("2025-04-07", "2025-04-08")]
def backfill(target, fail_after=None):
done = json.loads(CHECKPOINT.read_text())["done"] if CHECKPOINT.exists() else []
for i, (start, end) in enumerate(CHUNKS):
if [start, end] in done:
print(f" skip chunk {start}..{end} (already done)")
continue
if fail_after is not None and len(done) >= fail_after:
raise RuntimeError("simulated interruption")
for r in (r for r in SOURCE if start <= r["date"] <= end):
target[r["id"]] = r
done.append([start, end])
CHECKPOINT.write_text(json.dumps({"done": done}))
print(f" checkpoint after {start}..{end}")
target = {}
try:
backfill(target, fail_after=2)
except RuntimeError as e:
print("interrupted:", e)
print("resuming:")
backfill(target)
print("rows backfilled:", len(target))
Exercise 4: Volume alert
Write check_run(report, history) that returns an alert string when loaded is less than half the median of the last 5 runs, else None. Show it staying quiet on a normal run and firing on a zero-row run.
Show the solution to Exercise 4
# Exercise 4: alert when volume collapses
from statistics import median
def check_run(report, history):
typical = median(run["loaded"] for run in history[-5:])
if report["loaded"] < typical / 2:
return f"ALERT: loaded {report['loaded']} rows; recent median is {typical:.0f}"
return None
history = [{"loaded": n} for n in (400, 420, 395, 410, 405)]
print("normal run:", check_run({"loaded": 398}, history))
print("bad run: ", check_run({"loaded": 0}, history))
Mini-project: Scheduled Acme sync
One script that performs an incremental sync from the simulated API (reuse your Part 5 client; the API rows carry updated_at), upserts into sqlite, saves the watermark after the load, and writes a JSON run report (extracted, loaded, watermark, duration). Run it twice to show the second run loads 0.
A solution is in solutions/mini_scheduled_acme_sync.py.
Stretch: add a --backfill mode that chunks history and respects the rate limit, and an alert when a run loads unusually few rows.
Common mistakes
| Mistake | Why it hurts | Fix |
|---|---|---|
| One monolithic script | Untestable; a failure anywhere restarts everything | extract / transform / load as functions |
| Full reload every night | Breaks on rate limits as history grows | Watermark + incremental fetch |
| Saving the watermark before the load | A failed load skips rows forever | Save only after success; fetch with overlap |
| Backfilling at full speed | You take down the customer's source system | Chunk, checkpoint, stay under the limit |
| Alerting only on exit codes | Zero-row "successes" go unnoticed | Alert on volume and freshness |
| Assuming exactly-once delivery | Queues deliver at-least-once | Idempotent consumers |
Quick recap
- A pipeline is three functions — extract, transform, load — plus a run report of counts per step.
- A watermark means fetching only what is newer and saving the mark only after a safe load; a small overlap plus upserts keeps it correct.
- Backfills run chunked and checkpointed, stay polite to the source, and get reconciled at the end.
- Schedule with the simplest thing the customer can operate.
- Alert on data volume and freshness, not on exit codes.
- If you designed for it, every failure's runbook is the same line: run it again.
Checklist
- I ran the watermark sync three times and can explain each run's count.
- I can state the watermark save rule and what
>=+ upsert buys. - I printed a run report with counts per step.
- I can plan a polite backfill in four bullet points.
- I know when a queue beats polling, and what at-least-once implies.
Read more: cron (Wikipedia) · Apache Airflow docs