12 minute read

“Cron is not an orchestrator. A script is not a pipeline.”

TL;DR

ML workflows are dependency graphs that cron cannot manage. DAG orchestrators like Airflow and Kubeflow handle task dependencies, retries, backfills, and distributed execution across heterogeneous infrastructure. The KubernetesExecutor scales with the cluster, avoids idle worker cost and isolates tasks from each other. Backfilling turns historical reprocessing into a one-click operation, and task caching via input hashing prevents redundant multi-hour recomputation. For how pipelines feed into model deployment, see Model Serialization and Feature Stores.

A complex model railway switching yard seen from above with trains on parallel tracks being routed through switches t...

1. Problem Statement

Standard software runs via Request -> Response. ML software runs as a Pipeline.

  • Step 1: Ingest Data (Wait for Hive partition).
  • Step 2: Clean Data (Requires Step 1).
  • Step 3: Distributed Training (Requires Step 2, Requires GPU cluster).
  • Step 4: Validation (Requires Step 3).
  • Step 5: Deploy.

The Problem: How do you manage this dependency graph reliably, handling retries, backfills, and distributed execution, without writing spaghetti bash scripts?


2. Understanding the Requirements

2.1 Why cron fails

0 2 * * * train_model.sh.

  1. Dependency Hell: What if the Data Ingest job (scheduled at 1:00 AM) is delayed? train_model.sh runs on empty data.
  2. No State: If Step 3 fails, cron doesn’t know. It won’t retry just Step 3. You have to re-run the whole thing.
  3. No Scaling: cron runs on one machine. We need to run Step 3 on a Kubernetes GPU cluster.

2.2 The Solution: The DAG

We represent the workflow as a Directed Acyclic Graph (DAG).

  • Directed: Data flows A -> B.
  • Acyclic: B cannot feed back into A (infinite loop).
  • Graph: Nodes are tasks, Edges are data/control dependencies.

2.3 What the Scheduler Actually Computes

Every orchestrator reduces to the same core loop: a task is ready when all of its upstream tasks have succeeded, and anything ready can run in parallel. That is a topological sort, and a cycle means no valid order exists. A minimal version:

from collections import deque

def execution_waves(deps):
    """deps: {task: [upstream tasks]} -> list of waves that can run in parallel."""
    indegree = {task: len(ups) for task, ups in deps.items()}
    downstream = {task: [] for task in deps}
    for task, ups in deps.items():
        for up in ups:
            downstream[up].append(task)

    ready = deque(task for task, n in indegree.items() if n == 0)
    waves, done = [], 0
    while ready:
        wave = list(ready)
        ready.clear()
        waves.append(wave)
        for task in wave:
            done += 1
            for nxt in downstream[task]:
                indegree[nxt] -= 1
                if indegree[nxt] == 0:
                    ready.append(nxt)
    if done != len(deps):
        raise ValueError("Cycle detected: not a DAG")
    return waves

pipeline = {
    "ingest": [],
    "clean": ["ingest"],
    "features_text": ["clean"],
    "features_image": ["clean"],
    "train": ["features_text", "features_image"],
    "validate": ["train"],
    "deploy": ["validate"],
}
print(execution_waves(pipeline))
# [['ingest'], ['clean'], ['features_text', 'features_image'], ['train'], ['validate'], ['deploy']]

The two feature tasks land in the same wave, so a scheduler with free workers runs them at the same time. Real schedulers add the parts this sketch skips: persisted task state, retries, time-based triggers, resource limits and backfills.


3. High-Level Architecture

An MLOps Orchestrator (like Airflow or Kubeflow Pipelines) consists of:

[Scheduler (The Brain)]
   |  (Polls DAGs, Checks Time, Checks Dependencies)
   |
   +---> [Queue (Redis/RabbitMQ)]
            |
            v
   [Workers (The Brawn)]
      | Worker 1: [Task A: Data Prep]
      | Worker 2: [Task B: Training (GPU)]
      | Worker 3: [Task C: Evaluation]

Key Components

  1. Metastore (Postgres): “Task B failed at 2:03 PM”.
  2. Executor: “Launch this task on Kubernetes” vs “Launch this task in a local process”. The queue in the diagram belongs to queue-based executors such as Airflow’s CeleryExecutor; the KubernetesExecutor (Section 6.1) launches pods directly instead.

4. Component Deep-Dives

