Skip to content

Deploying FastAPI under Uvicorn workers in production

Run an ASGI FastAPI app under Uvicorn or Gunicorn-managed Uvicorn workers, terminated by Nginx, with the worker count and lifespan hooks tuned for production.

FastAPI is ASGI, not WSGI, so the deployment shape is different from the Gunicorn-only stack. The runtime that actually speaks HTTP/1.1 and WebSockets to your clients is Uvicorn (or Hypercorn), and there are two reasonable ways to run it in production: plain Uvicorn under systemd, or Uvicorn workers under a Gunicorn master. This article wires both, with Nginx in front and a lifespan hook for clean startup and shutdown.

How to verify

Check what’s running and whether the socket actually answers:

systemctl status fastapi-app --no-pager | head
ss -ltnp | grep -E ':(8000|/run/fastapi)'
curl -i http://127.0.0.1:8000/health
journalctl -u fastapi-app -n 100 --no-pager | tail -40
ps -eo pid,ppid,etime,cmd | grep -E "uvicorn|gunicorn" | head

If curl returns 503 or hangs, the workers are crashing at import — read the full traceback from journald before changing anything else.

What’s happening

Uvicorn is a single-process event-loop server built on uvloop and httptools. One Uvicorn process can saturate one CPU core, and that’s the operational ceiling for a plain uvicorn ... invocation. To use the other cores you either run several Uvicorn processes behind a load balancer, or you let Gunicorn fork N copies of the Uvicorn worker class.

Gunicorn-managed workers is the model most production stacks settle on because Gunicorn handles process supervision, graceful reload on SIGHUP, and max_requests recycling — capabilities Uvicorn’s --workers flag does not match. The async event loop still runs inside each forked Uvicorn worker; the GIL is irrelevant for async I/O because there’s only one Python thread per worker.

The lifespan protocol is the FastAPI/ASGI way to say “open the DB pool before serving traffic, close it on shutdown.” It runs once per worker, not once per app. Anything you open in lifespan is per-process state.

The procedure

  1. Install Uvicorn with the C-speedups and Gunicorn into the project venv:

    /opt/venvs/app/bin/pip install 'uvicorn[standard]' gunicorn
    /opt/venvs/app/bin/uvicorn --version

    uvicorn[standard] pulls uvloop, httptools, websockets, and python-dotenv — the production runtime, not the pure-Python fallback.

  2. Add a lifespan to your FastAPI app so resources open and close per worker. In app/main.py:

    from contextlib import asynccontextmanager
    from fastapi import FastAPI
    from .db import engine, dispose_engine
    
    @asynccontextmanager
    async def lifespan(app: FastAPI):
        # Startup
        await engine.connect()
        yield
        # Shutdown
        await dispose_engine()
    
    app = FastAPI(lifespan=lifespan)
  3. Write /etc/gunicorn/fastapi-app.conf.py:

    bind = "unix:/run/fastapi-app.sock"
    workers = 4
    worker_class = "uvicorn.workers.UvicornWorker"
    timeout = 60
    graceful_timeout = 30
    keepalive = 5
    max_requests = 2000
    max_requests_jitter = 200
    accesslog = "-"
    errorlog = "-"

    Worker count for an async app is closer to CPU cores than 2 × CPU + 1 — async workers don’t block on I/O, so over-provisioning just thrashes the scheduler.

  4. Create the systemd unit at /etc/systemd/system/fastapi-app.service:

    [Unit]
    Description=FastAPI app (Uvicorn workers under Gunicorn)
    After=network.target
    
    [Service]
    User=deploy
    Group=www-data
    WorkingDirectory=/var/www/fastapi-app
    RuntimeDirectory=fastapi-app
    RuntimeDirectoryMode=0750
    Environment=PYTHONUNBUFFERED=1
    EnvironmentFile=/etc/fastapi-app/env
    ExecStart=/opt/venvs/app/bin/gunicorn -c /etc/gunicorn/fastapi-app.conf.py app.main:app
    ExecReload=/bin/kill -s HUP $MAINPID
    KillMode=mixed
    Restart=on-failure
    RestartSec=2
    
    [Install]
    WantedBy=multi-user.target
  5. Reload and start:

    sudo systemctl daemon-reload
    sudo systemctl enable --now fastapi-app
    curl --unix-socket /run/fastapi-app.sock http://localhost/health
  6. In Nginx, terminate TLS and proxy to the socket. Add WebSocket headers if any route uses them:

    location / {
      proxy_pass http://unix:/run/fastapi-app.sock;
      proxy_http_version 1.1;
      proxy_set_header Host $host;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection $connection_upgrade;
      proxy_read_timeout 60s;
    }

    $connection_upgrade requires a map at the http block — without it, WebSocket upgrades silently drop to HTTP/1.0.

Common pitfalls

  • Running uvicorn --workers 4 directly: it forks but has no graceful reload, no max_requests, and no ExecReload integration. Use it only for dev or single-process containers; everywhere else, put Gunicorn in front.
  • Mixing sync def and async def routes without run_in_threadpool — sync routes block the event loop and a single slow handler stalls every other request in that worker. Either keep all routes async, or expect to tune --threads and accept the cost.
  • Forgetting to set proxy_set_header Host $host — FastAPI’s request.url returns the upstream socket path instead of the public hostname, and OAuth redirects break.
  • max_requests recycles workers on a counter, not a timer. A worker with a leak that triggers only on a specific endpoint may never hit the count under low traffic — pair this with a cron-driven systemctl reload if you’ve seen leaks in observability.
  • Heavy CPU work in an async handler (image resize, JSON parse of a 50 MB payload) blocks the loop. Offload to concurrent.futures.ProcessPoolExecutor or move to a worker queue.

For the worker-queue side of the same application — Celery on Redis — see Celery with a Redis backend. Stack Harbor’s managed operations practice runs Gunicorn-managed Uvicorn workers behind Nginx as the default ASGI shape, with Prometheus scraping /metrics and journald handling rotation.