Script Valley
FastAPI: Build Production Python APIs
Production DeploymentLesson 6.4

How to add health check and readiness endpoints to FastAPI

health check endpoint, readiness vs liveness, database ping, dependency check, Kubernetes probes, load balancer health checks, startup events, health response schema

Health Check Endpoints

Load balancers and Kubernetes need health endpoints to know when to route traffic to your app. A liveness probe checks if the app is running. A readiness probe checks if it can serve traffic (e.g., database connected).

Basic health endpoint

from fastapi import FastAPI
from sqlalchemy import text
from .database import SessionLocal

app = FastAPI()

@app.get("/health")
def health():
    return {"status": "ok"}

@app.get("/health/ready")
def readiness():
    try:
        db = SessionLocal()
        db.execute(text("SELECT 1"))
        db.close()
        return {"status": "ready", "database": "ok"}
    except Exception as e:
        raise HTTPException(
            status_code=503,
            detail={"status": "not ready", "database": str(e)}
        )

/health always returns 200 if the process is alive — Kubernetes uses this as the liveness probe and restarts the container if it fails. /health/ready returns 503 if the database is unreachable — Kubernetes stops sending traffic to the pod until it recovers.

Keep health endpoints fast. Never run expensive queries in them. The SELECT 1 ping is sufficient to verify connectivity. Add Redis and any other critical dependencies to the readiness check.

Up next

How to deploy FastAPI with Gunicorn and Uvicorn workers in production

Sign in to track progress