Serving a Model with an API
Building a prediction service with FastAPI, with input validation, automatic documentation and a health check.
Serving patterns
| Pattern | When |
|---|---|
| Online | An instant decision, such as an application interface |
| Batch | Nightly predictions for millions of records |
| Streaming | Successive events, such as fraud detection |
| Edge | Privacy or offline operation |
A service with FastAPI
# app.py — pip install fastapi uvicorn joblib scikit-learn pandas
from contextlib import asynccontextmanager
from fastapi import FastAPI
from pydantic import BaseModel, Field
import joblib, pandas as pd
MODEL_VERSION = "1.0.0"
state = {}
@asynccontextmanager
async def lifespan(app: FastAPI):
state["model"] = joblib.load("model.joblib") # once at startup
yield
app = FastAPI(title="Risk model", lifespan=lifespan)
class Patient(BaseModel):
age: int = Field(ge=0, le=120)
glucose: float = Field(ge=0)
sex: str
region: str
@app.get("/health")
def health():
return {"status": "ok", "model_version": MODEL_VERSION}
@app.post("/predict")
def predict(p: Patient):
proba = float(state["model"].predict_proba(pd.DataFrame([p.model_dump()]))[0, 1])
return {"probability": proba, "model_version": MODEL_VERSION}Running: uvicorn app:app --host 0.0.0.0 --port 8000, with interactive documentation at /docs.
Practices
- Log every request (without unnecessary personal data) with the version and the latency.
- Set a timeout and a maximum request size.
- Add authentication if the service is not public.
- Load-test it and measure p50, p95 and p99 latency.
Lesson terms
- Latency
- The time between sending a request and receiving the response, often measured as a percentile such as p95.
- Model serving
- Making the trained model available to receive prediction requests from other systems or users.
Abstract
Serving a model means making it available to other systems. Common patterns: a real-time service over HTTP, scheduled batch processing, event streaming, and running on the device. FastAPI is a Python framework that uses Pydantic models to validate inputs and generates documentation automatically. The model is loaded once when the service starts, a health check endpoint is added, and the model version is recorded in every response to make tracing easier.
Review questions
-
Why do we load the model when the service starts and not inside each request?
Because loading is costly, and repeating it raises latency and consumes resources.
-
What is the benefit of returning the model version with each prediction?
Linking each decision to the model that produced it, for auditing and error analysis.
Sources and references
Complete the lesson
You have completed all the lessons in the track! You can now request the track completion certificate.
Request the certificate