Learning path: Serve a Model in Production: Docker, Latency and Scaling · Step 2 of 9
A Production FastAPI for an ML Model: Input Limits, /health, /ready and a Model Version
Grow a simple model API into one you can run: Field limits that refuse a humidity of 140, a clean 422, a /v1 route with a response model, a startup load with /health and /ready, and a model version in every log line.
What you will learn
- Refuse impossible inputs with Pydantic Field limits and extra="forbid"
- Return one short, clean 422 shape with a RequestValidationError handler
- Load the model once at startup with lifespan and report it through /health and /ready
- Version the route and log the model version with every prediction
Before you start
- Deploy a Machine Learning Model with FastAPI
- Python logging basics
Our rain service from Deploy a Machine Learning Model with FastAPI answers correctly. Now the question changes: not "does it answer?" but "can we trust it and run it?" The model doesn't change at all. It's the same model.joblib with the same five inputs. Only the service around it grows up.
From a window to a real shop
Picture a little window in a wall. You shout your order and somebody shouts back. Are they open? Nobody knows. A receipt? No. Order something silly and they'll answer anyway.
A real shop has three things the window doesn't:
- A counter, where your order gets checked: input limits and clean errors.
- Opening hours, so you can tell if it's open or not open yet:
/healthand/ready. - A receipt that says what you got and where it came from: the model version in every log line.
The window answers anything
First, let's probe the first service. Humidity3pm is just a float, so any number passes, though humidity runs from 0 to 100. A small script, probe.py, sends some odd days:
Humidity3pm=140 200 {"rain_tomorrow":"Yes","probability":0.96}
Cloud9am=99 200 {"rain_tomorrow":"Yes","probability":0.99}
Rainfall=-5 200 {"rain_tomorrow":"Yes","probability":0.61}
Wind=12 200 {"rain_tomorrow":"Yes","probability":0.63}
/health 404 {"detail":"Not Found"}
/ready 404 {"detail":"Not Found"}
It's very confident about days that can't exist. An extra field, Wind, is quietly ignored. There's no way to ask whether it's up. And if the model file is missing, the load at the top of the file fails and the server exits with code 1:
FileNotFoundError: [Errno 2] No such file or directory: 'model.joblib'
It does its job. It just can't refuse an order or say how it's doing.
The top of app.py
The new app.py starts with its imports and one logger, which every log line below comes from:
import hashlib
import logging
import threading
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Literal
import joblib
import pandas as pd
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel, ConfigDict, Field
logging.basicConfig(level=logging.INFO, datefmt="%H:%M:%S",
format="%(asctime)s %(levelname)s %(message)s")
log = logging.getLogger("rain")
The counter has limits
Each float now gets a Field with ge (greater or equal) and le (less or equal):
class Weather(BaseModel):
model_config = ConfigDict(extra="forbid")
Rainfall: float = Field(ge=0, le=500)
Humidity3pm: float = Field(ge=0, le=100)
Cloud9am: float = Field(ge=0, le=9)
Cloud3pm: float = Field(ge=0, le=9)
RainToday: Literal["Yes", "No"]
Where do the limits come from? From the meaning of each field, and from the data. The biggest rainfall in the training data is 371, so 500 leaves some room. Humidity runs from 0 to 100, and both cloud columns run from 0 to 9 in the training data.
extra="forbid" means a field that isn't on the list, like Wind, is refused instead of ignored. RainToday stays a Literal, so "Maybe" can't get in either. A limit says what the model was built for; outside it, the model is only guessing.
A refusal that reads clean
When a check fails, FastAPI raises a RequestValidationError. Our handler catches it before the route even runs:
@app.exception_handler(RequestValidationError)
def bad_input(request: Request, exc: RequestValidationError):
fields = {str(e["loc"][-1]): e["msg"] for e in exc.errors()}
log.info("rejected fields=%s", list(fields))
return JSONResponse(status_code=422, content={
"error": "invalid_input", "fields": fields})
Here's a humidity of 140, sent with the small helper ask.py:
POST /v1/predict -> 422
{"error":"invalid_input","fields":{"Humidity3pm":"Input should be less
than or equal to 100"}}
The model was not asked. Now compare the word "high" in the old service and the new one. The default FastAPI error has a type, a loc, a msg, and input, which repeats back whatever you sent:
{"detail":[{"type":"float_parsing","loc":["body","Humidity3pm"],"msg":"Input should be a valid number, unable to parse string as a number","input":"high"}]}
Ours keeps the message and drops the rest:
POST /v1/predict -> 422
{"error":"invalid_input","fields":{"Humidity3pm":"Input should be a valid
number, unable to parse string as a number"}}
The other refusals have the same shape:
{"error":"invalid_input","fields":{"RainToday":"Input should be 'Yes' or
'No'"}}
{"error":"invalid_input","fields":{"Wind":"Extra inputs are not
permitted"}}
{"error":"invalid_input","fields":{"Cloud3pm":"Field required"}}
Short, always the same shape, and it never repeats the input back.
A good order, through a versioned door
class Prediction(BaseModel):
rain_tomorrow: Literal["Yes", "No"]
probability: float
model_version: str
@app.post("/v1/predict", response_model=Prediction)
def predict(day: Weather):
if state["status"] != "ready":
return JSONResponse(status_code=503,
content={"error": "model_not_ready"})
row = pd.DataFrame([day.model_dump()])
answer = state["model"].predict(row)[0]
chance = round(float(state["model"].predict_proba(row)[0, 1]), 2)
log.info("prediction version=%s rain=%s probability=%s",
state["version"], answer, chance)
return Prediction(rain_tomorrow=answer, probability=chance,
model_version=state["version"])
The v1 is the version of the API, not of the model. If we ever change the inputs in a way that breaks callers, that gets its own door, /v2, and old callers keep using /v1. response_model=Prediction gives the answer a shape too, and that shape is a promise to the caller. Our wet day:
POST /v1/predict -> 200
{"rain_tomorrow":"Yes","probability":0.63,"model_version":"71aa8578"}
The same answer as before, with one new field.
One load, at startup
MODEL_FILE = Path("model.joblib")
state = {"status": "loading", "model": None, "version": None}
def load_model():
try:
data = MODEL_FILE.read_bytes()
state["version"] = hashlib.sha256(data).hexdigest()[:8]
state["model"] = joblib.load(MODEL_FILE)
state["status"] = "ready"
log.info("model loaded version=%s", state["version"])
except Exception as err:
state["status"] = "failed"
log.error("load failed: %s", err)
@asynccontextmanager
async def lifespan(app):
threading.Thread(target=load_model, daemon=True).start()
yield
app = FastAPI(title="Rain Predictor", lifespan=lifespan)
lifespan runs once, when uvicorn starts. It starts a side thread to do the load and then yields, which opens the door. Without the side thread, nothing would answer until the model is in.
The model version is the first 8 characters of the SHA-256 hash of the file's bytes: a fingerprint of the file. We sent 100 predictions; the log showed 100 predictions and exactly one load. Every request shares that one model.
Alive is not the same as ready
@app.get("/health")
def health():
return {"status": "alive"}
@app.get("/ready")
def ready():
if state["status"] != "ready":
return JSONResponse(status_code=503,
content={"status": state["status"]})
return {"status": "ready", "model_version": state["version"]}
/health asks "is the process alive?" and doesn't even look at the model. /ready asks "can it serve a prediction?" A script, watch_start.py, starts the server and prints every change:
1.01s /health no answer
2.02s /ready no answer
2.12s /health 200 {"status":"alive"}
2.12s /ready 503 {"status":"loading"}
22:43:18 INFO model loaded version=71aa8578
3.96s /ready 200 {"status":"ready","model_version":"71aa8578"}
The door opens before the model is in, and /ready says so. During that wait, a prediction gets a clean 503 {"error":"model_not_ready"}. Over 20 starts on this machine, all 20 saw the 503; the wait had a median of 2.15 seconds and a p95 of 2.77.
What if the model doesn't load?
Take the model file away. The first service stopped, so there was no server at all. In this one, the load runs inside a try, so the status becomes failed and the server keeps running:
1.01s /health no answer
22:45:20 ERROR load failed: [Errno 2] No such file or directory: 'model.joblib'
1.53s /ready 503 {"status":"failed"}
1.53s /health 200 {"status":"alive"}
A prediction gets 503 {"error":"model_not_ready"}: a clean answer, not a crash, and the log says why.
Who reads all this? Something in front of the service, like a load balancer. Ready is 503, so it sends no traffic. Health is 200, so restarting won't help. Someone still has to come and fix it; it won't fix itself. But a service that can say "I'm broken" is far easier to run than one that just vanishes.
Every answer gets a receipt
Every prediction logs one line with the version, the answer and the probability. Here's the server log for a wet day, a dry day, the humidity of 140 and a rainy day:
22:42:51 INFO prediction version=71aa8578 rain=Yes probability=0.63
22:42:52 INFO prediction version=71aa8578 rain=No probability=0.03
22:42:54 INFO rejected fields=['Humidity3pm']
22:42:59 INFO prediction version=71aa8578 rain=Yes probability=0.93
The rejected request has no prediction line, because the model never ran.
One honest limit of a fingerprint: we saved the same model again, compressed. The file changed, so the version became 08a96eef, with the same answer, 0.63. A file hash tells files apart, not trainings. If you serve from a model registry, such as the one in MLflow Model Registry Aliases, log the registry's version number instead.
Common mistakes
- One endpoint for both health and readiness. A process can be alive with no model. Keep the two questions apart.
- Letting a failed load kill the process. Then nothing can report what's wrong. Catch it, set a status, and answer 503.
- Echoing the input in errors. The default 422 repeats whatever was sent. Return the field and the message only.
- Calling
/v1the model version. It versions the request and response shape. The model version goes in the response and the log. - Limits with no reason. Base them on the field's meaning and the training data, not on guesses.
Quick recap
| Shop part | Code | Real result |
|---|---|---|
| Counter | Field(ge=..., le=...), extra="forbid" | humidity 140 gets 422; Wind refused |
| Clean errors | @app.exception_handler(RequestValidationError) | {"error":"invalid_input","fields":{...}} |
| Versioned door | /v1/predict, response_model=Prediction | Yes, 0.63, 71aa8578 |
| Opening hours | lifespan, /health, /ready | ready at 3.96 s; 503 while loading |
| Receipt | log.info("prediction version=...") | one line per answer |
Try it yourself
Set the Rainfall limit to 100 in app.py and restart uvicorn. Then run python ask.py rainy, which sends a Rainfall of 120. Which field does the error name? The project files are in the community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Online, Batch or Streaming? Picking the Serving Pattern for an ML Model
Next →Batch Scoring a Million Rows: Chunks, a Run ID and a Safe Rerun
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Python Virtual Environments: One Project, One Toolbox
Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.
Git and GitHub Fundamentals: Commits, Branches, Push and Pull
The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.
Testing a FastAPI App with pytest: Three Small Tests
A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.
Config and Logging Instead of Hard-Coded Values in ML Training
Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.