Sub topic 7
Adding a health check
This chapter assumes you have the FastAPI service from the earlier chapters. That means a main.py that loads model.joblib in a lifespan function, a /predict endpoint, and a models dictionary. You should also know what an HTTP status code is. By the end, the service will report whether it is alive and whether it can serve predictions, and a test will check both.
Why a service needs a health check
A running process is not always a working service. A model API can fail while the process stays up. The model may still be loading, the model file may be corrupt, or memory may be exhausted so that every request fails.
Other programs need a cheap way to ask whether the service is fine. Load balancers use it to decide where to send traffic. Container runtimes use it to decide whether to restart a container. Deployment tools use it to wait for a new version before they stop the old one. They all do the same thing. They call a URL and read the status code.
The /health endpoint from the earlier chapters has two weaknesses:
- It returns HTTP 200 even when
model_loadedisfalse. Callers that only check the status code will be told the service is fine. - It mixes two questions: "is the process running?" and "can it answer prediction requests?"
Liveness and readiness
Orchestrators such as Kubernetes separate these two questions, and the split is useful even if you never use Kubernetes.
| Check | Question | Typical failure response | What the caller does on failure |
|---|---|---|---|
| Liveness | Is the process running and responding at all? | No response, or 500 | Restart the container |
| Readiness | Can this instance handle prediction traffic now? | 503 Service Unavailable | Stop sending traffic, but do not restart |
The difference matters because the responses differ. If a slow model load makes the readiness check fail, restarting the container would only restart the load. The correct action is to wait. If the liveness check fails, the process is stuck and a restart is the right fix.
Keep the liveness check trivial. It should not touch the model. If it did, a model problem would trigger restarts that cannot fix it.
Implementing the two endpoints
Replace the old /health route in main.py with the two routes below. Update the import line to include Response and status.
from fastapi import FastAPI, Response, status
@app.get("/health/live")
def live():
return {"status": "ok"}
@app.get("/health/ready")
def ready(response: Response):
loaded = "iris" in models
if not loaded:
response.status_code = status.HTTP_503_SERVICE_UNAVAILABLE
return {
"status": "ready" if loaded else "unavailable",
"model_loaded": loaded,
}The readiness route takes a Response parameter. FastAPI lets you change the status code on it while still returning a normal dictionary. The body stays useful to a person who calls the URL with curl, and the status code gives automated callers a signal they can act on without parsing JSON.
Start the service and check both routes:
uvicorn main:app --port 8000
curl -i http://localhost:8000/health/live
curl -i http://localhost:8000/health/readyWith the model loaded, both calls return 200 OK. The -i flag prints the status line, which is the part health checkers read.
What a failed startup looks like
Look again at the lifespan function. FastAPI does not serve any request until the code before yield has finished. Two cases follow from that:
- If
joblib.loadraises an exception, the application fails to start and Uvicorn exits. No endpoint answers, including the health checks. The caller sees a refused connection or a crashed container, not a 503. - If
joblib.loadis slow, the port is not yet accepting connections. Early health checks fail with a connection error, not a 503.
With this design, the "iris" in models condition will almost never be false while the server is answering requests. The check still earns its place. It protects you if you later move loading into a background task to start faster, and it documents the contract. The more important point is that a connection error from a readiness probe means "not ready yet", exactly as a 503 does. Configure probes to treat both the same way.
Going deeper: a smoke prediction
Checking that the model object exists does not prove it works. A corrupted artifact, or a library version that no longer matches the one used for training, can load but fail on the first call. A deeper readiness check runs one fixed prediction:
def model_can_predict() -> bool:
model = models.get("iris")
if model is None:
return False
try:
model.predict([[5.1, 3.5, 1.4, 0.2]])
except Exception:
return False
return True
@app.get("/health/ready")
def ready(response: Response):
ok = model_can_predict()
if not ok:
response.status_code = status.HTTP_503_SERVICE_UNAVAILABLE
return {"status": "ready" if ok else "unavailable", "model_loaded": ok}The cost is that the check does real work on every call. For a small random forest this takes about a millisecond. For a large model it could take long enough to compete with real traffic, and a probe that runs every few seconds on every replica adds up. Some options:
- Run the smoke prediction once at the end of the startup code and store the result in a variable. The readiness route then reads the variable.
- Run it periodically in a background task.
- Keep the cheap
in modelscheck and rely on tests and deployment checks to catch broken artifacts.
Pick based on model cost. The key rule is that a health check must be much cheaper than the work it protects.
Testing the health checks
A test confirms that readiness changes with the application lifecycle. The TestClient only runs the lifespan code when you use it as a context manager. This gives a convenient way to test both states:
from fastapi.testclient import TestClient
from main import app
def test_live_always_ok():
client = TestClient(app)
assert client.get("/health/live").status_code == 200
def test_ready_after_startup():
with TestClient(app) as client:
response = client.get("/health/ready")
assert response.status_code == 200
assert response.json()["model_loaded"] is True
def test_not_ready_without_startup():
client = TestClient(app)
response = client.get("/health/ready")
assert response.status_code == 503The last test builds a client without the with block, so startup never runs and models is empty. This reproduces the "not loaded" state without any mocking. It relies on the models.clear() call after yield, which resets the dictionary when an earlier test's with block exits.
Using the check outside your code
Most platforms accept the same URL. Docker can run a check inside the container. The slim Python image has no curl, so use Python itself:
HEALTHCHECK --interval=10s --timeout=3s --start-period=20s --retries=3 \
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health/ready', timeout=2)"urlopen raises an error on a 503 status, so the command exits with a non-zero code and Docker counts a failure. The --start-period gives the model time to load before failures count against the container. A later chapter on containers places this line in the full Dockerfile.
On Kubernetes, the same two URLs map to two probe types:
livenessProbe:
httpGet:
path: /health/live
port: 8000
periodSeconds: 10
readinessProbe:
httpGet:
path: /health/ready
port: 8000
periodSeconds: 5
failureThreshold: 3Common mistakes
- Returning 200 with an error in the body. Callers read the status code first. Use 503 when the service cannot take traffic.
- Using the readiness URL for liveness. A slow model load then causes restart loops, and the model never finishes loading.
- Making the check expensive. Probes run often on every replica, so a heavy check becomes a source of load and latency.
- Exposing internal details. The health body should not include file paths, library versions, or stack traces. If the endpoint is reachable from outside your network, keep the output minimal.
- Forgetting the start period. A probe that begins immediately will fail while the model loads and may get the container killed. Set a start delay or failure threshold that covers the load time.
Exercise
Your model takes 40 seconds to load. A teammate sets a liveness probe on /health/ready with a 10-second timeout and 3 retries. What happens when the container starts, and how would you fix it?
Show answer
The probe fails during the 40-second load, because the port is not accepting connections or readiness returns 503. After about 30 seconds of failures the platform treats the container as dead and restarts it. The restart begins the load again, so the container never becomes healthy. Fix it in two ways. Point the liveness probe at /health/live, which does not depend on the model. Then give the readiness probe a start delay or a failure threshold longer than the load time, such as a 40-second --start-period in Docker.
Exercise
Write a test that proves /health/ready returns 503 when the model has been removed from the models dictionary after startup.
Show answer
Use the context-manager client, remove the entry inside the block, and call the endpoint. from fastapi.testclient import TestClient from main import app, models def testreadyfailswhenmodelmissing(): with TestClient(app) as client: models.pop("iris") response = client.get("/health/ready") assert response.statuscode == 503 assert response.json()["model_loaded"] is False