Skip to content

Data and ML pipelines

Phase 7 · Designing AI systems · 16 min read · 8 Atlas cases linked

What you'll be able to do

  • Draw a pipeline as a DAG and make each step safe to rerun: idempotent, deterministic, atomic, and gated by validation.
  • Choose between batch, micro-batch and streaming, and trace a late event through windows and a watermark.
  • Spot where a training pipeline leaks the future or drifts between training and serving, and say how you would roll a model back.

From notebook to pipeline

A pipeline turns raw data into something useful on a schedule or trigger, without you in the loop. Typical stages:

A data pipeline: each stage feeds the next, and every stage reports to monitoring.

A pipeline is a DAG (directed acyclic graph): nodes are tasks, edges mean "B needs A's output". A valid run order is a topological order (Data structures and Big-O):

from graphlib import TopologicalSorter
deps = {"clean": {"ingest"}, "features": {"clean"},
        "train": {"features"}, "report": {"train", "clean"}}
print(list(TopologicalSorter(deps).static_order()))
# ['ingest', 'clean', 'features', 'train', 'report']

An orchestrator (Airflow-style schedulers are one example) runs the graph: it starts a task when its upstream tasks succeed, retries failures, and records what happened. Some tools also skip work. Cache a task only when its key includes every dependency that can change its output: code version, input hashes, relevant configuration, and for a source task the source snapshot id or run date. Do not skip a side-effecting task (a deploy, an external write) unless its effect is tracked too and safe to reuse. You build the caching in the lab.

Steps you can trust

Every step must survive being run twice. An idempotent step leaves the same final state after one run or three (see Delivery guarantees and idempotency). A daily job that appends 10,000 rows is not: two retries leave 3 × 10,000 = 30,000 rows, and every downstream sum is tripled. Fix it by partitioning outputs by run key (for example date=2025-03-01/) and overwriting or upserting that partition.

For reproducible outputs and reliable cache keys, make pure transformations deterministic: same inputs and code, same output. The clock and unseeded randomness break this, so pass in the run date and the seed as parameters.

Output must be atomic: readers see the old result or the complete new one. Write a temporary file in the same directory, then rename it over the target; os.replace on one POSIX filesystem is atomic. A process crash may leave a stray temp file, not a half-written output. Object stores generally do not provide atomic rename. Table formats use a commit protocol, such as atomic creation of a log entry or an atomic update of a snapshot pointer, so readers see one committed version.

Together these make backfills possible: to reprocess March, rerun its partitions. Unparseable records should neither kill the batch nor vanish: send them to a dead-letter location with the error, and alert when their count jumps.

Gates, contracts and versions

Most pipeline failures are silent: the job succeeds and the data is wrong. Put quality gates between stages that stop the run on failed checks: schema, null rate, value ranges, row counts, and drift against a reference period. With 1,000 rows and a 2% null limit, up to 20 nulls pass; 35 nulls is 3.5% and fails.

A data contract is the agreement between a dataset's producer and consumer: names, types, meaning, freshness. Adding an optional column is usually a safe schema evolution, but only for consumers that tolerate unknown fields: update a strict schema gate before the producer adds the field. Renaming, removing or retyping a column breaks consumers and needs a new version.

Never keep only a mutable latest dataset. Give each snapshot an immutable id and record lineage (which inputs and code produced it), so "what data trained this model?" has an answer.

Storage layers and cost

The medallion layout keeps raw (bronze: exactly what arrived), cleaned (silver: validated, deduplicated, typed) and curated (gold: aggregates and features) data. Because raw is kept, you can rebuild everything downstream after a bug.

A data lake is cheap files in object storage, flexible but easy to turn into a swamp. A warehouse is a managed SQL engine with strong schemas. A lakehouse adds table semantics (schemas, transactions) over lake files (Choosing a datastore). Analytics files are usually columnar (Parquet-style): a query over 3 of 100 equally sized columns reads roughly 3% of the column data (Storage engines).

Two cost traps. Partition by a key your queries filter on (Partitioning), but avoid the small-files problem: 10,000 files of 100 KB is about 1 GB, yet opening 10,000 files costs far more than reading about 8 files of 128 MB, so compact them. And a shuffle, moving rows between workers so equal keys meet for a join, is network and disk heavy; keep the count low.

Batch versus streaming

Batch Micro-batch Streaming
Runs per period per short interval per event, continuously
Completeness whole period small slices partial, may be revised
Cost and complexity usually lowest usually moderate usually highest: state, ordering, recovery

These are tendencies; real delay and cost depend on scale, engine and targets.

Start with batch and move only when freshness matters. Lambda runs a batch path and a streaming path and merges them; the risk is two code paths that drift apart. Kappa uses one streaming path and reprocesses by replaying a retained log: simpler, but it needs a replayable log and careful state handling.