4.1 Airflow (The Scheduler King)

  • Python as Config: You define DAGs in Python code.
  • Operators: SQLExecuteQueryOperator, PythonOperator, BashOperator.
  • Sensors: Special tasks that “wait” for something (e.g., S3KeySensor waits for a file to appear).
  • Data-aware scheduling: Instead of a clock, a DAG can trigger when an upstream DAG updates a dataset (called Datasets in Airflow 2.4+, Assets in Airflow 3). This removes the “ingest ran late, training ran on nothing” failure from Section 2.1.
  • Best For: Data Engineering, Scheduled jobs.

4.2 Kubeflow Pipelines (The ML Specialist)

  • Container Native: Every task is a Docker container.
  • Artifact Tracking: Automatically logs “Task A produced dataset.csv (hash: xyz)”.
  • Best For: Deep Learning workflows where reproducibility (Docker) is critical.

4.3 Choosing an Orchestrator

Tool How Pipelines Are Defined Strengths Watch Out For
Airflow Python DAG files Scheduling, backfills, huge operator ecosystem Passing large data between tasks; DAG parse overhead
Kubeflow Pipelines Python SDK compiled to a pipeline spec, one container per step Artifact lineage, caching, Kubernetes-native Needs a Kubernetes platform team
Argo Workflows Kubernetes YAML, one pod per step Simple, general-purpose, fast fan-out No Python-level typing or data passing
Flyte Typed Python tasks and workflows Strong typing, versioning, caching Heavier platform to operate
Prefect Plain Python functions, graph built as the flow runs Dynamic flows, low ceremony Less built-in backfill tooling
Dagster Software-defined data assets Asset lineage and freshness tracking Asset-centric model is a mindset shift

For a deeper look at dependency patterns, retries and idempotent tasks in Airflow, Kubeflow and Metaflow, see ML pipeline dependencies and orchestration.


5. Data Flow: The Backfill

A unique feature of Orchestrators is Backfilling. Imagine you change your Feature Engineering logic today. You want to re-train the model on data from the past year using the new logic.

With cron, this is a nightmare. With Airflow:

  1. Clear the state of “FeatureEng Task” for dates=[ ... ] (or, in Airflow 3, create a backfill for the date range).
  2. The Scheduler sees these tasks as “Null state”.
  3. Since they have no dependencies blocking them (historical data exists), it schedules them all in parallel (up to max_active_runs).

This turns “Historical Reprocessing” into a one-click operation, provided every task is idempotent: it writes to a partition keyed by the run’s logical date and replaces that partition, so a re-run overwrites instead of duplicating.


6. Scaling Strategies

6.1 The Kubernetes Executor

Instead of having a fixed pool of workers (which sit idle or get overwhelmed), use the KubernetesExecutor.

  • Scheduler: “Task A needs to run.”
  • K8s: Spin up a Pod just for Task A.
  • Task A: Runs.
  • K8s: Kill Pod. Pros: Scales with the cluster. No idle worker cost (the scheduler and metadata database still run). Perfect isolation (Task A uses PyTorch 1.9, Task B uses PyTorch 2.0). Cons: Pod startup adds seconds to every task, which hurts DAGs made of many tiny tasks.

6.2 Caching (Memoization)

If Task A takes 5 hours to generate clean_data.csv, and Task B fails… When we retry, we don’t want to re-run Task A. Kubeflow natively checks inputs. If Hash(Inputs, Code) matches a previous run, it reuses the cached output.

6.3 Waiting Without Burning Slots

A sensor that polls for six hours in the default “poke” mode holds a worker slot the whole time. Run sensors in mode="reschedule" (the task frees its slot between checks) or use deferrable operators, which hand the wait to Airflow’s lightweight triggerer process.


7. Implementation: Defining a DAG (Airflow)

from airflow import DAG
from airflow.operators.python import PythonOperator
from airflow.providers.amazon.aws.sensors.s3 import S3KeySensor
from datetime import datetime

def train_model(**context):
    # ML Logic here
    print("Training...")

with DAG("ml_pipeline_v1", 
         start_date=datetime(2023, 1, 1), 
         schedule="@daily",
         catchup=False) as dag:

    # 1. Wait for data to arrive in S3 (reschedule mode frees the worker slot between checks)
    wait_for_data = S3KeySensor(
        task_id="wait_for_input",
        bucket_key="s3://data/incoming//data.csv",
        mode="reschedule",
        poke_interval=300,
    )

    # 2. Train logic
    train = PythonOperator(
        task_id="train_model",
        python_callable=train_model
    )

    # 3. Dependency Definition
    wait_for_data >> train

