Part 09 / Topic 5 of 7
Health and readiness checks
The first thing Acme's platform team will ask of your service is not a feature — it is "where are the health endpoints?" Their orchestrator restarts and routes based on them:
# examples/02_health_and_readiness_endpoints_for_the.py
from fastapi import FastAPI, Response
from fastapi.testclient import TestClient
app = FastAPI()
deps = {"database": True, "acme_api": False}
@app.get("/healthz") # liveness: is the process up?
def healthz():
return {"status": "ok"}
@app.get("/readyz") # readiness: can it serve traffic right now?
def readyz(response: Response):
failing = [name for name, ok in deps.items() if not ok]
if failing:
response.status_code = 503
return {"ready": not failing, "failing": failing}
c = TestClient(app)
print(c.get("/healthz").status_code, c.get("/healthz").json())
r = c.get("/readyz"); print(r.status_code, r.json())
# 200 {'status': 'ok'}
# 503 {'ready': False, 'failing': ['acme_api']}
Liveness (/healthz): the process is alive and not hung — if this fails, the platform restarts it. Readiness (/readyz): it can serve traffic right now, dependencies included — if this fails, the platform stops routing to it but leaves it running. One judgment call the example's output invites: only fail readiness for dependencies the service truly cannot work without. If acme_api being down just degrades one endpoint, a circuit breaker (Part 11) with clear errors often beats taking the whole service out of rotation.
🧪 Quick quiz
- What is the difference between
/healthzand/readyz?
Show the answer
healthz: the process is alive. readyz: it can serve traffic now, with its dependencies up — the example returned 200 and 503 respectively. Only fail readiness for dependencies the service truly cannot work without. (verified against the example output above)
Done here? The practice set for Part 9 — 4 exercises with solutions — is on the part page.