Sub topic 1
From trained model to served predictions
A trained model does nothing until something runs it on new data. This chapter defines inference, explains what "serving" a model means, and sets up the two delivery patterns the rest of the tutorial compares: batch and real time.
Prerequisites
This chapter assumes you already know the following:
- Basic machine learning vocabulary: training, model, features, and prediction.
- Python at a level where you can read short scripts that use pandas and scikit-learn.
- The basic idea of an HTTP API (a client sends a request and gets a response) and of a scheduled job (a program that runs at set times).
You do not need to know any serving framework. The examples use joblib, pandas, and FastAPI, and each is explained where it appears.
Training and inference are different jobs
Machine learning work has two phases that run under very different conditions.
- Training fits a model's parameters to historical data. It is expensive, runs occasionally, and can take hours. Nobody is waiting on a single result.
- Inference applies the fitted model to new inputs to produce predictions. It runs many times, often for years, and the output feeds a product or a business process.
A prediction is the output of one inference call. A score is a prediction expressed as a number, such as a churn probability between 0 and 1. The running example in this tutorial is a churn model. It predicts how likely a customer is to cancel, using three features: tenure_months, monthly_spend, and support_tickets.
The two phases differ in what they optimize for.
| Aspect | Training | Inference |
|---|---|---|
| Frequency | Occasional (daily to quarterly) | Continuous or very frequent |
| Input | Large labeled historical dataset | New records, usually unlabeled |
| Main cost driver | Long compute runs | Volume of predictions over time |
| Who waits | Nobody directly | Sometimes a user, sometimes a downstream job |
| Failure impact | A retry or delayed model release | Wrong or missing predictions in production |
Because inference is where the model touches the business, most of the operational difficulty lives there.
What "serving a model" means
Serving is everything that gets a trained model's predictions to the systems and people that use them. It has four parts.
- The artifact. The model saved to disk, for example a
model.joblibfile. The artifact must be versioned, so you know which model produced which score. - The runtime. The process that loads the artifact and calls its predict function. It needs the same library versions that were used to train and save the model.
- The inputs. The feature values the model expects, in the same columns, order, and units as in training.
- The delivery path. How requests reach the runtime and how predictions get back: a file written to storage, a database table, or an HTTP response.
Parts 1 and 2 are mostly packaging problems. Parts 3 and 4 are design decisions, and those decisions are the subject of this tutorial.
The core question: when is the prediction computed?
Every serving design answers one question: when does the model run relative to the moment someone needs the answer?
- In batch prediction, the model runs ahead of time, on a schedule, over many records at once. The results are stored. When someone needs an answer, they look it up.
- In real-time prediction, also called online prediction, the model runs at the moment of the request, for one record (or a few). The caller waits for the answer.
The timing decision drives almost everything else: how fresh the inputs can be, how fast the response must be, what infrastructure you pay for, and what can go wrong.
Batch prediction in practice
A batch job loads the model, reads a whole table of records, scores them in one pass, and writes the results where other systems can read them later.
import joblib
import pandas as pd
model = joblib.load("model.joblib")
customers = pd.read_parquet("customers_2026-11-28.parquet")
feature_columns = ["tenure_months", "monthly_spend", "support_tickets"]
customers["churn_score"] = model.predict_proba(customers[feature_columns])[:, 1]
customers[["customer_id", "churn_score"]].to_parquet("scores_2026-11-28.parquet")Points to notice in this script:
predict_probareturns one row per customer and one column per class. The slice[:, 1]selects the probability of the positive class (churn).- The model scores the whole DataFrame in a single vectorized call. This is much faster than looping over rows.
- The output file name carries the date. Scores are a snapshot of one moment, and the name says which one.
- Selecting
feature_columnsby name makes the column order explicit. The columns reach the model in the order of that list, which must match training.
Nobody waits for this job. If it takes 20 minutes, that is fine as long as it finishes before the results are needed. A failed run can simply be rerun.
Real-time prediction in practice
A real-time service keeps the model in memory and answers one request at a time over HTTP.
import joblib
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
model = joblib.load("model.joblib")
class Features(BaseModel):
tenure_months: float
monthly_spend: float
support_tickets: int
@app.post("/predict")
def predict(features: Features):
row = [[features.tenure_months, features.monthly_spend, features.support_tickets]]
return {"churn_score": float(model.predict_proba(row)[0, 1])}Points to notice here:
- The model loads once, at startup, not on each request. Loading from disk on every call would add a large, avoidable delay.
Featuresis a Pydantic model. FastAPI uses it to validate the request body and reject malformed input before it reaches the model.- The row is a plain list in a fixed order. The service has no column names to protect it, so the order
tenure_months,monthly_spend,support_ticketsmust match the training order exactly. A swapped order raises no error and produces wrong scores. - The
float(...)conversion turns a NumPy number into a Python float that can be converted to JSON.
You can run this with uvicorn app:app if the file is saved as app.py, then send a POST request to /predict.
Side-by-side view
The two patterns make opposite trade-offs. Later chapters cover each row in detail.
| Question | Batch | Real time |
|---|---|---|
| When does the model run? | On a schedule, before results are needed | At request time |
| Input size per run | Thousands to billions of records | One record or a few |
| Who waits? | No one | The caller |
| How fresh is the prediction? | As old as the last run | Based on inputs at request time |
| What must be always available? | The schedule and storage | A running service |
| Typical output location | File or table | HTTP response |
Neither pattern is better in general. Batch is simpler and cheaper to operate when predictions can be prepared ahead. Real time is necessary when the answer depends on information that only exists at the moment of the request.
Common mistakes at this stage
- Choosing real time by default. Teams often build an online service because it feels more modern, then discover the use case only needed a nightly table. A service you must keep available around the clock costs more to run than a job that runs once a day.
- Mixing up the model and the pipeline. The same model file can be served either way. The choice belongs to the delivery design, not to the model.
- Ignoring where inputs come from. A model needs features. Whether those features can be assembled in 50 milliseconds, or only by a nightly query, often decides the pattern before anything else does.
- Treating the saved file as the whole deliverable. Without pinned library versions, a feature list, and a version identifier, a model file is hard to serve correctly.
Where the rest of the tutorial goes
The next chapters take each pattern in turn and then compare them on latency, throughput, freshness, feature access, and cost. They then cover pipeline and service design, the patterns that sit between batch and real time, monitoring, and a decision framework. A third code example, a hybrid lookup that returns a precomputed score when one exists and falls back to a live prediction otherwise, appears when those hybrid patterns are covered.
Summary
- Inference applies a trained model to new data. Serving is the whole path from the saved artifact to the consumer of the predictions.
- The central design question is when the model runs: ahead of time on a schedule (batch) or when the request arrives (real time).
- A batch job scores many records in one vectorized pass and stores the results. A real-time service loads the model once and scores one request per call.
- Feature order and library versions must match training in both patterns.
- Neither pattern is universally better. The choice follows from the use case.
Exercise
A retailer wants a churn score for each of its 2 million customers, to be used by a marketing team that builds a campaign list every Monday morning. Which serving pattern fits, and what is the main reason?
Show answer
Batch prediction. The marketing team needs scores for the whole customer base once a week, and nobody waits on an individual result. A scheduled job can score all 2 million records in one pass, write them to a table, and finish before Monday. A real-time service would add always-on infrastructure and no benefit, because the use case has no per-request deadline.
Exercise
In the real-time service above, a teammate reorders the list to [features.monthly_spend, features.tenure_months, features.support_tickets] to "tidy up". The service still runs without errors. What goes wrong, and how could you protect against it?
Show answer
The model was trained with tenure_months first and monthly_spend second, so it now reads each value as the wrong feature and returns wrong scores with no error. To protect against this, build the row from a single shared list of feature names used in both training and serving, or pass a DataFrame with named columns. Also add a test that compares the service's output with the batch output for the same record.
Exercise
Why does the real-time example load the model at module level instead of inside the predict function?
Show answer
Loading the file from disk on every request adds a large, avoidable delay and wastes work. Loading once at startup keeps the model in memory, so each request pays only for the prediction itself.