← Back to FastAPI, page 2

fastapi-0038 · Hard senior

How would you deploy a FastAPI service to production? Cover processes, containers, proxies, health checks and graceful shutdown.

Package the app in a small container that runs Uvicorn (or fastapi run) as a non-root user, one or a few worker processes per container, scaled horizontally behind a load balancer that terminates TLS. Trust forwarded headers only from the proxy, restrict hosts, set body size limits, expose liveness and readiness endpoints, load configuration from the environment, log to stdout, run migrations as a separate job, and let SIGTERM drain in-flight requests before the process exits.

Full answer

A production setup has several layers. A typical one:

Load balancer or ingress

  • Terminates TLS, routes to healthy instances, enforces request size and timeouts, may add a WAF and rate limits.
  • Forwards X-Forwarded-For and X-Forwarded-Proto. Run Uvicorn with --proxy-headers --forwarded-allow-ips=<proxy IPs> so request.client.host and request.url.scheme are correct, and only trust these headers from the proxy.

Application processes

  • Kubernetes or another orchestrator: often one Uvicorn process per container and many replicas, so the orchestrator handles restarts and scaling. On a VM: uvicorn --workers N or Gunicorn with Uvicorn workers.
  • Async apps doing I/O can handle many concurrent requests per process; CPU-bound work needs more processes or offloading.

Container image

  • Slim Python base image, dependencies installed in a separate layer (or with uv for speed), app code copied last.
  • Non-root user, no secrets baked in, exec-form CMD ["fastapi", "run", "app/main.py", "--port", "8000", "--proxy-headers"] so SIGTERM reaches the server.

Configuration and secrets: environment variables via pydantic-settings, secrets from a secret manager or orchestrator secrets.

Health checks

  • Liveness: "is the process alive?" Cheap, no dependency checks, or a stuck database would restart every pod.
  • Readiness: "can it serve traffic?" Checks the database pool and required services; the load balancer stops sending traffic when it fails.

Graceful shutdown: on SIGTERM, Uvicorn stops accepting connections and waits for in-flight requests (bounded by --timeout-graceful-shutdown), then lifespan shutdown closes pools. Set the orchestrator's termination grace period longer than this. Kubernetes may send traffic for a short time after SIGTERM, so a small pre-stop delay helps.

Safety settings: TrustedHostMiddleware with allowed hosts, request body limits (recent FastAPI versions accept max_body_size on the app or a route; also limit at the proxy), disable or protect /docs if the API is not public.

Release process: run Alembic migrations as a separate job before rolling out, keep schema changes backward compatible, roll out gradually (rolling or canary), and watch error rate and latency dashboards.

Observability: structured JSON logs to stdout, metrics (Prometheus or OpenTelemetry), tracing, and alerts on p95 latency and 5xx rates.

python
from contextlib import asynccontextmanager

from fastapi import FastAPI, Request, Response
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from fastapi.testclient import TestClient
from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware

state = {"db_ready": False}


@asynccontextmanager
async def lifespan(app: FastAPI):
    state["db_ready"] = True          # open the database pool here
    yield
    state["db_ready"] = False         # close it here during graceful shutdown


app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, max_body_size=1_000_000)
app.add_middleware(TrustedHostMiddleware, allowed_hosts=["api.college.edu", "testserver"])


@app.get("/livez")
def livez():
    return {"status": "alive"}


@app.get("/readyz")
def readyz(response: Response):
    if not state["db_ready"]:
        response.status_code = 503
        return {"status": "not ready"}
    return {"status": "ready"}


@app.get("/whoami")
def whoami(request: Request):
    return {"client": request.client.host, "scheme": request.url.scheme}


@app.post("/upload")
async def upload(request: Request):
    return {"bytes": len(await request.body())}


asgi = ProxyHeadersMiddleware(app, trusted_hosts=["10.0.0.5"])   # what --proxy-headers enables

print("before startup:", TestClient(app).get("/readyz").status_code)
with TestClient(asgi, base_url="http://api.college.edu", client=("10.0.0.5", 5000)) as c:
    print(c.get("/livez").json(), c.get("/readyz").json())
    print(c.get("/whoami", headers={"X-Forwarded-For": "203.0.113.9", "X-Forwarded-Proto": "https"}).json())
    print(c.get("/livez", headers={"Host": "evil.example"}).status_code)
    print(c.post("/upload", content=b"x" * 2_000_000).status_code)

with TestClient(ProxyHeadersMiddleware(app, trusted_hosts=["10.0.0.5"]), client=("198.51.100.7", 5000)) as c:
    print("untrusted proxy:", c.get("/whoami", headers={"X-Forwarded-For": "203.0.113.9"}).json())

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. ProxyHeadersMiddleware is the same middleware Uvicorn adds for --proxy-headers; client=(...) sets the TCP peer address TestClient reports. max_body_size needs a recent FastAPI release (verified on 0.165). 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 {'status': 'alive'} {'status': 'ready'} {'client': '203.0.113.9', 'scheme': 'https'} 400 413 untrusted proxy: {'client': '198.51.100.7', 'scheme': 'http'}

Key points

  • Container: slim image, non-root, exec-form CMD
  • One process per container with replicas, or --workers on VMs
  • Trust proxy headers only from the proxy; TrustedHostMiddleware
  • Separate liveness and readiness checks
  • SIGTERM drains requests; migrations run as a separate job

Common mistakes

  • Trusting X-Forwarded-For from any client, which lets callers fake their IP
  • Making liveness checks depend on the database and restart-looping every pod during an outage
  • Using the shell form of CMD so SIGTERM never reaches Uvicorn
  • Running migrations at container startup from every replica
  • Baking secrets into the image

Follow-ups

  • How would you roll out a breaking database change with zero downtime?
  • How many Uvicorn workers per container would you run on Kubernetes, and why?
  • What should a readiness check verify?

Tips

  • Walk the request path from load balancer to process
  • Separate liveness from readiness
  • Mention graceful shutdown and proxy header trust explicitly