Skip to content

Python Gunicorn worker class + count on PaaS — sync vs gthread vs uvicorn

How to pick the right Gunicorn worker class and how many workers to run inside a PaaS container, with copy-pasteable gunicorn.conf.py for Django, Flask, and FastAPI.

Your Django app sits behind Gunicorn in a 2 GiB / 2 vCPU PaaS container. Someone read a blog post recommending workers = (2 × cores) + 1, set it to 5, and now p95 latency is bouncing between 80 ms and 4 s depending on which worker picks up the request. Memory hovers near the limit. The app does database calls plus two outbound HTTP calls per request. Five sync workers is the wrong shape for that workload, and the symptoms are exactly what you’d expect from it.

What’s happening

Gunicorn’s worker model is a process pre-fork, with one of several concurrency strategies inside each worker process:

  • sync — one request at a time, blocks the whole process. Workers = concurrency. Fine for fast CPU-bound endpoints. Disastrous when a request spends most of its time waiting on a downstream HTTP call, because four other workers can’t help the blocked one.
  • gthread — one worker process, N threads inside. Concurrency = workers × threads. Good middle ground for I/O-bound WSGI apps. Subject to the Python GIL, so adding threads doesn’t help CPU-bound work, but it lets a single worker handle a dozen slow database queries concurrently.
  • uvicorn.workers.UvicornWorker — ASGI worker built on asyncio. Required for FastAPI / Starlette / async Django. Each worker handles thousands of concurrent connections cooperatively; throughput is bounded by the event loop, not by thread count.
  • gevent / eventlet — monkey-patched cooperative coroutines for legacy WSGI code. Works but surprising — any unpatched C extension that blocks (some database drivers, some image libraries) blocks the whole worker.

The rule of thumb most operators internalize — (2 × cores) + 1 — assumes you have a sync WSGI app that’s roughly 50/50 CPU and I/O. The moment your endpoints make outbound calls, that rule overprovisions memory (each worker is a full Python interpreter, often 80-200 MiB) and underdelivers concurrency. A FastAPI app should run one uvicorn worker per core with 1000-2000 concurrent connections, not nine sync workers.

How to verify

Look at three signals before changing anything.

# 1. What's the per-worker memory footprint
ps -o pid,rss,cmd -C gunicorn --no-headers | awk '{rss+=$2; n++} END {print n" workers, avg RSS "(rss/n/1024)" MiB"}'

# 2. What fraction of request time is the worker blocked on I/O
# (run a few minutes of py-spy against a worker pid)
py-spy top --pid $(pgrep -f 'gunicorn.*worker' | head -1) --duration 60 --rate 100

# 3. How long are requests waiting for a worker
# Gunicorn exposes this via the statsd output if you've wired it
gunicorn --statsd-host localhost:8125 --statsd-prefix app ...

py-spy top is the diagnostic that ends the argument. If 70% of CPU time is in socket.recv or select, you’re I/O-bound — switch to gthread or uvicorn. If 90% is in your handler code, you’re CPU-bound — stick with sync, and adding threads won’t help (GIL).

A second check: the request queue. If your platform shows a load balancer with growing connection counts but worker CPU at 30%, the queue is full and workers are blocked on something. Add concurrency, not workers.

The fix

Pick the framework, then the matching gunicorn.conf.py. All three of these run on 2 vCPU / 2 GiB.

Django (WSGI, I/O-bound with downstream calls):

# gunicorn.conf.py
import os
import multiprocessing

bind = "0.0.0.0:8000"
workers = int(os.getenv("WEB_CONCURRENCY", multiprocessing.cpu_count()))
worker_class = "gthread"
threads = int(os.getenv("GUNICORN_THREADS", "8"))
worker_tmp_dir = "/dev/shm"

# Connection lifecycle
keepalive = 5
timeout = 60
graceful_timeout = 30

# Restart workers periodically to bound memory growth
max_requests = 1000
max_requests_jitter = 200

# Preload the app — copy-on-write saves memory across workers
preload_app = True

