EPRM-L04: Deployment Patterns

In short

A trained model earns nothing until something uses its predictions, so how do you get them to whoever needs them? There are four ways: batch (a workflow that starts on a trigger, runs and exits), API (a service that is always up and answers requests), streaming (a system that reacts to every message on a stream) and edge (the model runs on the user’s device). The course works with the two most common. A batch workflow is a DAG of tasks, which the course runs with Airflow: each task is a container, arrows say what waits for what, and a schedule or event starts it. An API is a set of HTTP endpoints, such as /predict and /health, which the course builds with Flask. Between the two sits a quiet danger: serving has to turn inputs into features exactly as training did, with the statistics saved at training time, or predictions go wrong without any error.

There is no written exam: this feeds Assignment 4 (scheduling the training DAG, reloading the API’s model from the DAG, passing a new feature’s state from training to the API) and the course project, which starts after this week.

A model has to reach someone

Week 1 opened with the finding that most ML projects never deliver value, often because the model is never deployed: without production deployment there is no economic value. Week 3 showed how to package code in a Docker container so it runs the same everywhere. This week answers the next question: once the model is packaged, in what shape does it serve predictions?

The lecturer, Kemal Yesilbek, points out that the answer, like the rest of MLOps, comes from backend engineering. Ordinary software already had to decide whether work runs as a nightly job, as a web service, or on the user’s phone. An ML model is one more piece of software making that choice.

Four ways to serve a model

The four ways to serve or deploy an ML/AI system

  • Batch: predefined processes that start and stop. They run and exit.
  • API: a way to let other systems interact with yours. It is always up.
  • Streaming: uses a message bus. The system listens to one or more message streams and acts on them.
  • Edge: the model is deployed directly on a device.

A message bus is a shared channel (Kafka is a common one, from outside the course material) where producers publish events, such as “payment made”, and any number of consumers read them as they arrive.

The difference that matters most is who starts the work, and when:

BatchAPIStreamingEdge
Starts ona triggera requesta messagethe app
Lifetimeruns, exitsalways upalways listeningon the device
Predictions areprecomputedfresh per requestfresh per eventlocal, offline
Examplenightly scores for all users/predict for a web shopfraud check per paymenttext recognition on a phone

The consequences follow from the first row. Batch computes predictions ahead of time for everything that exists when it runs. That is cheap and simple, and nobody waits for the model, but a user who signs up at noon has no prediction until the next run. An API computes a prediction when asked, so it is always fresh, but it must stay up and answer fast. Streaming reacts to events without anyone asking. Edge removes the network: the device needs no connection and the data never leaves it, but the model has to fit the device, and updating it means updating every device.

The course looks only at batch and APIs, the most common two. The reading by Christian Kästner (see EPRM-Book Ch10 - Deploying a Model) cuts the space slightly differently: the model as a library inside an application (which covers edge), the model as a service (the API), batch processing, and cached predictions, where every prediction is computed ahead of time and serving is a lookup in a table. His point about choosing: the decision follows from the system’s requirements (latency, offline use, privacy, cost, how often the model changes), and hybrids are common. See ML Deployment Patterns.

Batch: a workflow that starts and stops

A batch process (also called a workflow, pipeline or process) has three parts:

  • it starts and stops: it runs to completion and exits;
  • it is composed of tasks, each a unit of execution (one script, one container run);
  • it begins when a trigger fires.

The trigger can be many things, or several at once:

  • a schedule: every night at 02:30, every Monday;
  • a file arrival: a new export lands in a storage bucket;
  • CDC (change data capture): a change in a source database, such as new or updated rows, is detected (usually by reading the database’s change log, from outside the course material) and starts the workflow.

Written out as a template, every batch workflow says:

When trigger happens, start the workflow name, which starts task A; when A finishes, starts tasks B and C; when B and C finish, starts task D. If the workflow fails, do action.

flowchart LR
    T[Trigger] --> A((A))
    A --> B((B))
    A --> C((C))
    B --> D((D))
    C --> D
    F[Action on fail]

The action on failure is part of the definition: alert someone, retry, or clean up partial output.

The structure is a DAG

DAG

The structure of the tasks is called a DAG, a directed acyclic graph: tasks are nodes, and an arrow from A to B means B starts only after A finishes. Directed because the arrows have a direction; acyclic because no path leads back to where it started.

The lecturer warns that the name is easy to confuse with the data structure, and Airflow’s documentation now writes “Dag” for the workflow for that reason. Two properties of the graph do the work:

  • No cycles, so it can finish. If D also had to finish before A, then A would wait on D, which waits on B, which waits on A: nothing could ever start.
  • Independent branches run in parallel. B and C both depend only on A, so once A is done they can run at the same time. D waits for both.

