WSGI

Also known as: Web Server Gateway Interface

On this page 7

WSGI, the Web Server Gateway Interface, is the Python standard that defines how a server hands an HTTP request to a Python web application and how the application returns a response. Among web servers and application servers, it plays the role that the Common Gateway Interface once played for scripts: a neutral contract between server and framework, so that any compliant server can run any compliant application.

The interface is specified in PEP 3333, which updated the original PEP 333 for Python 3. It is deliberately small: one callable, one dictionary of request data and one function for starting the response. That simplicity explains why Django, Flask, Pyramid and Bottle all expose WSGI applications, and why servers such as Gunicorn, uWSGI, mod_wsgi and Waitress can host them interchangeably.

How the WSGI calling convention works

A WSGI application is any Python callable that accepts two arguments, conventionally named environ and start_response, and returns an iterable of byte strings. The server calls it once per request, and the application never opens sockets or parses raw HTTP itself.

The environ dictionary carries CGI-style variables such as REQUEST_METHOD, PATH_INFO, QUERY_STRING and HTTP_HOST, plus WSGI-specific keys such as wsgi.input for the request body and wsgi.errors for logging. The application calls start_response with a status line and a list of headers, then yields the body. The server takes care of transfer encoding, keep-alive and socket writes.

The following table lists the components that every compliant server and application must agree on.

ElementProvided byPurpose
environServerRequest metadata, headers and input stream
start_responseServerSets the status code and response headers
Application callableFramework or codeProduces the response body
Response iterableApplicationYields body chunks as bytes
close() methodApplication, optionalReleases resources after the response
Core elements of the WSGI contract

Because the contract is plain Python, middleware can sit between server and application. A middleware component is itself a WSGI application that wraps another one, which allows compression, authentication, session handling or error pages to be added without changing either side.

WSGI servers and deployment layers

In production, WSGI usually runs in a three-layer stack: a front web server or reverse proxy, a WSGI server that manages Python processes, and the application itself. Nginx, Apache or Caddy terminates TLS, serves static files and buffers slow clients, while the WSGI server focuses on executing Python code efficiently.

The common WSGI servers differ mainly in their process model and their integration with the front server, as the table shows.

ServerConcurrency modelTypical placement
GunicornPre-fork workers, optional threads or geventBehind Nginx over HTTP or a Unix socket
uWSGIProcesses, threads, async loopsBehind Nginx using the uwsgi binary protocol
mod_wsgiEmbedded or daemon mode inside ApacheDirectly in the Apache web server
WaitressPure Python, thread poolWindows hosts and simple deployments
Werkzeug development serverSingle process, auto-reloadLocal development only
Widely used WSGI servers compared

Worker sizing is a central tuning decision. A common starting point for Gunicorn is two to four workers per CPU core, adjusted after measuring memory use and latency. Each synchronous worker handles exactly one request at a time, so the worker count sets the upper bound on concurrent requests unless threads or green threads are enabled.

WSGI compared with CGI, FastCGI and ASGI

WSGI sits between the older process-per-request gateways and the newer asynchronous interface. The Common Gateway Interface starts a new process for every request, FastCGI keeps processes alive but defines a wire protocol, and WSGI defines a Python-level API rather than a network protocol.

The comparison below summarizes where each interface fits.

InterfaceLevelConcurrencyLong-lived connections
CGIProcess and environment variablesOne process per requestNot supported
FastCGIBinary socket protocolPersistent worker poolLimited
WSGIPython function callSynchronous, one request per workerNot supported natively
ASGIPython async callEvent loop, many connections per workerWebSockets and HTTP/2 streams
Gateway interfaces side by side

ASGI, the Asynchronous Server Gateway Interface, was designed as the successor for applications that need WebSockets, server-sent events or high connection counts. Servers such as Uvicorn speak ASGI, and many ASGI servers can also wrap a WSGI application in a thread pool. WSGI remains the better fit for classic request-response applications with blocking database drivers.

Choosing and configuring a WSGI stack

The right configuration depends on the workload profile: CPU-bound pages, I/O-bound calls to databases or external APIs, and the share of slow clients. The decision table maps typical situations to a recommended setup.

SituationRecommended setupReason
CPU-heavy page renderingSync workers equal to cores times twoAvoids contention from the global interpreter lock
Many slow outbound API callsThreaded or gevent workersOverlaps waiting time within one process
Large file uploads from mobile clientsNginx buffering in frontProtects workers from slow request bodies
Existing Apache estatemod_wsgi in daemon modeReuses current configuration and modules
Real-time features requiredASGI server with WSGI fallbackWSGI cannot hold WebSocket connections
WSGI deployment decisions

Several settings deserve explicit values rather than defaults: request timeouts, the maximum requests per worker to contain memory leaks, graceful reload behavior, and the bind address. A Unix domain socket between Nginx and the WSGI server avoids TCP overhead on the same host and keeps the application port off the network.

Limitations and common mistakes

The main limitation of WSGI is its synchronous request model. A worker blocked on a slow query or remote call cannot serve anyone else, so traffic spikes quickly exhaust the pool and produce queued requests and 502 or 504 errors at the proxy.

SymptomLikely causeFix
Gateway timeouts under loadToo few workers or blocking callsAdd workers, threads or move work to a queue
Memory grows steadilyLeak in application or librarySet a maximum request count per worker
Wrong client IP in logsProxy headers ignoredConfigure trusted forwarded headers
Static files served slowlyPython serving assetsLet the front web server deliver them
Frequent WSGI problems and remedies
  • Running the development server in production exposes debugging features and offers no process management.
  • Returning text instead of bytes violates PEP 3333 and fails under Python 3.
  • Exposing the WSGI server directly to the internet removes buffering and TLS handling provided by a reverse proxy.

Explained without jargon

Think of WSGI as a standard electrical socket for Python websites. The server is the power outlet in the wall, and the Python application is the appliance. Because both follow the same shape, you can plug any appliance into any outlet without rewiring.

When a visitor opens a page, the server collects the details of the request and passes them to the application in an agreed format. The application answers with the page content. The key point is that neither side needs to know the other, so developers can switch servers or frameworks freely.

A typical use case

A small online retailer runs its catalog on a Django application. On a virtual server with four CPU cores, the team places Nginx in front to handle TLS certificates and deliver product images directly from disk. Behind it, Gunicorn listens on a Unix socket with nine synchronous workers and a timeout of 30 seconds.

During a seasonal sale, traffic triples and checkout pages slow down because each order calls an external payment API. The team switches Gunicorn to threaded workers with four threads each, which lets a single process continue serving other customers while one request waits on the payment provider. Median response time returns to under 300 milliseconds, and no application code had to change, because the WSGI contract stayed the same.