Sub topic 5
Loading the model once at startup
This chapter assumes you can write a basic FastAPI route, you know what a Pydantic model is, and you have a model.joblib file from the previous chapter. It covers where a model should be loaded in a web service, why, and what goes wrong when it is loaded in the wrong place.
Why loading location matters
Loading a model means reading a file from disk and rebuilding Python objects in memory. For the iris forest this takes milliseconds. For a real model it can take seconds or minutes, and it can use gigabytes of memory.
A web service handles many requests over its lifetime. If each request loads the model, every caller pays the load cost, and memory use multiplies when requests overlap. The fix is to load the model once, when the process starts, and let every request reuse the same object.
There are three common places to put the load. Only one of them is a good default.
| Where the load happens | Cost per request | Risk |
|---|---|---|
| Inside the route function | Full load time on every call | Slow responses, memory spikes under load |
| At module import time | None after import | Hard to test, hard to fail cleanly, runs on any import |
| In a lifespan handler | None after startup | Needs a small amount of extra code |
The naive version and its cost
This route loads the model on every call. It works, but it is the pattern to avoid.
import joblib
from fastapi import FastAPI
app = FastAPI()
@app.post("/predict-slow")
def predict_slow(row: list[float]):
model = joblib.load("model.joblib") # runs on every request
return {"class_index": int(model.predict([row])[0])}Under a load test, the latency of this route is roughly the prediction time plus the load time. With a large model the second term dominates, and parallel requests each hold their own copy of the model in memory.
The lifespan handler
FastAPI lets you run code before the first request and after the last one. You pass an async context manager to the lifespan argument. Code before yield runs at startup. Code after yield runs at shutdown.
The service from this tutorial uses it like this:
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 sequence of events is:
- The server process starts and imports
main.py. - The server enters the lifespan context. The model is loaded into the
modelsdictionary. - The server begins accepting requests. Every route reads
models["iris"]. - On shutdown, the code after
yieldruns and the dictionary is cleared.
Why a dictionary
The model lives in a module-level dictionary instead of a bare global variable. A dictionary can be changed in place from inside the lifespan function without a global statement. It also scales to several models: add another key and a second joblib.load line. The routes look the model up by name.
The older @app.on_event("startup") hooks still work in many FastAPI versions, but they are deprecated. Use lifespan in new code.
Using the loaded model in a route
A route reads the model from the dictionary and calls it. Nothing is loaded here.
@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))The next chapter walks through this route in detail. For now, notice that the only model-related work is the predict call.
What startup loading gives you
- Predictable latency. The first request is as fast as the thousandth.
- One copy in memory per process. Memory use does not grow with request count.
- Fail-fast behavior. If the file is missing or corrupt, startup raises an exception and the server does not begin serving. An orchestrator sees a failed start instead of a service that returns errors.
- A clear place for setup. Warm-up calls, config reads, and other one-time work belong in the same block.
Edge cases and common errors
The model file path
joblib.load("model.joblib") is relative to the working directory of the process, not to the location of main.py. If you start Uvicorn from another directory, the load fails with FileNotFoundError. A more robust form builds the path from the source file:
from pathlib import Path
MODEL_PATH = Path(__file__).parent / "model.joblib"Then call joblib.load(MODEL_PATH). In a container, copy the model next to main.py so both approaches agree.
Several worker processes
Each Uvicorn worker is a separate process with its own memory. If you run four workers, the lifespan handler runs four times and you hold four copies of the model. This is correct behavior, but it affects memory planning. A 2 GB model with four workers needs about 8 GB.
Tests that skip startup
TestClient(app) does not run the lifespan handler unless you use it as a context manager. This test fails with a KeyError on "iris":
from fastapi.testclient import TestClient
from main import app
client = TestClient(app) # lifespan does not run
response = client.post("/predict", json={
"sepal_length": 5.1, "sepal_width": 3.5,
"petal_length": 1.4, "petal_width": 0.2,
})Write with TestClient(app) as client: and the model loads before the request. The testing chapter returns to this.
Version mismatches
A .joblib file is a pickle. It must be loaded with a compatible scikit-learn version, and loading it can run arbitrary code. Pin the same library versions in training and serving, and only load files you produced yourself or trust fully.
Blocking the event loop at startup
A slow load inside an async lifespan function blocks the event loop while it runs. That is acceptable at startup, because no requests are being served yet. It would be a problem if you reloaded a model while the service was live. Chapter material on concurrency covers that case.
Reloading without a restart
The pattern here loads once and never refreshes. If you replace model.joblib on disk, the running process keeps the old model. The usual answer is to deploy a new process and let the old one drain, not to hot-reload inside the process. This also keeps each running instance tied to one known model version.
Checking it works
Start the service and look at the log. You should see Uvicorn report that application startup is complete only after the load finishes:
uvicorn main:app --port 8000
curl http://localhost:8000/healthThe health response should contain "model_loaded": true. To confirm the load happens once, add a print("loading model") line before joblib.load and send several prediction requests. The message appears a single time.
Exercise
You run uvicorn main:app --workers 3 and the lifespan handler loads a 1.5 GB model. Roughly how much memory do the model copies use, and how many times does the load message print?
Show answer
About 4.5 GB, because each of the three worker processes has its own copy. The message prints three times, once per worker at startup.
Exercise
A test creates client = TestClient(app) at module level and calls /predict. It fails with KeyError: 'iris'. What is wrong and how do you fix it?
Show answer
The lifespan handler never ran, so models is empty. Use the context-manager form, with TestClient(app) as client:, so startup code executes before the request.