Splitting a job into tasks is also the recovery design from week 2: when each task saves its output and the next one reads it, a crash means rerunning one task instead of the whole multi-day job. The DAG is where that split becomes explicit.

Airflow: the course’s batch orchestrator

Apache Airflow is an open-source tool that runs DAGs: it reads DAG definitions written in Python, starts each task when its upstream tasks have succeeded, starts the whole DAG when its schedule or trigger fires, and shows every run and task in a web interface.

The course’s training pipeline is one DAG, nova_training:

flowchart TD
    S["log_datetime_start (Bash)"] --> P["preprocessing (Docker)"]
    P --> FE["feature_engineering (Docker)"]
    P --> CH["Chatter (Bash)"]
    FE --> TR["training (Docker)"]
    CH --> TR
    TR --> E["log_datetime_end (Bash)"]

Two of the tasks are part of it:

model_training_task = DockerOperator(
    docker_url="unix://var/run/docker.sock",
    command="python src/main_training.py --training",
    image="nova:latest",
    network_mode="infra_default",
    task_id="training",
    mounts=[Mount(source="data", target="/nova/data")],
    dag=dag,
)
 
log_datetime_end_task = BashOperator(
    task_id="log_datetime_end",
    bash_command="echo date",
    dag=dag,
)
 
(
    log_datetime_start_task
    >> preprocessing_task
    >> [feat_eng_task, completely_unnecessary_task_to_display_parallelism]
    >> model_training_task
    >> log_datetime_end_task
)

How to read it:

  • An operator is a kind of task. BashOperator runs a shell command. DockerOperator starts a container from an image and runs a command in it. The three real stages (preprocessing, feature engineering, training) are the same image, nova:latest, run with a different flag to main_training.py each time. The Bash tasks only print the time. Chatter, which the code honestly names completely_unnecessary_task_to_display_parallelism, exists to show two tasks running side by side.
  • >> is “then”. a >> b means b runs after a. A list fans out (preprocessing >> [feat_eng, chatter]: both start when preprocessing is done) and fans in ([feat_eng, chatter] >> training: training waits for both).
  • The DockerOperator’s settings (explained from outside the course material, Docker and Airflow documentation). docker_url points at the Docker daemon’s socket, so Airflow asks the host’s Docker to start each task as a new container next to the others. network_mode="infra_default" attaches that container to the network Docker Compose created for the infra/ project, so it can reach the MLflow server by its service name, as in week 3. Mount(source="data", ...) attaches a named Docker volume called data at /nova/data: every task container sees the same volume, which is how the feature engineering task reads what preprocessing wrote.

Each stage being a separate container run that hands files to the next is the week 2 recovery design in practice: if training crashes, the preprocessed data and features are still on the volume.

Making a DAG run on its own

The DAG in the course code has no schedule, so it only runs when someone presses the trigger button. Scheduling it is the first part of Assignment 4. What follows is from outside the course material (Airflow documentation, for Airflow 3, the version the course uses):

import pendulum
from airflow.sdk import DAG
 
with DAG(
    dag_id="my_pipeline",
    schedule="30 2 * * *",
    start_date=pendulum.datetime(2026, 11, 1, tz="Europe/Amsterdam"),
    catchup=False,
    default_args={"retries": 1},
) as dag:
    ...
  • schedule takes a cron expression, five fields: minute hour day-of-month month day-of-week. 30 2 * * * is minute 30, hour 2, every day of every month, any weekday: daily at 02:30. 0 * * * * is hourly, 0 9 * * 1 is Mondays at 09:00. Presets such as "@daily" (midnight) also work, and None means manual runs only.
  • start_date is the earliest moment a scheduled run may happen. Airflow needs it to know where the schedule begins.
  • Time zone. Airflow works in UTC by default, so a cron time without a time zone means UTC. A start_date built with pendulum and tz="Europe/Amsterdam" makes the cron times Amsterdam times, daylight saving included.
  • catchup. If start_date lies in the past, Airflow could create a run for every missed slot since then. In Airflow 3 the default is not to (catchup=False): it runs only the most recent slot and continues from there.
  • New DAGs start paused. Airflow’s default configuration creates every new DAG in the paused state, and a paused DAG is never scheduled until someone switches it on in the interface (or the DAG is created with is_paused_upon_creation=False).
  • The action on fail. retries reruns a failed task; on_failure_callback on the DAG runs a function when a run fails, such as sending an alert.
  • Removing a task means deleting its operator and its place in the >> chain. Leaving the operator defined but unconnected still adds it to the DAG as a task with no dependencies.

APIs: a service that is always up

API, as the course puts it

