FastAPI for Production: Loading, Health, Versions and Errors
The service from the previous lesson answers correct requests correctly. Production is mostly about everything else: the first seconds after start-up, when the model is still loading; the orchestrator asking whether the process is alive; a client that still uses last year's API; a request with 50,000 rows; a model call that hangs; an exception at 3 a.m. that someone must find in the logs. None of this is ML, and all of it decides whether the ML is usable. This lesson adds those pieces one at a time, with the same rule as before: every endpoint is async def so that the examples run in the browser.
Load once, and say when you are ready
Loading a model can take a long time: reading hundreds of megabytes, verifying a hash, warming up a runtime. It must happen once per process, before the first request, and the process must be able to tell the outside world whether it is done. FastAPI's lifespan handler is the place for start-up and shutdown work: the code before yield runs at start-up, the code after it at shutdown.
Two health endpoints serve two different questions from the orchestrator (Kubernetes, a load balancer; see probes):
- liveness (
/health/live): is the process working at all? If not, restart it. It should not depend on the model, or a slow load causes a restart loop. - readiness (
/health/ready): can it serve predictions now? If not, send traffic elsewhere. It returns 503 until the model is loaded (and, if you like, when a dependency it needs is down).
httpx.ASGITransport does not run lifespan events, so the example enters the lifespan context itself; on a real server Uvicorn does that.
import asyncio, hashlib, io, httpx, joblib
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
# Stand-in for the artifact store: a model file and its recorded hash
X, y = make_classification(n_samples=2000, n_features=8, n_informative=5, random_state=0)
buf = io.BytesIO(); joblib.dump(LogisticRegression().fit(X, y), buf)
ARTIFACT, EXPECTED_SHA = buf.getvalue(), hashlib.sha256(buf.getvalue()).hexdigest()
state = {}
@asynccontextmanager
async def lifespan(app):
if hashlib.sha256(ARTIFACT).hexdigest() != EXPECTED_SHA: # refuse a corrupted artifact
raise RuntimeError("model hash mismatch")
state["model"] = joblib.load(io.BytesIO(ARTIFACT))
state["version"] = "3"
print("startup: model loaded")
yield
state.clear()
print("shutdown: model released")
app = FastAPI(lifespan=lifespan)
@app.get("/health/live")
async def live():
return {"status": "alive"}
@app.get("/health/ready")
async def ready():
if "model" not in state:
raise HTTPException(status_code=503, detail="model not loaded")
return {"status": "ready", "model_version": state["version"]}
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as c:
async def probe(when):
l, r = await c.get("/health/live"), await c.get("/health/ready")
print(f"{when}: live {l.status_code}, ready {r.status_code} {r.json()}")
await probe("before start-up")
async with lifespan(app): # what uvicorn does around the server's lifetime
await probe("after start-up ")
await probe("after shutdown ")
asyncio.run(main())before start-up: live 200, ready 503 {'detail': 'model not loaded'}
startup: model loaded
after start-up : live 200, ready 200 {'status': 'ready', 'model_version': '3'}
shutdown: model released
after shutdown : live 200, ready 503 {'detail': 'model not loaded'}
Before start-up the process is alive (200) but not ready (503); after the lifespan has loaded and hash-checked the model, both are 200; after shutdown, readiness is 503 again, so a load balancer stops sending traffic to a pod that is shutting down.
Versioned routes and a batch endpoint
A deployed API is a promise. When the response format must change (a new field is harmless, a renamed or removed field is not), keep the old version running and add a new one next to it: /v1/predict and /v2/predict. An APIRouter per version keeps the code apart; the old version is removed only once its clients have moved (watch its request count).
Clients that score many rows should not send thousands of separate requests: a batch endpoint takes a list, runs the model once on the whole matrix (much faster per row, see batching) and returns a list. It needs an input limit, or one client can send a million rows and occupy the service for minutes.
import asyncio, httpx
import numpy as np
from fastapi import APIRouter, FastAPI
from pydantic import BaseModel, Field, create_model
from sklearn.datasets import make_classification
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
FEATURES = ["income", "debt_ratio", "age", "years_employed", "num_accounts",
"late_payments", "credit_utilisation", "loan_amount"]
X, y = make_classification(n_samples=2000, n_features=8, n_informative=5, random_state=0)
MODEL = make_pipeline(StandardScaler(), LogisticRegression()).fit(X, y)
Row = create_model("Row", **{f: (float, ...) for f in FEATURES}) # one required float per feature
class Batch(BaseModel):
rows: list[Row] = Field(min_length=1, max_length=100) # input limit
def score(rows):
m = np.array([[getattr(r, f) for f in FEATURES] for r in rows])
return MODEL.predict_proba(m)[:, 1]
v1, v2 = APIRouter(prefix="/v1"), APIRouter(prefix="/v2")
@v1.post("/predict")
async def predict_v1(row: Row):
return {"p_default": round(float(score([row])[0]), 4)} # v1 contract: one number
@v2.post("/predict")
async def predict_v2(row: Row):
p = float(score([row])[0]) # v2 adds a decision and the version
return {"p_default": round(p, 4), "decision": "review" if p >= 0.5 else "approve", "model_version": "3"}
@v2.post("/predict/batch")
async def predict_batch(batch: Batch):
return {"p_default": score(batch.rows).round(4).tolist(), "n": len(batch.rows)}
app = FastAPI()
app.include_router(v1); app.include_router(v2)
async def main():
rows = [dict(zip(FEATURES, r.round(3).tolist())) for r in X[:150]]
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as c:
print("v1 ", (await c.post("/v1/predict", json=rows[0])).json())
print("v2 ", (await c.post("/v2/predict", json=rows[0])).json())
r = await c.post("/v2/predict/batch", json={"rows": rows[:3]})
print("batch 3 ", r.status_code, r.json())
r = await c.post("/v2/predict/batch", json={"rows": rows})
print("batch 150", r.status_code, [(e["loc"], e["type"]) for e in r.json()["detail"]])
asyncio.run(main())v1 {'p_default': 0.9974}
v2 {'p_default': 0.9974, 'decision': 'review', 'model_version': '3'}
batch 3 200 {'p_default': [0.9974, 0.0892, 0.0652], 'n': 3}
batch 150 422 [(['body', 'rows'], 'too_long')]
Both versions return the same probability (0.9974 for the first row), in their own format. The batch of 3 rows is scored in one model call; the batch of 150 rows is refused with 422 too_long before any work is done, because the limit is part of the request model.
Errors, request ids, logs and size limits
Three cross-cutting concerns are best handled once, outside the endpoints:
- Request ids. Every request gets an id, taken from the client's
X-Request-IDheader if present, else generated. It is returned in the response and put in every log line, so a user's complaint ("request abc-123 failed") leads straight to the logs, and through tracing to the other services involved. - Structured logs. One JSON line per request with id, path, status, latency and model version, and no personal data (structured logging). Logging the prediction inputs is a separate, deliberate decision (privacy, retention) that monitoring needs.
- Error handling. Known failure modes (the model or a feature store is unavailable) get their own exception and a clear status code (503, retry later). Everything else becomes a generic 500 without the stack trace or internal details in the body; the details go to the log, under the request id.
A body size limit belongs here too: reject a request whose Content-Length is too large with 413 before reading or parsing it.
import asyncio, itertools, json, logging, sys, httpx
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
log = logging.getLogger("risk-service")
log.handlers.clear(); log.propagate = False
handler = logging.StreamHandler(sys.stdout); handler.setFormatter(logging.Formatter("%(message)s"))
log.addHandler(handler); log.setLevel(logging.INFO)
MAX_BODY = 10_000 # bytes
ids = itertools.count(1) # a real service would use uuid4()
app = FastAPI()
class FeatureStoreDown(Exception):
pass
@app.middleware("http")
async def request_context(request: Request, call_next):
rid = request.headers.get("x-request-id") or f"req-{next(ids)}"
if int(request.headers.get("content-length", 0)) > MAX_BODY:
response = JSONResponse({"detail": "request body too large"}, status_code=413)
else:
try:
response = await call_next(request)
except Exception as exc: # a bug: log the details, answer with a generic 500
log.info(json.dumps({"rid": rid, "error": type(exc).__name__, "msg": str(exc)}))
response = JSONResponse({"detail": "internal error", "request_id": rid}, status_code=500)
response.headers["X-Request-ID"] = rid
log.info(json.dumps({"rid": rid, "path": request.url.path, "status": response.status_code}))
return response
@app.exception_handler(FeatureStoreDown)
async def feature_store_down(request: Request, exc: FeatureStoreDown):
return JSONResponse({"detail": "feature store unavailable, retry later"}, status_code=503)
@app.post("/v2/predict")
async def predict(request: Request):
body = await request.json()
if body.get("customer") == "unknown-features":
raise FeatureStoreDown()
if body.get("customer") == "bug":
raise KeyError("credit_utilisation") # a bug: the details must not reach the client
return {"p_default": 0.12}
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as c:
for body, headers in [({"customer": "c1"}, {"X-Request-ID": "abc-123"}),
({"customer": "unknown-features"}, {}),
({"customer": "bug"}, {}),
({"customer": "x" * 20_000}, {})]:
r = await c.post("/v2/predict", json=body, headers=headers)
print(" ->", r.status_code, r.json(), "| id", r.headers["x-request-id"])
asyncio.run(main()){"rid": "abc-123", "path": "/v2/predict", "status": 200}
-> 200 {'p_default': 0.12} | id abc-123
{"rid": "req-1", "path": "/v2/predict", "status": 503}
-> 503 {'detail': 'feature store unavailable, retry later'} | id req-1
{"rid": "req-2", "error": "KeyError", "msg": "'credit_utilisation'"}
{"rid": "req-2", "path": "/v2/predict", "status": 500}
-> 500 {'detail': 'internal error', 'request_id': 'req-2'} | id req-2
{"rid": "req-3", "path": "/v2/predict", "status": 413}
-> 413 {'detail': 'request body too large'} | id req-3
Every response carries an id, the client's own (abc-123) or a generated one, and every log line has it. The feature-store outage becomes a 503 through its exception handler; the bug becomes a 500 whose body says only "internal error" and the id, while the log line under req-2 records the KeyError and the missing key; the 20 kB body is refused with 413 before the endpoint parses it. The example catches unexpected exceptions inside the middleware rather than with @app.exception_handler(Exception): a handler for the base Exception class runs in Starlette's outermost error middleware, outside this one, so its 500 response would bypass the request id header and the status log line.
Timeouts
A model call can hang: a remote feature store does not answer, a large input takes far longer than usual, a GPU queue is full. Without a timeout, the request waits forever, holds a worker, and the client (whose own timeout already fired) has long gone. Give each step a time budget smaller than the client's, and return 504 (or a fallback) when it is exceeded. The SRE lesson on timeouts explains how to choose budgets along a call chain.
import asyncio, httpx
from fastapi import FastAPI, HTTPException
BUDGET_S = 0.05 # the model step's share of the client's deadline
app = FastAPI()
async def call_model(delay_s):
await asyncio.sleep(delay_s) # stands in for a remote feature lookup + model call
return 0.12
@app.get("/v2/predict")
async def predict(delay_ms: int = 0, fallback: bool = False):
try:
p = await asyncio.wait_for(call_model(delay_ms / 1000), timeout=BUDGET_S)
return {"p_default": p, "source": "model"}
except asyncio.TimeoutError:
if fallback:
return {"p_default": 0.08, "source": "fallback: segment average"}
raise HTTPException(status_code=504, detail=f"model step exceeded {int(BUDGET_S * 1000)} ms")
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as c:
for q in ("delay_ms=10", "delay_ms=200", "delay_ms=200&fallback=true"):
r = await c.get(f"/v2/predict?{q}")
print(f"{q:27s} {r.status_code} {r.json()}")
asyncio.run(main())delay_ms=10 200 {'p_default': 0.12, 'source': 'model'}
delay_ms=200 504 {'detail': 'model step exceeded 50 ms'}
delay_ms=200&fallback=true 200 {'p_default': 0.08, 'source': 'fallback: segment average'}
The 10 ms call fits the 50 ms budget; the 200 ms call is cancelled after 50 ms and answered with 504, or with a labelled fallback when the client asks for one. asyncio.wait_for cancels awaitable work (network calls, asyncio.sleep). It cannot interrupt a CPU-bound computation running in the same thread; for that, run the model in a process pool or a separate model server and time out the call to it. A fallback (a cached score, a simple rule, a segment average) is often better than an error, as long as responses say where they came from and monitoring counts how often it happens.
A checklist
| Concern | Mechanism | Status code |
|---|---|---|
| model not loaded yet | lifespan + readiness endpoint | 503 on /health/ready |
| process stuck | liveness endpoint, no model dependency | restart by orchestrator |
| breaking API change | /v1, /v2 routers, retire by traffic |
404 after removal |
| many rows | batch endpoint with max_length |
422 over the limit |
| huge body | middleware size check | 413 |
| invalid input | Pydantic models | 422 |
| slow dependency | asyncio.wait_for, fallback |
504 or fallback |
| known outage | custom exception handler | 503 |
| bug | generic handler, details only in the log | 500 |
The process around the code matters as much: run several replicas behind a load balancer, roll out new versions gradually (deployment strategies), package the service in a small image (Docker for models), and monitor latency, error rates and prediction distributions (monitoring).
Pitfalls
- Readiness that ignores the model. The orchestrator sends traffic to a pod that returns errors for the first 30 s after every restart.
- Liveness that depends on the model or a database. A slow dependency makes the orchestrator kill healthy pods, in a loop.
- Stack traces in responses. They leak internals (paths, library versions, sometimes data); return an id, log the details.
- No limits. A batch of a million rows or a 1 GB body is a denial of service by accident.
- Timeouts longer than the client's. The service keeps working on requests nobody waits for any more.
- Changing a response in place. Removing or renaming a field breaks clients silently; add a version.
Practice
- The model takes 40 s to load. Kubernetes' liveness probe calls
/health/liveafter 10 s and the endpoint returns 503 until the model is loaded. What happens? - A client's timeout is 300 ms. The service calls a feature store and then the model. How would you set the internal timeouts?
- Why does the generic exception handler return a request id?
Answers
- The liveness probe fails while the model loads, Kubernetes restarts the container, the load starts again, and the pod never becomes ready (a restart loop). Liveness must not depend on the model; use readiness for that, and a startup probe with a long enough budget for slow starts.
- Budget below the client's deadline, split by step, for example 100 ms for the feature store, 100 ms for the model, leaving margin for network and serialisation; on a timeout, return a fallback or 504 quickly instead of using the whole 300 ms.
- The client gets no internal details, but can report the id; the log line with the same id has the exception type and message, so the error can be found and fixed.
Test yourself
What should /health/ready return while the model is still loading?
- 200, the process is running
- 503, so the load balancer does not send traffic yet
- 404
- 500
Why keep /v1/predict running after /v2/predict is released?
- For performance
- Existing clients rely on the v1 response format; remove it only when its traffic has gone
- Because FastAPI requires two versions
- To train the model
An unexpected KeyError occurs in an endpoint. What should the client receive?
- The full stack trace
- A 500 with a generic message and a request id; details go to the log
- A 200 with an empty body
- A 422
What can asyncio.wait_for NOT interrupt?
await asyncio.sleep(...)- An awaited network call
- A long CPU-bound computation running in the same thread
- An awaited database query