Sub topic 2
Loading a Machine Learning Model Once at Startup
Prerequisites: you should know basic Python, FastAPI, HTTP, JSON, and scikit-learn model usage. Assume model.joblib already contains a trained classifier.
Loading the model once at startup
A web service should load the model during application startup, not for every request. Loading once avoids repeated disk access and makes prediction latency more consistent. FastAPI’s lifespan function runs startup code before the service accepts requests.
from contextlib import asynccontextmanager
import joblib
from fastapi import FastAPI
from pydantic import BaseModel, Field
class IrisFeatures(BaseModel):
sepal_length: float = Field(gt=0)
sepal_width: float = Field(gt=0)
petal_length: float = Field(gt=0)
petal_width: float = Field(gt=0)
class Prediction(BaseModel):
class_index: int
models = {}
@asynccontextmanager
async def lifespan(app: FastAPI):
models["iris"] = joblib.load("model.joblib")
yield
models.clear()
app = FastAPI(lifespan=lifespan)The model is stored in a process-local dictionary. Each server worker loads its own copy, so memory use increases when you add workers.
Building the prediction endpoint
The endpoint converts the validated object into the feature order used during training. That order must remain unchanged.
@app.post("/predict", response_model=Prediction)
def predict(features: IrisFeatures):
row = [[
features.sepal_length,
features.sepal_width,
features.petal_length,
features.petal_width,
]]
prediction = models["iris"].predict(row)[0]
return Prediction(class_index=int(prediction))Adding a health check
A health endpoint gives deployment systems a simple signal. Report whether the model is loaded, rather than only whether the web process is running.
@app.get("/health")
def health():
return {"status": "ok", "model_loaded": "iris" in models}Testing the API
Use FastAPI’s TestClient as a context manager so the lifespan function runs during the test.
from fastapi.testclient import TestClient
from main import app
def test_predict():
with TestClient(app) as client:
response = client.post(
"/predict",
json={
"sepal_length": 5.1,
"sepal_width": 3.5,
"petal_length": 1.4,
"petal_width": 0.2,
},
)
assert response.status_code == 200
assert isinstance(response.json()["class_index"], int)
def test_rejects_negative_value():
with TestClient(app) as client:
response = client.post(
"/predict",
json={
"sepal_length": -1,
"sepal_width": 3.5,
"petal_length": 1.4,
"petal_width": 0.2,
},
)
assert response.status_code == 422Exercise
Why should the model load in the lifespan function instead of inside predict?
Show answer
Startup loads it once, avoiding repeated disk access for every request.