These are Airflow 2 import paths; Airflow 3 moves DAG to airflow.sdk and PythonOperator into the standard provider.

Test the DAGs in CI, before the scheduler ever sees them:

from airflow.models import DagBag

def test_dags_import_cleanly():
    dagbag = DagBag(include_examples=False)
    assert not dagbag.import_errors, dagbag.import_errors

def test_training_waits_for_data():
    dag = DagBag(include_examples=False).get_dag("ml_pipeline_v1")
    assert dag.get_task("train_model").upstream_task_ids == {"wait_for_input"}

8. Monitoring & Metrics

  1. DAG Parse Time: If your Python DAG file is slow to parse (e.g., connects to DB at top level), the Scheduler hangs. Anti-pattern!
  2. Task Latency: Track Input_Size vs Duration. If data grew 2x but time grew 10x, you have a non-linear scaling bug.
  3. Data Freshness SLA: Alert when the newest successful partition of a key output is older than expected, which catches silent failures that per-task alerts miss.

9. Failure Modes

  1. Thundering Herd: You backfill 1 year of data. 365 jobs launch instantly. Your Database crashes.
    • Fix: Cap parallelism with max_active_runs and max_active_tasks on the DAG, and put database-heavy tasks in an Airflow pool with a fixed number of slots.
  2. Deadlock: Task A waits for Task B. Task B waits for connection slot held by Task A.
    • Fix: Size pools so waiting tasks cannot hold every slot, and never hold a connection while waiting on another task.
  3. Zombies: The Scheduler thinks Task A is running. Task A’s pod died OOM. The state stays “Running” forever.
    • Fix: Frequent “Heartbeat” checks by the Scheduler, which marks tasks without a recent heartbeat as failed so retries can kick in.

10. Real-World Case Study: Lyft Flyte

Lyft built Flyte (open-sourced in 2020), and strict typing between tasks is one of its core design goals. Flyte enforces Type Safety between tasks.

  • Task A output: dataframe_schema[age: int]
  • Task B input: dataframe_schema[age: String]
  • Flyte catches this mismatch when the workflow is compiled and registered, preventing runtime failures 5 hours into the pipeline.

11. Cost Analysis

  • Spot Instances: Since ML pipelines are fault-tolerant (auto-retry), use Spot Instances for the Heavy Workers. AWS advertises discounts of up to 90% versus on-demand; checkpoint long training tasks so an interruption costs minutes, not hours.
  • Idle Clusters: Using K8s Executor prevents paying for idle workers at night.
  • Caching: Every cache hit on a multi-hour upstream task is compute you don’t pay for twice.

12. Key Takeaways

  1. Dependency Management: This is the core value prop. “Run B only after A succeeds.”
  2. Idempotency: Every task must be idempotent. If run twice, it should produce the same result (or overwrite safely).
  3. Infrastructure as Code: The Pipeline is code. Version control your DAGs, and test them in CI.
  4. Static vs Dynamic: Airflow DAGs are defined upfront (with dynamic task mapping for runtime fan-out since Airflow 2.3). Prefect builds the graph as the flow runs.
  5. Trigger on Data, Not Clocks: Data-aware scheduling removes a whole class of “upstream was late” failures.

FAQ

Why can’t cron handle ML pipelines?

Cron has no dependency awareness, no state tracking for retries, and no ability to scale across distributed infrastructure. If an upstream data job is delayed, cron will run training on empty data without knowing anything went wrong, and if a step fails, you must manually re-run the entire pipeline instead of just the failed task.

What is backfilling in ML pipeline orchestration?

Backfilling is the ability to re-run pipeline tasks for historical dates when logic changes. With Airflow, you clear the task states for a date range, the scheduler sees them as unresolved, and since historical data already exists, it schedules them all in parallel up to the concurrency limit, turning a nightmare into a one-click operation.

How does the KubernetesExecutor improve ML pipeline scalability?

Instead of maintaining a fixed worker pool that either sits idle or gets overwhelmed, the KubernetesExecutor spins up a dedicated pod for each task and kills it after completion. This scales with the cluster, avoids paying for idle workers, and isolates dependencies so Task A can use PyTorch 1.9 while Task B uses PyTorch 2.0.

What are common failure modes in DAG pipeline orchestration?

The main failures are thundering herd from uncapped parallel backfills that crash your database, deadlocks from circular resource dependencies between tasks, and zombie tasks where the scheduler thinks a task is running but its pod has died from out-of-memory errors. Fixes include concurrency limits, heartbeat checks, and explicit resource management.