A service that is always up and ready to receive requests. Upon a request, with or without input, it runs a specific process (an endpoint) and returns a result, with or without data. HTTP APIs are the most common.

Batch pushes predictions out on its own schedule. An API waits for others to pull a prediction when they need one, which makes it the pattern for anything interactive. See HTTP API.

What goes over the wire

Every HTTP API call is a request from a client (a browser, curl, another service) to a server, and a response back:

The client sendsThe server returns
HTTP method: GET, POST, PUT, DELETEStatus code: 200, 500, …
URL / endpoint: /predict, /score, /health, /orderResponse data: JSON, HTML
Params (optional): ?<param>=<val> in the URL
Body / payload (optional): the data

Three examples make it concrete:

  • Fetching data with GET. Opening dog.ceo/api/breeds/list/all in a browser sends a GET to the endpoint /api/breeds/list/all with no parameters and no body. The response is JSON: a message object mapping each breed to its sub-breeds ("australian": ["kelpie", "shepherd"], "beagle": []).
  • Parameters in the URL. google.com/search?q=hello+world&hl=en is a GET to /search with two parameters: q (the query, with + standing for a space) and hl (interface language). The response is an HTML page.
  • A body with POST. The colour palette service Colormind has two endpoints. curl 'http://colormind.io/list/' (a GET) returns the available models as JSON. Then curl 'http://colormind.io/api/' --data-binary '{"input":[[44,43,44],[90,83,82],"N","N","N"],"model":"default"}' sends a POST (curl switches to POST when given data) whose body fixes two colours and marks three free slots with "N". The response is a full five-colour palette that keeps the given two (nearly unchanged) and fills the rest: a model prediction behind an API.

The methods (from outside the course material): GET fetches something and carries its inputs in the URL; POST sends a body for the server to process; PUT creates or replaces the thing at a URL; DELETE removes it. A prediction request with a feature vector is usually a POST with a JSON body.

Status codes group by their first digit: 2xx means success (200 OK), 4xx means the client got something wrong (400 bad request, 404 not found, 405 method not allowed), 5xx means the server failed (500 internal server error, 503 service unavailable). The course names 200 and 500, the two you see most.

A /health endpoint answers “are you up?” with a cheap 200. It is what a Docker Compose health check from week 3 can call before dependent services start, and what an orchestrator polls to restart a dead service.

A model behind an API with Flask

The course’s API is written in Flask, a small Python web framework; its quickstart is a reading for the week. The sketch below is from that reading and from Kästner’s chapter, and the course code follows the same shape, with /health and a POST /predict.

import pickle
from flask import Flask, request
 
app = Flask(__name__)
 
with open("models/model.pkl", "rb") as f:
    model = pickle.load(f)          # loaded once, when the process starts
 
@app.route("/health")               # GET only, by default
def health():
    return {"status": "ok"}          # a dict is returned as JSON, status 200
 
@app.route("/predict", methods=["POST"])
def predict():
    payload = request.get_json(silent=True)   # the JSON body, None if invalid
    if payload is None or "features" not in payload:
        return {"error": "send JSON with 'features'"}, 400
    y = model.predict([payload["features"]])
    return {"prediction": y.tolist()}
flask --app app run --host 0.0.0.0 --port 5001
curl http://localhost:5001/health
curl -X POST http://localhost:5001/predict \
     -H "Content-Type: application/json" -d '{"features": [120.5, 3, 0]}'

What to notice:

  • @app.route binds a URL to a function. By default a route answers only GET; methods=["POST"] (or the shortcut @app.post) changes that, and a request with another method gets 405.
  • Return values become responses. A string becomes an HTML response, a dict or list becomes JSON, and a tuple (body, status) sets the status code. An unhandled exception in the function becomes a 500.
  • request.get_json() reads a JSON body, request.args the URL parameters. The client has to send the header Content-Type: application/json; without it, or with broken JSON, plain get_json() aborts the request with a 4xx error, while silent=True returns None so the view can send its own 400.
  • --host 0.0.0.0. By default the development server listens only on 127.0.0.1, which inside a container is the container itself (the week 3 pitfall).
  • The model is loaded once, at start-up, and every request reuses it. Loading a pickle per request would make every prediction slow.
  • Development server only. flask run is meant for development; the Flask docs warn against using it, and especially its debug mode, in production, where a WSGI server such as gunicorn runs the app (Kästner’s Dockerfile does this).
  • Testing (from outside the course material, Flask testing docs): app.test_client() sends fake requests without a running server, so endpoints can be unit-tested like functions: client.post("/predict", json={...}) returns a response whose status_code and get_json() you assert on.

Same features in training and serving