# Observability
accesslog = "-"
errorlog = "-"
access_log_format = '%(t)s %(h)s "%(r)s" %(s)s %(b)s %(L)s "%(f)s" "%(a)s"'
loglevel = "info"
statsd_host = os.getenv("STATSD_HOST")
statsd_prefix = "django"

# Reasonable HTTP limits
limit_request_line = 8190
limit_request_field_size = 16380

Two workers × eight threads = sixteen concurrent requests per container, on two cores. preload_app = True matters: Django imports cost 100+ MiB; sharing them copy-on-write across workers saves real memory. The trade-off is no in-process state changes after fork — connection pools and worker-local caches must be initialized in a post_fork hook, not at module load.

Flask (WSGI, lighter, I/O-bound):

Same gunicorn.conf.py as Django but with threads = 4 is usually enough. Flask apps are smaller; you can afford more processes if the app is CPU-bound.

FastAPI / Starlette / async Django (ASGI):

# gunicorn.conf.py — FastAPI
import os
import multiprocessing

bind = "0.0.0.0:8000"
workers = int(os.getenv("WEB_CONCURRENCY", multiprocessing.cpu_count()))
worker_class = "uvicorn.workers.UvicornWorker"
worker_tmp_dir = "/dev/shm"

keepalive = 5
timeout = 60
graceful_timeout = 30

max_requests = 5000
max_requests_jitter = 1000

preload_app = False  # uvicorn worker handles startup; preload trips event loop init

accesslog = "-"
errorlog = "-"
loglevel = "info"

Two uvicorn workers handle thousands of concurrent connections cooperatively. Don’t set threads — it’s meaningless for ASGI workers. Don’t preload_app = True either; the asyncio loop must be created per-worker, after fork.

For FastAPI specifically, set the event loop policy in your app:

# main.py
import uvloop
uvloop.install()

uvloop is 2-4× faster than the default asyncio loop on the typical FastAPI workload. Worth the dependency.

Dockerfile that ships either of the above:

FROM python:3.12-slim-bookworm AS builder

ENV PIP_NO_CACHE_DIR=1 \
    PIP_DISABLE_PIP_VERSION_CHECK=1 \
    PYTHONDONTWRITEBYTECODE=1

WORKDIR /build
COPY requirements.txt .
RUN pip install --user --no-cache-dir -r requirements.txt

FROM python:3.12-slim-bookworm AS runtime

RUN apt-get update \
  && apt-get install -y --no-install-recommends curl tini libpq5 \
  && rm -rf /var/lib/apt/lists/* \
  && groupadd -g 1001 app \
  && useradd -u 1001 -g app -m -d /app app

ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    PATH=/home/app/.local/bin:$PATH

COPY --from=builder --chown=app:app /root/.local /home/app/.local
COPY --chown=app:app . /app

WORKDIR /app
USER app

EXPOSE 8000
HEALTHCHECK --interval=10s --timeout=3s --start-period=20s --retries=3 \
  CMD curl -fsS http://127.0.0.1:8000/healthz || exit 1

ENTRYPOINT ["/usr/bin/tini", "--"]
CMD ["gunicorn", "--config", "/app/gunicorn.conf.py", "myapp.wsgi:application"]

The --config flag points at the file above. Override WEB_CONCURRENCY and GUNICORN_THREADS from the platform env — that way the same image runs on a 1 vCPU dev environment and a 4 vCPU production node without rebuilding.

A note on max_requests

max_requests = 1000 recycles each worker after 1000 requests. This is the cheap defense against slow memory leaks in third-party libraries — and there are many. max_requests_jitter = 200 staggers the recycles so they don’t all hit the same second. Without jitter you’ll see a clear latency spike every time max_requests is reached across all workers simultaneously.


We size Python runtimes per workload on Cloud PaaS — sync vs. gthread vs. uvicorn picked from the actual request profile, not a blog rule of thumb, with worker memory tracked in our monitoring plane. If your p95 is hopping around and you suspect Gunicorn sizing, book a runtime tuning session.