Sub topic 5
Loading the model once at startup
This chapter assumes you can write a FastAPI route, you know what a Pydantic model is, and you have a model.joblib file from the previous chapter. You should also know that joblib.load reads a file from disk and rebuilds a Python object.
Why load once
Loading a model reads a file, unpickles it, and allocates memory. For the iris forest this takes milliseconds. For a large model it can take seconds or minutes. If you call joblib.load inside the request handler, every request pays that cost, and each concurrent request holds its own copy in memory.
The fix is to load the model once, when the process starts, and keep it in a place every request can read.
The lifespan pattern
FastAPI runs a lifespan function around the whole life of the app. Code before yield runs once at startup, before the server accepts requests. Code after yield runs once at shutdown.
from contextlib import asynccontextmanager
import joblib
from fastapi import FastAPI
models = {}
@asynccontextmanager
async def lifespan(app: FastAPI):
models["iris"] = joblib.load("model.joblib")
yield
models.clear()
app = FastAPI(lifespan=lifespan)The module-level dictionary models holds the loaded object. Handlers read from it with models["iris"]. A dictionary lets you add more models later without new global names.
Fail fast
If the file is missing or corrupt, joblib.load raises an exception inside the lifespan. The server then refuses to start. This is the behavior you want. A service that starts without its model and returns errors on every call is harder to diagnose than one that never comes up.
The /health endpoint from the full service reports "model_loaded": "iris" in models. With fail-fast startup this is always true for a running process, but the check is cheap and later chapters use it.
Common errors
- Loading inside the handler. The service works but is slow, and memory use grows under load.
- Loading at import time. A bare
model = joblib.load(...)at the top ofmain.pyalso loads once. However, it runs whenever anything imports the module, including test collection and tools that only inspect the app. Lifespan keeps loading tied to the app actually running. - Using the old
@app.on_event("startup")hook. It still works in many versions but is deprecated in favor of lifespan. - Relative paths.
"model.joblib"resolves against the working directory, not the file's location. Startinguvicornfrom another folder givesFileNotFoundError. Use a path built fromPath(__file__).parentor an environment variable when this matters. - Testing without startup.
TestClient(app)used without awithblock does not run lifespan, somodelsis empty and/predictraisesKeyError. Usewith TestClient(app) as client:.
Check your understanding
Exercise
You start the service from the parent directory with uvicorn app.main:app and it fails at startup with FileNotFoundError: model.joblib, although the file sits next to main.py. Why does this happen, and how would you fix it?
Show answer
The path "model.joblib" is resolved against the current working directory, which is the parent directory, not the folder containing main.py. Fix it by building the path from the source file, for example Path(__file__).parent / "model.joblib", or by reading the path from an environment variable. Because loading happens in the lifespan function, the server fails at startup instead of failing on the first request.
Exercise
A teammate's test calls client = TestClient(app) and then client.post("/predict", ...). The request fails with KeyError: 'iris'. What is wrong?
Show answer
Without a with block, TestClient does not run the lifespan startup code, so the model was never loaded into models. Use with TestClient(app) as client: so startup runs before the request.