← Back to FastAPI, page 4

fastapi-0080 · Medium mid

How do you design liveness, readiness and startup health endpoints in FastAPI, and how do they interact with shutdown?

Liveness answers "is the process alive and not deadlocked?" and should be cheap with no dependencies; if it fails the platform restarts the container. Readiness answers "can this instance serve traffic now?" and checks critical dependencies (database, cache) with short timeouts; if it fails the instance is removed from the load balancer without a restart. Mark the app not ready during shutdown so the load balancer drains it before the server stops.

Full answer

Probes serve different decisions:

  • Liveness (/livez): returns 200 if the event loop responds. Do not check the database here: a database outage would make the platform restart all pods, making things worse.
  • Readiness (/readyz): returns 200 only if the instance can do useful work: start-up finished, database reachable (SELECT 1 with a 1 to 2 second timeout), required caches or queues available. Return 503 with a JSON body listing which checks failed.
  • Startup probe (platform feature): gives slow start-ups (cache warming, migrations) more time before liveness begins.

Implementation notes:

  • Keep a state object set in lifespan: ready=True after resources open, ready=False at shutdown start. The readiness endpoint reads it.
  • Run dependency checks with timeouts (asyncio.wait_for) so a hanging database does not hang the probe, and cache results for a few seconds to avoid hammering dependencies on busy clusters.
  • Use include_in_schema=False and keep health endpoints out of authentication, access logs noise and rate limits.
  • Return minimal information publicly; detailed dependency status can leak internals. Use an internal port or authenticated route for diagnostics.
  • Health must be fast; do not run heavy queries.

Graceful shutdown sequence on deploy: SIGTERM arrives; mark not ready; the load balancer stops sending new requests (allow a delay equal to probe interval times failure threshold); in-flight requests finish within the server's graceful timeout (--timeout-graceful-shutdown in Uvicorn); lifespan shutdown closes pools; process exits. Configure the platform's termination grace period to exceed these timers.

Also expose build version and git SHA in a separate /version endpoint to help debugging rollouts.

python
import asyncio
from contextlib import asynccontextmanager

from fastapi import FastAPI, Response
from fastapi.testclient import TestClient

state = {"ready": False, "db_up": True}


async def check_database():
    await asyncio.sleep(0)
    if not state["db_up"]:
        raise ConnectionError("database unreachable")


@asynccontextmanager
async def lifespan(app: FastAPI):
    state["ready"] = True                                   # resources are open
    yield
    state["ready"] = False                                  # begin draining


app = FastAPI(lifespan=lifespan)


@app.get("/livez", include_in_schema=False)
async def livez():
    return {"status": "alive"}                              # no dependency checks here


@app.get("/readyz", include_in_schema=False)
async def readyz(response: Response):
    checks = {"startup": "ok" if state["ready"] else "not ready"}
    if state["ready"]:
        try:
            await asyncio.wait_for(check_database(), timeout=1)
            checks["database"] = "ok"
        except (ConnectionError, asyncio.TimeoutError) as exc:
            checks["database"] = f"failed: {exc}"
    if any(v != "ok" for v in checks.values()):
        response.status_code = 503
    return {"checks": checks}


c = TestClient(app)
print("before startup:", c.get("/readyz").status_code, c.get("/readyz").json())
with TestClient(app) as running:
    print("running:", running.get("/readyz").status_code, running.get("/livez").json())
    state["db_up"] = False
    r = running.get("/readyz")
    print("database down:", r.status_code, r.json(), "| still alive:", running.get("/livez").status_code)
    state["db_up"] = True
print("after shutdown:", state["ready"])
print("hidden from docs:", [p for p in c.get("/openapi.json").json()["paths"]])

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): before startup: 503 {'checks': {'startup': 'not ready'}} running: 200 {'status': 'alive'} database down: 503 {'checks': {'startup': 'ok', 'database': 'failed: database unreachable'}} | still alive: 200 after shutdown: False hidden from docs: []

Key points

  • Liveness is cheap and dependency-free; readiness checks dependencies
  • Failing liveness restarts; failing readiness only removes from traffic
  • Mark not ready at shutdown to drain traffic
  • Use timeouts and brief caching for dependency checks
  • Keep health routes out of the schema and out of auth

Common mistakes

  • Checking the database in the liveness probe and causing restart storms
  • No timeout on dependency checks so probes hang
  • Not marking the instance unready before shutdown
  • Exposing detailed internals on public health routes
  • Heavy queries inside health checks

Follow-ups

  • How long should the termination grace period be?
  • What does a startup probe add?
  • How would you check a message broker without overloading it?

Tips

  • Contrast liveness and readiness
  • Describe the shutdown sequence
  • Mention timeouts