Streams use event time (when it happened), not processing time (when you saw it), because queues back up and devices go offline. Aggregation uses windows: tumbling (fixed, non-overlapping), sliding (overlapping) and session (split by gaps of inactivity). Because events arrive late, a watermark says "all events up to time T have probably arrived"; a common rule is the largest event time seen minus a tolerance. With 10-second tumbling windows and a 5-second tolerance:

Arrival Event time Watermark What happens
1 3 -2 counted in [0,10)
2 14 9 counted in [10,20); [0,10) stays open
3 8 9 out of order, still counted in [0,10)
4 22 17 watermark passes 10: emit [0,10) with 2 events
5 6 17 window already emitted: late, goes to a side output
6 31 26 watermark passes 20: emit [10,20) with 1 event

A larger tolerance catches more late data but delays results and holds more state. The watermark is a guess, so decide what late events do: drop, route aside, or revise.

Many stream setups redeliver events after a failure. Upserting a deterministic, complete window result under a stable key such as (window start, group) is an idempotent sink: repeated writes overwrite the same row. It does not stop a replayed event from being counted twice before the write. For exactly-once effects, also deduplicate inputs by event id, or use a checkpoint and sink protocol that handles replay (Queues, pub/sub and streams).

ML-specific pipelines

A training pipeline runs data, features, train, evaluate, register, deploy. A model registry stores each version with its metrics and the data version, code version and config that made it; reproducibility needs those plus the seed. Retraining can be triggered by schedule, new data, or monitoring. An evaluation gate blocks deployment if the new model is worse (Evals as tests). A shadow deployment sends live traffic to the new model and logs its predictions without serving them (Serving models).

Training/serving skew means the model sees different features online than offline (a different tokenizer, rounding or missing-value default). Use one feature code path for both, or a feature store serving the same definitions offline and online.

Time leakage is subtler. A churn model predicts at time 10, the prediction cutoff; whether the customer churned is observed later. A ticket count was 2 at time 5 and 9 at time 12. Joining the "latest" value gives 9, which includes the future. So would a count of 4 that describes time 8 but only arrived in your tables at time 11. A point-in-time join takes, per label, the latest feature value whose event time and availability time are both at or before the cutoff (SQL and relational modeling). Split train and test by time too.

For AI engineers

Your notebook is already a pipeline, one cell at a time. Make it rerunnable: a dataset version id instead of data_final_v3.csv, preprocessing in one tested function used by training and serving, a validation gate before fit, a seed and config saved with the model, and a registry entry to roll back to.

LLM-era pipelines have the same shape. RAG ingestion is parse, chunk, embed, upsert (Designing a RAG system): key chunks by document id and content hash so identical reruns do not duplicate vectors. When a document changes, also delete the keys of chunks no longer present. Include the chunking and embedding versions in the index identity: changing the embedding model means re-embedding everything into a new index, then switching. Version eval sets, and gate logged feedback for PII and your own model's outputs before it becomes training data.

Common mistakes

  • Appending on rerun: a retry duplicates rows. Overwrite or upsert by partition or key.
  • Training on the future: random splits, or the latest feature value instead of the value available at prediction time.
  • Different preprocessing in training and serving: two implementations diverge.
  • No validation until the model fails silently: bad data trains a bad model with no error.
  • A huge notebook as the pipeline: no caching, retries or partial reruns.
  • No backfill plan, and a mutable "latest" dataset: you cannot reprocess history or say what trained a model.

Check yourself

A nightly job appends 50,000 rows, times out at 80% done, and is retried. What goes wrong, and what are two fixes?

If the first attempt committed as it went, about 40,000 rows are already there and the retry adds 50,000 more, so rows are duplicated. Make the step idempotent: overwrite a date partition, or upsert on a unique key.

With 10-second windows and a 5-second tolerance, the largest event time seen is 40 and an event stamped 33 arrives. Is it accepted? What about 29?

The watermark is 40 - 5 = 35. Event 33 belongs to [30,40), which ends at 40 > 35, so the window is open and the event counts. Event 29 belongs to [20,30), which closed once the watermark passed 30, so it is late.

Offline AUC is excellent but live results are poor. Name two pipeline causes to check first.

Time leakage (features or splits using information from after prediction time) and training/serving skew (features computed by different code online).

Lab

Build five pipeline building blocks in code/data-ml-pipelines/:

  • a DAG runner that skips tasks whose version and input hashes are unchanged;
  • a batch validator with a gate;
  • a tumbling window with a watermark and a late-event side output;
  • an atomic file write that survives a crash mid-write;
  • a point-in-time join that respects both event time and availability time.

Run: cd code/data-ml-pipelines && PYTHONPATH=starter python -m pytest tests -q

Go deeper

See it in the wild

Open these real architectures and find the idea in the diagram. Predict how it is used before you read the analysis.