Automating Training Pipelines with Kubeflow and Airflow
Difficulty: Senior Level | Companies: Google, Meta, Netflix, Uber, Stripe
Prerequisites
- !Running a training script end to end
- !Basic familiarity with containers
- !Understanding of DAGs and task dependencies
What You'll Learn
- 1Decompose a training script into stages with explicit contracts
- 2Choose between Kubeflow Pipelines and Airflow with real criteria
- 3Write components that are cached, retryable, and independently testable
- 4Design for spot interruptions without losing hours of work
What turns a training script into a pipeline
A training script answers one question: how do I fit a model. A pipeline answers a different one: how do I run this again next Tuesday when the data is different, the author is on leave, and the previous attempt failed halfway through. The transformation is not automation for its own sake â it is the moment intermediate artifacts get names, each stage gets an interface, and failure becomes a property of one stage rather than a mystery across four hundred lines of notebook output. Until that happens, every retraining is an act of faith.
Three properties separate a pipeline from a script chained with ampersands. Each stage declares its inputs and outputs as artifacts rather than implicit filesystem paths. Each stage is idempotent, so a retry after a transient network error cannot double-write or half-write. And each stage is individually testable, because a pipeline you cannot unit test becomes a system where the only way to reproduce a failure is to break production again.
Picking an orchestrator
The choice is less about features than about who runs what and how long jobs live. Kubeflow Pipelines packages each step as a container, which gives strong isolation and a natural caching unit at the cost of a Kubernetes cluster to operate. Airflow schedules Python callables and sensors with a mature ecosystem for backfills and SLAs, but its execution model assumes tasks are lightweight coordinators rather than heavy trainers. Many teams end up with both: Airflow for the calendar and data dependencies, KFP for the training steps that need GPUs.
| Criterion | Kubeflow Pipelines | Apache Airflow |
|---|---|---|
| Unit of work | Container per step | Python callable per task |
| Best suited to | GPU training, ML-specific caching | Backfills, SLAs, cross-system DAGs |
| Caching | Step-level memoization by inputs | External, usually manual |
| Failure isolation | Pod per step, easy to inspect | Logs per task, shared workers |
| Operational weight | Kubernetes plus KFP services | Scheduler, metadata DB, workers |
| Typical team | ML platform owning clusters | Data platform already running Airflow |
If nobody on your team can operate Kubernetes on call, choosing KFP anyway means your first real test arrives during an incident. Start with the orchestrator you can debug at 3 a.m. and migrate later; the stage contracts you write now will carry over.
Steps as containers: a Kubeflow pipeline
Componentization forces the contract question early, because each function gets packaged into its own image and can only communicate through declared inputs and outputs. The example below validates data, builds features, and trains â each step independently rerunnable, with hyperparameters passed as pipeline parameters so a re-run with new values does not require editing code.
# kfp_pipeline.py
import kfp
from kfp import dsl
from kfp.dsl import component, Input, Output, Dataset, Model
@component(base_image="python:3.11-slim",
packages_to_install=["pandas==2.2.0", "pyarrow==15.0.0"])
def validate_data(data_path: str, min_rows: int = 1000, max_null_ratio: float = 0.1) -> str:
import json
import pandas as pd
df = pd.read_parquet(data_path)
errors = []
if len(df) < min_rows:
errors.append(f"only {len(df)} rows, need {min_rows}")
null_ratio = float(df.isnull().mean().mean())
if null_ratio > max_null_ratio:
errors.append(f"null ratio {null_ratio:.3f} exceeds {max_null_ratio}")
if errors:
raise ValueError("; ".join(errors))
return json.dumps({"rows": len(df), "columns": list(df.columns)})
@component(base_image="python:3.11-slim",
packages_to_install=["pandas==2.2.0", "scikit-learn==1.4.0"])
def build_features(data_path: str, features: Output[Dataset],
target: str = "churned") -> str:
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
df = pd.read_parquet(data_path)
numeric = [c for c in df.columns if c != target and df[c].dtype.kind in "fi"]
preprocessor = ColumnTransformer([(
"num",
Pipeline([("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler())]),
numeric,
)], remainder="drop")
X = preprocessor.fit_transform(df[numeric])
out = pd.DataFrame(X, columns=numeric)
out[target] = df[target].values
out.to_parquet(features.path, index=False)
return f"{len(numeric)} numeric features, {out.shape[0]} rows"
@component(base_image="python:3.11-slim",
packages_to_install=["pandas==2.2.0", "scikit-learn==1.4.0"])
def train(features: Input[Dataset], model: Output[Model],
n_estimators: int = 300, max_depth: int = 8) -> str:
import json
import pandas as pd
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.metrics import accuracy_score, f1_score
from sklearn.model_selection import train_test_split
target = "churned"
df = pd.read_parquet(features.path)
X = df.drop(columns=[target])
y = df[target]
X_tr, X_te, y_tr, y_te = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
clf = GradientBoostingClassifier(
n_estimators=n_estimators, max_depth=max_depth, random_state=42
)
clf.fit(X_tr, y_tr)
pred = clf.predict(X_te)
metrics = {
"accuracy": float(accuracy_score(y_te, pred)),
"f1": float(f1_score(y_te, pred, average="weighted")),
"n_estimators": n_estimators,
"max_depth": max_depth,
}
import joblib
joblib.dump(clf, model.path)
model.metadata["metrics"] = json.dumps(metrics)
return json.dumps(metrics)
@dsl.pipeline(name="churn-training", description="Validate, featurize, train")
def pipeline(data_path: str, n_estimators: int = 300, max_depth: int = 8):
check = validate_data(data_path=data_path)
feats = build_features(data_path=data_path)
feats.after(check)
fit = train(features=feats.outputs["features"],
n_estimators=n_estimators, max_depth=max_depth)
fit.after(feats)
if __name__ == "__main__":
kfp.compiler.Compiler().compile(pipeline, "churn_pipeline.yaml")
The step declarations are what the compiler turns into a resumable graph: Input and Output artifacts define what crosses a boundary, and the after calls define ordering that is not implied by data flow. Everything inside a component runs in its own container with pinned package versions, which is what makes "works on my machine" impossible to reintroduce. Logging to your experiment tracker inside the training step means the pipeline inherits reproducibility without extra wiring, because the run identifier is the natural key linking a graph execution to a model version.
Scheduling and sensors: an Airflow DAG
Airflow's strength in ML work is the calendar plus the data dependency. An S3KeySensor waits for the nightly extract instead of failing at 02:00, task groups make the data phase readable, and XCom passes the small values between steps while large artifacts stay in object storage. Note what the example passes between tasks: references and metrics, never megabytes â pushing arrays through the metadata database is the fastest way to make an Airflow cluster fall over.
# airflow_ml_dag.py
from datetime import datetime, timedelta
import pandas as pd
from airflow import DAG
from airflow.operators.python import PythonOperator
from airflow.providers.amazon.aws.sensors.s3 import S3KeySensor
default_args = {
"owner": "ml-platform",
"retries": 3,
"retry_delay": timedelta(minutes=10),
"email_on_failure": True,
"email": ["[email protected]"],
}
def validate_extract(**ctx):
df = pd.read_parquet("s3://warehouse/extracts/latest.parquet")
nulls = float(df.isnull().mean().mean())
if len(df) < 5000 or nulls > 0.15:
raise ValueError(f"rows={len(df)} nulls={nulls:.3f} outside tolerance")
ctx["ti"].xcom_push(key="rows", value=len(df))
return {"rows": len(df)}
def train_model(**ctx):
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
import mlflow
df = pd.read_parquet("s3://warehouse/features/latest.parquet")
X = df.drop(columns=["churned"])
y = df["churned"]
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, stratify=y)
with mlflow.start_run(run_name="airflow-daily"):
model = HistGradientBoostingClassifier(max_depth=8, max_iter=300)
model.fit(X_tr, y_tr)
auc = roc_auc_score(y_te, model.predict_proba(X_te)[:, 1])
mlflow.log_metrics({"auc": auc, "rows": len(df)})
mlflow.log_param("source_run", ctx["run_id"])
if auc < 0.72:
raise ValueError(f"auc {auc:.4f} below release floor 0.72")
ctx["ti"].xcom_push(key="auc", value=auc)
with DAG(
"churn_retraining",
default_args=default_args,
start_date=datetime(2026, 1, 1),
schedule="0 3 * * *",
catchup=False,
max_active_runs=1,
dagrun_timeout=timedelta(hours=2),
) as dag:
wait = S3KeySensor(
task_id="wait_for_extract",
bucket_key="extracts/latest.parquet",
bucket_name="warehouse",
timeout=3600,
poke_interval=60,
mode="reschedule",
)
validate = PythonOperator(task_id="validate", python_callable=validate_extract)
train = PythonOperator(task_id="train", python_callable=train_model)
wait >> validate >> train
Two settings in that DAG are doing real work. max_active_runs=1 prevents yesterday's backfill from training concurrently with today's run and racing for the same output path. mode="reschedule" frees the worker slot while waiting, so a late extract does not occupy a task slot for an hour.
Retries, idempotency, and intermediate state
Retries only help if the stage they retry is safe to repeat. That means every writer targets a unique path per attempt â usually a run identifier â followed by an atomic rename or commit, so a partially written artifact is never visible to the next stage. Object stores make this easy with per-run prefixes; a shared latest.parquet written in place makes it impossible, because a retry after a timeout leaves the downstream task guessing whether the file is complete.
Equal care is needed for what passes between stages. Small scalars and identifiers travel through the orchestrator's task output mechanism; datasets stay in storage with their path recorded. When a stage is expensive, cache it on a hash of its inputs â data version plus code version â so a hyperparameter change reruns training but not the three-hour featurization that preceded it. The reverse error, caching on path alone, is how teams discover that a silently replaced upstream file produced a model trained on stale features.
Surviving long jobs and spot interruptions
Spot capacity can cut training costs by seventy percent, and it will interrupt you â that is the trade, not a bug. Design the job around checkpointing: save model and optimizer state at a fixed interval to durable storage, keep a step counter with it, and treat a preemption signal as a normal shutdown path rather than an error. On restart, resume from the newest complete checkpoint instead of step zero, and record the number of resumes alongside the final metrics so a model trained across nine interruptions is still explainable.
The second safeguard is determinism at the data layer. If the sampler shuffles with a seed derived from the wall clock, a resumed run trains on a different data order and the loss curve jumps for no visible reason. Seed the sampler from the epoch and rank, and resume becomes boring â which is exactly what you want from the mechanism that saves you money.
â ī¸Fail fast at the data boundary
Common Mistakes
Passing large datasets between tasks through the orchestrator
Fix: Move artifacts through object storage and pass only paths and small scalars between steps.
Writing intermediate outputs to a fixed shared path
Fix: Write to a run-unique prefix and publish atomically so retries cannot corrupt downstream state.
Choosing an orchestrator the team cannot operate on call
Fix: Pick the system you can debug at 3 a.m., and migrate once the stage contracts are stable.
Letting backfills run concurrently with scheduled runs
Fix: Cap active runs and separate backfill pools so they cannot race for the same outputs.
Best Practices
- Put validation first and make it raise on contract violations
- Hash inputs to cache expensive steps instead of rerunning them blindly
- Seed every sampler so resumed jobs stay reproducible
- Record checkpoint resumes next to final metrics for auditability
- Keep pipeline definitions in version control and review them like code
Interview Questions
Q1: Kubeflow or Airflow for ML â what decides it?
Whether your heavy steps are container-native GPU jobs or calendar-driven cross-system dependencies, and which one your team can operate during an incident.
Q2: What makes a pipeline stage safe to retry?
Idempotent writes to run-unique paths, an atomic publish step, and no side effects outside declared outputs.
Q3: How do you train on spot instances without losing work?
Periodic checkpoints including optimizer state, resume-from-latest on preemption, and deterministic seeding so resumed runs continue cleanly.
Q4: Why not just cron a training script?
Cron has no dependency graph, no backfill semantics, no per-task retry isolation, and no way to see which stage failed without reading logs.
Key Takeaways
- A pipeline names its artifacts, isolates failures, and makes reruns boring
- Orchestrator choice follows workload shape and on-call capability, not feature lists
- Pass paths and scalars between stages; keep datasets in object storage
- Spot instances are cheap because they interrupt â checkpoint or pay full price
- Validation first, with hard failures, protects every GPU hour downstream