Sub topic 16
Orchestrating the pipeline
This chapter assumes you know the basic ML workflow (train, validate, test, deploy), can read Python, and have used CI/CD. It covers how the stages of a retraining pipeline are wired together and run reliably once a trigger fires. The trigger policy decides whether to retrain. Orchestration decides how the run executes, in what order, and what happens when a step fails.
What an orchestrator does
An orchestrator is a system that runs a set of tasks in a defined order, passes data between them, retries failures, and records what happened. A retraining pipeline needs these things because its stages depend on each other and fail in different ways:
- Data validation must finish before training starts.
- Training is long and expensive, and it may be killed by a spot instance reclaim or an out-of-memory error.
- Evaluation needs both the challenger and the current champion.
- Registration and rollout must happen at most once per run, even if a step is retried.
You can run all of this in one script. That works for a first version. It stops working when you need partial reruns, per-step retries, scheduling, or an audit trail of who ran what.
Modeling the pipeline as a DAG
Most orchestrators describe a pipeline as a directed acyclic graph (DAG). Each node is a task. Each edge says "this task needs the output of that task". "Acyclic" means no task can depend on itself, directly or indirectly, so the graph always has a valid run order.
Two properties of this graph matter in practice.
- Branches that end the run are normal outcomes. A failed validation or a failed gate is not an error in the orchestrator's sense. The pipeline did its job by refusing to ship. Model these as explicit "skipped" or "stopped" states so that dashboards do not show them as crashes.
- Tasks that touch the outside world sit at the end. Registration and rollout change shared state. Keeping them after every check means a failed run leaves nothing behind except logs and artifacts.
Idempotency and passing data between tasks
A task is idempotent if running it twice with the same inputs gives the same result and no extra side effects. Retries are only safe for idempotent tasks. Three habits make tasks idempotent:
- Pin inputs by reference, not by "latest". The extract step writes a snapshot with a fixed identifier, such as a date range plus a query hash. Later tasks read that identifier. If training retries three hours later, it still sees the same data.
- Write outputs to a path derived from the run ID. A retry overwrites its own output instead of creating a second copy.
- Make registration conditional. Register under a key made from the run ID. If the key already exists, the second attempt does nothing.
Pass small values (identifiers, metrics, paths) between tasks through the orchestrator. Pass large objects (datasets, model files) through object storage and hand over only the location. Putting a 2 GB dataframe into the orchestrator's metadata store is a common cause of slow or crashing schedulers.
Triggering the DAG
The trigger policy from earlier chapters sits in front of the DAG. There are two common ways to connect them.
| Approach | How it works | Strength | Weakness |
|---|---|---|---|
| Orchestrator-native schedule | The orchestrator wakes up on a cron schedule and runs a first task that evaluates the policy. If the answer is "no", the run ends immediately. | One system holds both the check and the retraining. Every check is logged. | Many near-empty runs clutter the run history. |
| External event | A monitoring job evaluates drift and calls the orchestrator's API only when it should retrain. | Pipeline runs equal retraining decisions. | Two systems must agree on configuration and identities. |
The first approach is easier to reason about. Make the policy check the first task of the DAG and record its reason string (for example drift_with_enough_data) as run metadata. Months later, someone will ask why a model was retrained, and the answer should be in the run record.
A minimal scheduled and manual trigger in GitHub Actions looks like this:
name: retrain
on:
schedule:
- cron: "0 3 * * 1"
workflow_dispatch: {}
jobs:
retrain:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: python -m pip install -r requirements.txt
- run: python train_pipeline.pyThis is enough for a small pipeline. It lacks per-task retries, resumable runs, and long-running training on specialized hardware. Dedicated orchestrators such as Airflow, Dagster, Prefect, Kubeflow Pipelines, or a managed cloud service add these. The concepts below apply to all of them.
Writing the DAG as code
The following example uses plain Python to show the structure without depending on a specific orchestrator. It runs tasks in order, records a status for each, stops at the first stopping outcome, and retries transient failures.
import time
from dataclasses import dataclass, field
class StopRun(Exception):
"""A planned early exit, such as a failed gate. Not a crash."""
@dataclass
class RunContext:
run_id: str
values: dict = field(default_factory=dict)
status: dict = field(default_factory=dict)
def run_task(ctx, name, fn, retries=2, delay=0.1):
for attempt in range(retries + 1):
try:
ctx.values[name] = fn(ctx)
ctx.status[name] = "success"
return
except StopRun as exc:
ctx.status[name] = f"stopped: {exc}"
raise
except Exception as exc:
if attempt == retries:
ctx.status[name] = f"failed: {exc}"
raise
time.sleep(delay * 2 ** attempt)
def validate(ctx):
return {"rows": 120_000, "ok": True}
def train(ctx):
return {"auc": 0.903}
def gate(ctx):
if ctx.values["train"]["auc"] < 0.905:
raise StopRun("regression")
return True
ctx = RunContext(run_id="2026-11-30-001")
try:
for name, fn in [("validate", validate), ("train", train), ("gate", gate)]:
run_task(ctx, name, fn)
except StopRun:
pass
print(ctx.status)The output shows validate and train as success and gate as stopped: regression. The key design choice is the separate StopRun exception. Retrying a regression is pointless, so planned exits skip the retry loop. Real orchestrators offer the same split as "skip" or "short-circuit" states versus "failed" states.
Failure handling
Decide per task what should happen when it fails.
- Retry with backoff for transient problems: network errors, throttled APIs, preempted machines. Use exponential backoff and a small cap on attempts. Never retry a task that is not idempotent.
- Timeouts on every task. A hung training job can hold a GPU for days. Set a limit based on the normal duration plus a margin.
- Fail the run and alert for validation errors, schema changes, and missing data. Retrying will not fix these.
- Checkpoints for long training. Save intermediate model state to storage so a retry resumes instead of starting over.
- Cleanup tasks that run even after failure, to release clusters and delete temporary tables.
Concurrency and backfills
Two runs of the same pipeline should not overlap. Overlap causes two challengers to compete for promotion and doubles compute cost. Configure the orchestrator for a maximum of one active run per pipeline, and decide what happens to a trigger that arrives during a run: queue it, or drop it because the running job will see the same data.
Orchestrators also support backfills, which replay a pipeline for past dates. For retraining this is useful for reproducing a historical model, and risky for anything that deploys. Make the deployment tasks check a parameter such as deploy=false so a backfill cannot touch production.
Common errors
- Reading "latest" data in each task, so tasks in one run see different datasets.
- Putting the policy check outside the orchestrator, so no record explains why a run started.
- Treating a failed gate as a crash, which trains operators to ignore alerts.
- Letting retries repeat non-idempotent steps.
- No timeout on training, so one stuck job blocks all later runs.
- Hard-coding secrets and environment settings in the DAG instead of reading them from the orchestrator's secret store.
Exercise
A training task times out after two hours and the orchestrator retries it. The registration task, which runs later, creates a new model version each time it is called. Describe two changes that make the pipeline safe to retry, and say why a failed evaluation gate should not be retried.
Show answer
First, make registration idempotent by using the run ID as a key, so a second call finds the existing entry and does nothing. Second, pin the training input to the snapshot ID written by the extract task, and write outputs to a run-specific path, so a retry sees the same data and overwrites its own output. A failed gate reflects the challenger's measured quality on fixed data. Running it again gives the same result, so a retry wastes compute. It should end the run as a planned stop with an alert or log entry.
Exercise
Your team schedules the orchestrator to run the pipeline daily, and the first task evaluates the trigger policy. Most runs end immediately with reason "no_trigger". Name one benefit and one cost of this design.
Show answer
Benefit: every policy decision is logged in one place with its reason, which makes later audits easy. Cost: the run history fills with near-empty runs, which can hide real runs and make dashboards noisy. Filtering or tagging runs by outcome reduces the cost.