FastAPI health and readiness endpoints

Python
import shutil
import time

from fastapi import FastAPI, Response, status

# Run with: uvicorn main:app --reload
app = FastAPI(title="Service health")
STARTED = time.monotonic()


def disk_ready(minimum_free_gb: float = 0.5) -> bool:
    """Return True when the filesystem still has enough free space."""
    return shutil.disk_usage("/").free / 1e9 >= minimum_free_gb


@app.get("/healthz")
def healthz() -> dict:
    """Liveness probe: cheap, checks only that the process responds."""
    return {"status": "ok", "uptime_seconds": round(time.monotonic() - STARTED, 1)}


@app.get("/readyz")
def readyz(response: Response) -> dict:
    """Readiness probe: replies 503 while a dependency is unavailable."""
    ready = disk_ready()
    if not ready:
        response.status_code = status.HTTP_503_SERVICE_UNAVAILABLE
    return {"ready": ready, "disk": "ok" if ready else "low space"}