Skip to content

Lesson 8 of 9 · 23m

Deploying FastAPI: ASGI Servers, Workers, and Safe Rollout

How uvicorn, gunicorn, containers, reverse proxies, health checks, and graceful shutdown fit together — and the deployment defaults that cause mysterious production behavior.

FastAPI is an application framework, not a deployment architecture. Production usually means an ASGI server such as uvicorn behind a process manager or container orchestrator, behind a reverse proxy or load balancer. Every one of those layers owns part of correctness.

Choose the process model deliberately

For modern async services, uvicorn workers are common:

uvicorn app.main:app --host 0.0.0.0 --port 8000 --workers 4

Gunicorn with uvicorn.workers.UvicornWorker is still used in environments that want gunicorn's process management:

gunicorn app.main:app   --worker-class uvicorn.workers.UvicornWorker   --workers 4 --bind 0.0.0.0:8000

Worker count is not magic. Start near CPU count for CPU-bound work, but I/O-heavy async apps often need fewer workers and better concurrency discipline than synchronous services. Measure memory and event-loop saturation rather than copying a formula.

Async does not make blocking safe

An async endpoint that calls synchronous database drivers or CPU-heavy work blocks the event loop for every concurrent request on that worker. Use truly async libraries or push blocking work to a thread pool / job system deliberately. This is the most common reason a service looks scalable in a hello-world benchmark and collapses in production.

Put timeouts at every layer

There is no universal timeout. The client, load balancer, reverse proxy, ASGI server, database driver, and external HTTP client all have their own. Align them so inner timeouts fire first and outer layers do not retry after the application gave up. A hanging request is often a missing timeout, not a slow dependency.

Health checks are two different endpoints

Liveness means 'the process is not dead.' Readiness means 'this instance should receive traffic.' Do not make liveness depend on every downstream service; otherwise a database outage restarts all your healthy API pods. Readiness can check critical dependencies, but keep it cheap.

@app.get("/healthz")
def healthz():
    return {"ok": True}

@app.get("/readyz")
def readyz(db=Depends(get_db)):
    db.execute(text("SELECT 1"))
    return {"ready": True}

Graceful shutdown is a feature

Deployments terminate processes. Configure pre-stop delays or orchestration termination grace periods so the balancer stops sending traffic before workers exit. Finish in-flight requests where possible, close database pools, and stop accepting new work. Background jobs need separate consumer shutdown logic.

Proxy headers are security-sensitive

Only trust X-Forwarded-For and X-Forwarded-Proto from proxies you control. Configure uvicorn's --proxy-headers or trusted host middleware appropriately. Blindly trusting forwarded headers lets clients spoof IP addresses and URLs.

Field notes

  • --reload is development-only. If it exists in production configuration, remove it.
  • Pin dependencies and image digests; 'latest' is an uncontrolled deployment.
  • Log at the edge whether HTTP/2, websockets, or compression is actually supported through every proxy layer.
  • Rollout strategy matters: use rolling or canary deploys for API compatibility risk, not because the orchestrator defaults to it.

Was this lesson helpful?

Sign in to rate