Serving ML Models with FastAPI: A Practical Guide

Serve a scikit-learn model with FastAPI: Pydantic schemas, loading once in lifespan, sync vs async endpoints, health checks, workers, Docker and batching.

By AI Agents DirectoryLast checked
Small humanoid robot sitting on a red bench reading a booklet

FastAPI is a common way to put a trained model behind an HTTP endpoint. Your model code stays in Python, Pydantic checks every request, and you get interactive docs without extra work. This guide builds one small but complete service around a scikit-learn classifier, then goes through the choices that matter once it leaves your laptop: where the model gets loaded, whether endpoints should be async, how many workers to run, and when to hand the job to a dedicated inference server. The code was run locally with FastAPI 0.162, Pydantic 2.14, scikit-learn 1.9 and Uvicorn 0.54.

The pieces

ConcernWhat to useWhy
Input and output shapePydantic modelsBad requests are rejected before they reach the model, and the response is filtered to the declared fields
Loading the modelThe lifespan parameterLoads once per process, before any request, and cleans up at shutdown
Inference callPlain def endpointFastAPI runs it in a threadpool, so blocking inference doesn’t freeze the server
Running itfastapi run or uvicorn, optionally --workersBoth use Uvicorn; workers add processes
Shipping itA Docker image built from the official Python imagePins the environment the model was trained in

Step 1: train and save a model

The scikit-learn model persistence guide trains a HistGradientBoostingClassifier on the iris dataset as its example, so this guide does the same. Save it with joblib, which the guide recommends over plain pickle for large models and big NumPy arrays:

# train.py
import joblib
from sklearn.datasets import load_iris
from sklearn.ensemble import HistGradientBoostingClassifier

X, y = load_iris(return_X_y=True)
clf = HistGradientBoostingClassifier().fit(X, y)
joblib.dump(clf, "model.joblib")

Two warnings from the same guide apply to every serving setup. First, pickle, joblib and cloudpickle can execute arbitrary code when a file is loaded, so treat a model file the way you would treat a script: only load it from a source you trust. If that’s a problem, the docs point to skops.io, which refuses unknown types until you approve them, or to ONNX. Second, loading a model under a different scikit-learn version is unsupported; you get an InconsistentVersionWarning and possibly wrong results. Pin the same library versions in training and in your API’s requirements.txt.

Step 2: the service

# main.py
from contextlib import asynccontextmanager

import joblib
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field

ml = {}


@asynccontextmanager
async def lifespan(app: FastAPI):
    ml["clf"] = joblib.load("model.joblib")  # runs once per process, before requests
    yield
    ml.clear()  # runs at shutdown


app = FastAPI(lifespan=lifespan)

CLASSES = ["setosa", "versicolor", "virginica"]


