Sub topic 7
Adding a health check
This chapter assumes you have the main.py from the previous chapters: a FastAPI app that loads model.joblib at startup and serves /predict. You should also know basic HTTP status codes.
Why a service needs a health check
A running process is not always a working service. Uvicorn can be up while the model failed to load, or while the service is still starting. Load balancers, container platforms, and monitoring tools need a cheap way to ask: "Can you take traffic right now?"
A health check is an endpoint that answers that question without running a prediction. The convention is GET /health.
The endpoint you already have
The main.py from earlier includes this route:
@app.get("/health")
def health():
return {"status": "ok", "model_loaded": "iris" in models}It reports whether the models dictionary holds the model. The lifespan function fills that dictionary at startup, so the check ties directly to the model lifecycle.
There is a gap, though. This version always returns HTTP 200, even when model_loaded is false. Most tools read only the status code, so they would treat a broken service as healthy.
Return a failing status when not ready
Change the endpoint so the status code carries the answer. Add JSONResponse to your imports and use this version:
from fastapi.responses import JSONResponse
@app.get("/health")
def health():
loaded = "iris" in models
body = {"status": "ok" if loaded else "unavailable", "model_loaded": loaded}
return JSONResponse(content=body, status_code=200 if loaded else 503)Status 503 means "Service Unavailable". Orchestrators treat any non-2xx response as a failed check and stop sending traffic to that instance.
Liveness and readiness
Platforms such as Kubernetes distinguish two questions.
| Check | Question | Typical failure action |
|---|---|---|
| Liveness | Is the process stuck or broken? | Restart the container |
| Readiness | Can it serve requests now? | Stop routing traffic, keep the process |
The endpoint above is a readiness check, because it fails when the model is missing. A liveness check should be simpler. It should return 200 whenever the process can respond at all. If you used the readiness check for liveness, a slow model load could cause the platform to restart the container repeatedly.
@app.get("/live")
def live():
return {"status": "alive"}What a health check should not do
- Do not run a real prediction on every check. Checks run every few seconds, and the cost adds up.
- Do not call slow external systems unless your service truly cannot work without them.
- Do not expose version details, file paths, or secrets in the response.
How the pieces fit together
Try it
Start the service and call the endpoint with -i to see the status line:
uvicorn main:app --port 8000
curl -i http://localhost:8000/healthYou should see HTTP/1.1 200 OK and "model_loaded":true. To see the failure case, rename model.joblib and restart. Startup will raise an error, so the process exits. That is also useful: a service that cannot load its model fails loudly instead of running half-broken.
Common errors
- Checking
models["iris"]directly. This raisesKeyErrorand returns a 500. Usein. - Testing with
TestClient(app)without thewithblock. Startup does not run, so/healthreports 503. Usewith TestClient(app) as client:. - Pointing a container health check at
/predict. It needs a POST body and fails for the wrong reason.
Exercise
Why should a readiness check return 503 instead of 200 with "model_loaded": false in the body?
Show answer
Load balancers and orchestrators usually read only the status code. A 200 would mark the instance healthy and send it traffic that would fail. A 503 makes them stop routing requests until the model is loaded.
Exercise
Why is it risky to use the model-dependent readiness endpoint as a liveness probe?
Show answer
If the model takes a while to load, the liveness probe fails and the platform restarts the container. The restart begins another slow load, which can repeat forever. A liveness probe should only confirm that the process responds.