Gunicorn

On this page 7

Gunicorn, short for Green Unicorn, is a pre-fork WSGI HTTP server for Python that loads a web application and serves it through a pool of worker processes supervised by a single master process. Among web servers, it belongs to the class of application servers: it speaks HTTP, but its main job is to translate requests into calls to Python frameworks such as Django, Flask or Pyramid.

In production, Gunicorn almost always runs behind a reverse proxy such as Nginx, which handles TLS, static files, buffering of slow clients and connection limits. Gunicorn then focuses on executing application code reliably, restarting failed workers and scaling concurrency through its configurable worker model.

How the Gunicorn pre-fork model works

Gunicorn follows the pre-fork model inherited from Ruby’s Unicorn: the master process binds the listening socket, then forks a fixed number of workers that accept connections on that shared socket. The master never handles requests itself; it monitors worker health, replaces workers that crash or exceed the timeout, and reacts to Unix signals for reloads and graceful shutdowns.

Each worker imports the application through the WSGI interface defined in PEP 3333, receives an environ dictionary for each request and returns an iterable response. With the --preload option, the application is imported once in the master before forking, which saves memory through copy-on-write but prevents per-worker code reloading.

The table below shows how the master reacts to the most common signals and events.

Signal or eventMaster actionTypical use
HUPReloads configuration and starts new workersDeploying new code
TERMGraceful shutdown with timeoutStopping the service
TTIN and TTOUAdds or removes one workerManual capacity tuning
USR2Starts a new master binaryZero-downtime upgrade
Worker timeoutKills and replaces the workerRecovering from hung requests
Master process signals and events

Gunicorn worker classes

The worker class determines how each worker handles concurrency, and choosing it correctly matters more than any other setting. The default sync worker handles one request at a time, which is simple and predictable but vulnerable to slow clients when no proxy buffers them.

Other classes add threads, cooperative coroutines or an ASGI event loop. The following table compares them.

Worker classConcurrency per workerBest suited for
syncOne requestCPU-bound views behind a buffering proxy
gthreadSeveral threadsMixed I/O with blocking libraries
gevent and eventletHundreds of green threadsMany slow outbound calls or long polling
UvicornWorkerAsynchronous event loopASGI frameworks such as FastAPI
Worker classes and their characteristics

Asynchronous classes require cooperative, non-blocking code: a single blocking database driver or CPU-heavy loop stalls every connection in that worker. Monkey patching in gevent mitigates part of this risk but can break libraries that rely on native threads.

Key configuration parameters

Gunicorn is configured through command-line flags, environment variables or a Python configuration file such as gunicorn.conf.py. A common starting point for worker count is (2 x CPU cores) + 1, a heuristic that assumes some workers wait on I/O while others compute; real limits come from available memory and load testing.

The parameters below have the largest effect on stability and throughput.

SettingDefaultWhat it controls
workers1Number of worker processes
threads1Threads per worker with gthread
timeout30 secondsSilence limit before a worker is killed
graceful_timeout30 secondsTime to finish requests on restart
max_requests0 (disabled)Requests before a worker is recycled
keepalive2 secondsIdle time for kept-alive connections
bind127.0.0.1:8000TCP address or Unix socket
Important Gunicorn settings

Setting max_requests with a small max_requests_jitter is a practical defense against gradual memory leaks, because workers restart at staggered intervals instead of all at once.

Gunicorn is one of several ways to run Python or dynamic code behind a front-end server, and each option places the process boundary differently. Its strengths are a small configuration surface, pure-Python installation and mature behavior on Linux; it does not run natively on Windows.

ServerProtocol to applicationMain difference
GunicornWSGI, ASGI through workersSimple pre-fork design, Python only
uWSGIWSGI, uwsgi protocolVery many options, now in maintenance mode
UvicornASGINative async server, often run under Gunicorn
PHP-FPMFastCGIProcess manager for PHP rather than Python
Apache TomcatJava Servlet APIServlet container for Java applications
Gunicorn and neighboring application servers

Deployment practices and common mistakes

A robust deployment runs Gunicorn under a process supervisor such as systemd, binds it to a Unix socket or loopback port, and lets Nginx terminate TLS and serve static assets. Exposing sync workers directly to the internet is a classic error, because a few slow clients can occupy every worker and make the site unresponsive.

  • Too many workers: each worker holds a full copy of the application, so excess workers cause swapping and out-of-memory kills.
  • Raising timeout to hide slow code: long timeouts mask problems; move heavy jobs to a background task queue instead.
  • Missing proxy headers: without forwarded_allow_ips and correct headers, applications see the proxy address instead of the real client IP.
  • Async worker with blocking drivers: the event loop stalls and latency rises for all connections.

Explained without jargon

Gunicorn is a program that lets a website written in Python answer visitors. Picture a restaurant: Nginx is the host at the door who greets guests and hands out menus, while Gunicorn is the kitchen manager who assigns each order to one of several cooks.

If a cook gets stuck or falls ill, the manager replaces that cook immediately so the kitchen keeps running. More cooks mean more orders at once, but the kitchen has limited space, so adding too many slows everything down. The main point is that Gunicorn keeps Python applications running steadily and recovers from problems on its own.

A typical use case

A small software company runs a Django customer portal on a virtual server with 4 CPU cores and 8 GB of memory. Nginx listens on port 443, serves static files from disk and forwards dynamic requests to Gunicorn on a Unix socket. Gunicorn runs 9 gthread workers with 2 threads each, a 30-second timeout and max_requests set to 1,000 with a jitter of 100.

Each worker uses about 180 MB of memory, so the pool needs roughly 1.6 GB and leaves room for PostgreSQL and caching. Report generation, which used to take 40 seconds, was moved to a background queue so no request approaches the timeout.

During releases, the team sends a HUP signal through systemd; new workers start with the updated code while old ones finish their requests. The outcome is deployments without visible downtime and stable memory usage over weeks of operation.