The model was trained on features, and an API receives raw inputs: a transaction with an amount and a category, never a z-scored amount and a one-hot vector. So the API must run the same feature encoding as training. Kästner calls the failure training-serving skew: when the encoding at inference differs from the one at training, runtime data no longer matches the training data, and predictions are wrong while nothing crashes. The mismatch can be one feature scaled differently or completely scrambled inputs.

Some encodings depend on numbers learned from the training data. A z-score needs the training mean and standard deviation; an index or one-hot encoding needs the list of categories seen in training; a “how common is this category” feature needs the training counts. Call these numbers the feature state. Serving has to use exactly that state:

  • Never recompute it from the request. One request has one row: its mean is itself and its standard deviation is undefined. Even a batch of requests has different statistics from the training set, so the same raw value would map to a different feature.
  • Save it with the model. Log the state as artifacts of the same MLflow run as the model, so a model and its state always travel together and cannot be mixed up across versions.
  • Write the encoding once. One function, imported by both the training code and the API (Kästner’s advice), so the two cannot drift apart.

From outside the course material (MLflow documentation), a minimal version of all three:

# src/features.py: imported by training AND by the API
def fit_state(train_df):                        # training only
    return {"amount_mean": float(train_df["amount"].mean()),
            "amount_std": float(train_df["amount"].std())}
 
def encode(df, state):                          # training and serving
    out = df.copy()
    out["amount_z"] = (out["amount"] - state["amount_mean"]) / state["amount_std"]
    return out
 
# training
with mlflow.start_run() as run:
    state = fit_state(train_df)
    mlflow.log_dict(state, "feature_state.json")
    model.fit(encode(train_df, state)[FEATURES], train_df["fraud"])
    ...                                         # log the model in the same run
 
# API start-up
state = mlflow.artifacts.load_dict(f"runs:/{run_id}/feature_state.json")

In large organisations a Feature Store takes this further: a central catalogue of feature code that can also precompute and cache feature values for many models.

Getting a new model into a running API

The Flask app loads its model once, when it starts. That is what makes it fast, and it has a consequence: retraining does not change what the API serves. A nightly DAG can log a better model to MLflow every night while the API keeps answering with the model it loaded weeks ago, until the process restarts.

Two ways out (the second is part two of Assignment 4):

  • Restart or redeploy the service after training. Simple, but the API is briefly down unless several instances are restarted one at a time.
  • Hot reload: the API gets an endpoint that makes it load the latest model, with its feature state, while it keeps running. The training DAG then ends with one more task that calls that endpoint once training has succeeded. Scheduling, training, logging and serving become one automatic loop: the schedule starts the DAG, training logs a new run to MLflow, and the last task tells the API to pick it up.

Design points for a reload (from outside the course material):

  • Load fully, then swap. Build the new model and state in memory first, and replace the old ones only when loading succeeded. If loading fails, the old model keeps serving and the reload returns an error status.
  • Swap model and state together, both from the same MLflow run, or the API briefly encodes with one run’s statistics and predicts with another run’s model: training-serving skew by timing.
  • Cached loaders keep the old model. If the model sits in a module-level variable or behind a memoising cache such as functools.cache, it stays there until that variable is replaced or the cache is cleared.
  • Reload changes state, so it is a POST, and in a real system it is not open to the public.

Finding “the latest model” in MLflow, from outside the course material (MLflow documentation):

import pickle
import mlflow
 
runs = mlflow.search_runs(
    experiment_names=["Alpha"],
    filter_string="attributes.status = 'FINISHED'",   # skip runs still training
    order_by=["attributes.start_time DESC"],
    max_results=1,
)
run_id = runs.iloc[0]["run_id"]
path = mlflow.artifacts.download_artifacts(run_id=run_id, artifact_path="alpha.pkl")
with open(path, "rb") as f:
    model = pickle.load(f)

What to be able to do

  • Name the four ways to serve a model, say who starts the work in each, and pick one for a scenario.
  • Describe a batch workflow: triggers (schedule, file arrival, CDC), tasks, the DAG, the action on failure, and why the graph must be acyclic.
  • Read an Airflow DAG: operators, >> with lists, which tasks run in parallel, and how DockerOperator tasks share data and reach other services.
  • Give a DAG a schedule with a cron expression, and know what start_date, the time zone, catchup and paused DAGs do.
  • Take an HTTP request and response apart: method, endpoint, parameters, body, status code, response data.
  • Build a Flask API with /health and a POST /predict, load the model once, return the right status codes, and test it.
  • Explain training-serving skew, and pass feature state from training to serving through MLflow.
  • Explain why a retrained model does not reach a running API, and how a reload triggered by the training DAG fixes it.

Exam questions

Flashcards

mean?

b and c both start after a, and can run in parallel.