class Flower(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 PredictRequest(BaseModel):
    flowers: list[Flower] = Field(min_length=1, max_length=100)


class Prediction(BaseModel):
    label: str
    probability: float


class PredictResponse(BaseModel):
    predictions: list[Prediction]


@app.get("/health")
def health():
    if "clf" not in ml:
        raise HTTPException(status_code=503, detail="model not loaded")
    return {"status": "ok"}


@app.post("/predict")
def predict(req: PredictRequest) -> PredictResponse:
    rows = [[f.sepal_length, f.sepal_width, f.petal_length, f.petal_width]
            for f in req.flowers]
    probs = ml["clf"].predict_proba(rows)  # blocking call, so this is a plain def
    return PredictResponse(predictions=[
        Prediction(label=CLASSES[p.argmax()], probability=float(p.max()))
        for p in probs
    ])

Install with pip install "fastapi[standard]" scikit-learn joblib, run python train.py, then start the server with fastapi run main.py. Interactive docs appear at /docs. A request and the response from our local run:

curl -X POST localhost:8000/predict -H 'Content-Type: application/json' \
  -d '{"flowers":[{"sepal_length":5.1,"sepal_width":3.5,"petal_length":1.4,"petal_width":0.2}]}'
# {"predictions":[{"label":"setosa","probability":0.99998...}]}

Sending a negative length or leaving a field out never reaches the model. FastAPI answered with a 422 that named each failing field, for example ["body","flowers",0,"petal_width"] with “Field required”.

Why the model loads in lifespan

The FastAPI lifespan docs use exactly this case as their example. Code before yield in the lifespan function runs once, before the app accepts traffic; code after it runs once when the server stops, which is where you would free memory or a GPU. Loading at the top of the module also works, but then every import pays the load cost, including test runs that never touch the model.

Some details worth knowing:

  • The older @app.on_event("startup") and "shutdown" handlers are deprecated. If you pass lifespan, those handlers stop being called, so pick one style.
  • Lifespan only runs for the main app, not for sub-applications mounted under it.
  • In Docker, write CMD in exec form (a JSON list). The FastAPI docs say the shell form can stop lifespan shutdown code from running and the app from exiting cleanly.

Pydantic does the input checking

Declaring a parameter as a Pydantic model tells FastAPI to parse the JSON body, coerce types where it can, validate it, and hand you a typed object; see the request body tutorial. Field() adds constraints such as gt=0 or a maximum list length, which is a cheap guard against a client sending ten thousand rows in one call.

The return type matters too. According to the response model docs, FastAPI validates what you return, adds its schema to the OpenAPI docs, and trims the output to the declared fields. If your code returns something malformed, the client gets a server error rather than bad data. That trimming also stops you from leaking internal fields, such as raw feature vectors or debug values.

def or async def

This is the choice that most often hurts ML APIs. FastAPI’s concurrency page explains that a path operation declared with plain def runs in an external threadpool, while an async def function runs directly on the event loop. Model inference is CPU-bound work and libraries like scikit-learn don’t offer an awaitable API, so:

  • Use def when the endpoint calls a blocking model, as /predict does above. Other requests keep moving while a thread does the work.
  • Use async def only when everything inside it is awaitable, for example calling a remote model API with an async HTTP client.
  • Never call a slow model inside async def without handing it off. It blocks the event loop, and every other request on that process waits.

The docs’ own rule of thumb when unsure is to use plain def. For CPU-heavy inference, the same page points to running several processes in parallel to use more cores, which is what workers are for.

Health checks

The /health endpoint above returns 503 until the model is in memory. That fits how orchestrators work. The Kubernetes probe docs describe readiness probes for apps that need time to load large data at startup: a pod that isn’t ready gets no traffic, and a failing liveness probe gets the container restarted. Point readiness at an endpoint that confirms the model loaded. Keep liveness cheap so a slow prediction never gets a healthy container killed.

Workers and memory

Both fastapi run --workers 4 main.py and uvicorn main:app --workers 4 start several processes, as shown on the server workers page. Each one is a separate process that runs lifespan on its own, so each holds its own copy of the model. FastAPI’s deployment concepts page points out that processes don’t normally share memory. A model that takes a lot of RAM therefore costs that much again for every worker you add. Size the worker count to memory, not just to cores.

Uvicorn’s deployment docs add two practical notes: --reload (for local development) and --workers can’t be combined, and the uvicorn.workers module used to run Uvicorn under Gunicorn is deprecated.

Docker

The FastAPI Docker guide starts from the official Python image. Adapted for a single-file app plus the model file:

FROM python:3.14
WORKDIR /code
COPY ./requirements.txt /code/requirements.txt
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
COPY ./main.py ./model.joblib /code/
CMD ["fastapi", "run", "main.py", "--port", "80"]

Copying requirements.txt before the code lets Docker reuse the cached dependency layer when only your code changes. Add --proxy-headers if the container sits behind Nginx or Traefik. On Kubernetes, the guide recommends one Uvicorn process per container and leaving replication to the cluster. Use --workers inside a container only for simpler setups, such as one server running Docker Compose.

Batching, and when FastAPI is not enough

scikit-learn, PyTorch and TensorFlow can all score many rows in a single call. The request schema above already takes a list of flowers, so one HTTP request becomes one vectorized predict_proba call. That is client-side batching, and it covers many workloads.

What plain FastAPI doesn’t give you is server-side dynamic batching, which collects separate requests from different clients and runs them as one batch. That matters for GPU models, where small batches waste hardware. Dedicated servers do it for you:

OptionWhat it adds
Ray Serve@serve.batch queues requests up to a max batch size or a timeout. It can wrap an existing FastAPI app with @serve.ingress, so your routes and docs stay.
NVIDIA TritonOpen-source inference server for TensorRT, PyTorch, ONNX, OpenVINO and more models, with per-model schedulers and a configurable dynamic batcher

A reasonable rule: stay with FastAPI while one process per container keeps up and your model runs well on CPU. Move to Ray Serve or Triton once you need cross-request batching, several models sharing GPUs, or scaling per model. For other ways to package a model, see MLeap for exporting pipelines to a lightweight runtime and OpenVINO for optimized inference. The LLM infrastructure and developer tools hubs list more serving options, and if you want a quick UI in front of a model instead of an API, see our Streamlit guide.

#FastAPI#Python#Model serving#scikit-learn#Docker
AI

Written by AI Agents Directory

Editorial team

Facts in this guide are checked against official documentation and repositories, which are linked in the article.