Sub topic 1
From a Trained Model to a Service
Prerequisites
This chapter assumes you can do the following:
- Write basic Python, including functions and classes.
- Train and use a scikit-learn style model (
fitandpredict). - Read an HTTP request and response, and recognize JSON.
- Run commands in a terminal.
You do not need to know FastAPI yet. Later chapters introduce it step by step.
Training versus serving
A trained model is useful only when something can ask it questions. Two separate jobs are involved.
Training is the job of learning parameters from data. It runs rarely, often for minutes or hours, and it reads a whole dataset. Its output is a model.
Serving, also called inference, is the job of applying a finished model to new inputs. It runs continuously, handles one request or a small batch at a time, and must answer in milliseconds to seconds. Its input is a single set of feature values. Its output is a prediction.
These two jobs have different needs, so they usually run as different programs, on different machines, at different times.
| Aspect | Training | Serving |
|---|---|---|
| Input | Full dataset | One row or a small batch |
| Duration | Minutes to hours | Milliseconds per request |
| Frequency | Occasional | Continuous |
| Main concern | Model quality | Latency, reliability, correctness |
| Failure cost | Rerun the job | Callers see errors |
The consequence is that the training script and the service share only one thing: a file that holds the trained model. That file is the model artifact. The next chapter covers it in detail. Here we need only the idea.
Why a notebook is not a service
Suppose you have a model in a notebook. A colleague's application, written in another language, wants predictions. Several approaches are possible, and each has costs.
- Send them the notebook. They need your Python environment, your libraries, and your code. Any change breaks them.
- Send them the model file. They must run Python and the same scikit-learn version. A mismatch can fail to load or silently change results.
- Run the model behind an HTTP API. They send JSON over the network and receive JSON back. They need no Python, no scikit-learn, and no knowledge of how the model works.
The third approach is the subject of this tutorial. HTTP is understood by nearly every language and tool. The service hides the model behind a stable interface, so you can retrain, swap, or rewrite the model without changing any caller, as long as the interface stays the same.
What a model service does
A minimal prediction service performs the same steps for every request:
- Receive an HTTP request containing feature values as JSON.
- Check that the values are present, have the right types, and are in a sensible range.
- Convert them into the shape the model expects.
- Call the model's
predictmethod. - Convert the result into JSON and return it.
Steps 2 and 3 are where most production bugs occur. A model does not know what a sepal is. It accepts a numeric array, and it will happily return an answer for nonsense input. The service is the layer that protects the model from bad data.
The running example
Every chapter uses one small example so the infrastructure stays in focus. We train a random forest on the iris dataset, which has four measurements per flower and three flower classes, and expose it through FastAPI.
The first piece is the training script. It runs once, offline, and writes the artifact.
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
import joblib
X, y = load_iris(return_X_y=True)
model = RandomForestClassifier(n_estimators=100, random_state=0)
model.fit(X, y)
joblib.dump(model, "model.joblib")Running this produces model.joblib in the current directory. The service never trains. It only loads this file. That separation is the central design decision of the whole tutorial.
The finished service will look like this from the outside. You start it, then send one request:
uvicorn main:app --port 8000
curl -X POST http://localhost:8000/predict \
-H "Content-Type: application/json" \
-d '{"sepal_length": 5.1, "sepal_width": 3.5, "petal_length": 1.4, "petal_width": 0.2}'The uvicorn command starts the web server, and main:app means "the object named app in main.py". The curl command sends a POST request with a JSON body. The response is a small JSON object containing the predicted class index. You will write main.py over the next chapters. For now, treat it as a black box with one job: JSON in, prediction out.
Design decisions to make early
Moving from a model to a service forces choices that notebooks let you ignore. Making them early avoids rework.
What is the unit of prediction?
Decide whether callers send one row or many. A single-row endpoint is simple and fits interactive use. A batch endpoint scores many rows in one model call and is usually cheaper per row. Many services offer both. The batching chapter covers the latency trade-off.
Who owns preprocessing?
If training scaled features or encoded categories, the same steps must run at inference. There are two safe options. Bundle preprocessing and model into one scikit-learn Pipeline and save that. Or write the preprocessing in shared code that both training and serving import. Duplicating the logic by hand in the service is the most common cause of training-serving skew, where the model sees different inputs in production than it saw in training.
What does the caller see when things go wrong?
A service must return clear errors. Invalid input should produce a client error (HTTP 4xx) with a message. A broken model or missing file should produce a server error (5xx). Keep these two categories separate, because callers handle them differently: they fix their request for a 4xx and retry later for a 5xx.
How is the service kept in step with the model?
The artifact and the service code depend on each other. A model trained with four features cannot be served by code that sends five. The same applies to library versions, so record the versions used for training.
Common errors
These problems appear in almost every first deployment.
- Retraining inside the service. Fitting a model on startup or per request is slow and makes predictions change between restarts. Train offline and load a file.
- Loading the model on every request. Reading a file from disk each time adds avoidable latency. Load once at startup. A later chapter shows how.
- Version mismatch. A
joblibfile is a Python object snapshot. Loading it under a different scikit-learn version can raise errors or produce different results. Pin versions inrequirements.txt. - Trusting the input. Skipping validation lets malformed data reach the model, where it can produce a confusing exception or a meaningless answer.
- Treating the model file as safe data.
joblibfiles use Python's pickle format, and loading one can execute code. Only load artifacts you created or fully trust.
What the rest of the tutorial builds
The remaining chapters add one layer at a time. First, the artifact is saved and loaded in a separate process. Next come the request and response contract, input validation, startup loading, and the prediction endpoint. After that, a health check, automated tests, and a Docker image make the service something you can ship. The final chapters cover batching, concurrency, versioning, monitoring, security, scaling, and the point at which a dedicated model server beats a hand-written API.
Exercise
A teammate proposes calling model.fit(X, y) inside the service at startup, so the service always uses fresh data. Give two problems with this and describe what to do instead.
Show answer
First, startup becomes slow, because training can take minutes or hours, and the service cannot answer requests until it finishes. Second, predictions can change from one restart to the next, because training data or random seeds may differ, so behavior is hard to reproduce and debug. Instead, train offline in a separate script, save the result as a model artifact such as model.joblib, and have the service only load that file. To use fresh data, rerun the training script and deploy the new artifact.
Exercise
Your training code standardized features with StandardScaler before fitting the model. The service you write sends raw feature values straight to model.predict. What problem does this cause, and give one way to prevent it.
Show answer
The model was trained on scaled values but now receives unscaled ones, so its predictions will be wrong even though no error is raised. This is training-serving skew. To prevent it, put the scaler and the model together in one scikit-learn Pipeline and save the whole pipeline as the artifact, so the same preprocessing runs at inference. Sharing the preprocessing code between training and serving also works.