← Back to FastAPI, page 5

fastapi-0099 · Hard senior

How do you run FastAPI in production with Gunicorn and UvicornWorker, and which settings matter for workers, timeouts and graceful restarts?

Gunicorn acts as a process manager that forks several Uvicorn worker processes (class uvicorn_worker.UvicornWorker, from the uvicorn-worker package), restarts crashed workers and handles signals. Key settings are workers (about one per CPU core to start), timeout (heartbeat) and graceful_timeout, keepalive, max_requests with jitter against memory growth, preload_app for copy-on-write memory savings, and bind to a socket or port behind a reverse proxy. In containers, many teams run plain Uvicorn per container and scale with the orchestrator instead.

Full answer

Why a manager: a single Uvicorn process uses one CPU core (the event loop is single threaded). Multiple processes use all cores and provide crash recovery.

Options:

  • uvicorn app:app --workers 4: simple supervisor built in. Fine for many cases; fewer production knobs.
  • gunicorn -k uvicorn_worker.UvicornWorker app:app: mature process management (rolling restarts with SIGHUP, max_requests, worker timeouts, hooks). The old uvicorn.workers module is deprecated in favour of the separate uvicorn-worker package.
  • Containers on Kubernetes or ECS: often one Uvicorn process per container with resource limits and replicas for scaling, so the orchestrator handles restarts and rolling updates. Multiple workers per container make CPU limits and memory accounting less precise.

Important Gunicorn settings (gunicorn.conf.py):

  • workers: start around CPU cores (or 2 x cores + 1 for sync apps; async apps need fewer). Each worker loads the app, so memory is multiplied.
  • worker_class = "uvicorn_worker.UvicornWorker".
  • bind: 0.0.0.0:8000 in containers or a unix socket behind nginx.
  • timeout: with async workers it is a heartbeat from the worker to the master (default 30 s); a blocked event loop that stops heartbeating gets killed. It is not a per-request limit.
  • graceful_timeout: time workers get to finish in-flight requests on restart or shutdown.
  • keepalive: keep-alive seconds, set above the load balancer's idle timeout to avoid 502s on reused connections.
  • max_requests and max_requests_jitter: recycle workers periodically to contain slow leaks, staggered so they do not all restart together.
  • preload_app: import the app in the master before forking to share memory (copy-on-write); do not open database pools or threads at import time, create them in lifespan.
  • forwarded_allow_ips or Uvicorn --forwarded-allow-ips behind a proxy.
  • Logging: send access and error logs to stdout and stderr for the platform.

Shutdown: SIGTERM makes the master stop accepting, wait up to graceful_timeout, run lifespan shutdown in each worker, then exit. Match the orchestrator's termination grace period to this. Health checks, readiness and resource limits complete the setup.

python
import os
import signal
import socket
import subprocess
import sys
import tempfile
import textwrap
import time
from pathlib import Path

import httpx

work = Path(tempfile.mkdtemp())
with socket.socket() as s:
    s.bind(("127.0.0.1", 0))
    port = s.getsockname()[1]

(work / "main.py").write_text(textwrap.dedent("""
    import os
    from fastapi import FastAPI
    app = FastAPI()

    @app.get("/ping")
    async def ping():
        return {"pong": True}
"""))
(work / "gunicorn.conf.py").write_text(textwrap.dedent(f"""
    bind = "127.0.0.1:{port}"
    workers = 2
    worker_class = "uvicorn_worker.UvicornWorker"
    timeout = 30
    graceful_timeout = 20
    keepalive = 75
    max_requests = 1000
    max_requests_jitter = 100
    accesslog = None
    errorlog = "-"
    loglevel = "warning"
"""))

check = subprocess.run([sys.executable, "-m", "gunicorn", "--check-config", "-c", "gunicorn.conf.py", "main:app"],
                       cwd=work, capture_output=True, text=True)
print("config check exit code:", check.returncode)

proc = subprocess.Popen([sys.executable, "-m", "gunicorn", "-c", "gunicorn.conf.py", "main:app"],
                        cwd=work, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
    deadline = time.time() + 30
    while time.time() < deadline:
        try:
            reply = httpx.get(f"http://127.0.0.1:{port}/ping", timeout=1)
            break
        except httpx.TransportError:
            time.sleep(0.2)
    print("response:", reply.status_code, reply.json())
    while time.time() < deadline:
        children = Path(f"/proc/{proc.pid}/task/{proc.pid}/children").read_text().split()
        if len(children) == 2:
            break
        time.sleep(0.2)
    print("worker processes under the master:", len(children))
finally:
    proc.send_signal(signal.SIGTERM)                       # graceful shutdown
    print("master exit code after SIGTERM:", proc.wait(timeout=30))

Standalone script that starts a real Gunicorn server on a free local port, calls it once and stops it. Linux only (it reads /proc). Requires `pip install fastapi gunicorn uvicorn-worker httpx`. 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, gunicorn 27.0.1, uvicorn-worker 0.4.0): config check exit code: 0 response: 200 {'pong': True} worker processes under the master: 2 master exit code after SIGTERM: 0

Key points

  • Gunicorn manages processes; UvicornWorker runs the ASGI app
  • Use the uvicorn-worker package; uvicorn.workers is deprecated
  • timeout is a heartbeat for async workers, not a request limit
  • max_requests with jitter recycles workers; keepalive above the LB idle time
  • In containers, one Uvicorn per container with orchestrator scaling is common

Common mistakes

  • Running many workers per container with tight CPU limits
  • Treating Gunicorn timeout as a per-request limit
  • Opening pools at import time with preload_app
  • keepalive lower than the load balancer idle timeout causing 502s
  • Using the deprecated uvicorn.workers module

Follow-ups

  • When would you choose plain Uvicorn per container?
  • What does preload_app change?
  • How do you do zero-downtime deploys with Gunicorn?

Tips

  • Explain why a process manager
  • Name 4 settings
  • Mention graceful shutdown