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.
| Element | Provided by | Purpose |
|---|---|---|
| environ | Server | Request metadata, headers and input stream |
| start_response | Server | Sets the status code and response headers |
| Application callable | Framework or code | Produces the response body |
| Response iterable | Application | Yields body chunks as bytes |
close() method | Application, optional | Releases resources after the response |
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.
| Server | Concurrency model | Typical placement |
|---|---|---|
| Gunicorn | Pre-fork workers, optional threads or gevent | Behind Nginx over HTTP or a Unix socket |
| uWSGI | Processes, threads, async loops | Behind Nginx using the uwsgi binary protocol |
| mod_wsgi | Embedded or daemon mode inside Apache | Directly in the Apache web server |
| Waitress | Pure Python, thread pool | Windows hosts and simple deployments |
| Werkzeug development server | Single process, auto-reload | Local development only |
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.
| Interface | Level | Concurrency | Long-lived connections |
|---|---|---|---|
| CGI | Process and environment variables | One process per request | Not supported |
| FastCGI | Binary socket protocol | Persistent worker pool | Limited |
| WSGI | Python function call | Synchronous, one request per worker | Not supported natively |
| ASGI | Python async call | Event loop, many connections per worker | WebSockets and HTTP/2 streams |
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.
| Situation | Recommended setup | Reason |
|---|---|---|
| CPU-heavy page rendering | Sync workers equal to cores times two | Avoids contention from the global interpreter lock |
| Many slow outbound API calls | Threaded or gevent workers | Overlaps waiting time within one process |
| Large file uploads from mobile clients | Nginx buffering in front | Protects workers from slow request bodies |
| Existing Apache estate | mod_wsgi in daemon mode | Reuses current configuration and modules |
| Real-time features required | ASGI server with WSGI fallback | WSGI cannot hold WebSocket connections |
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.
| Symptom | Likely cause | Fix |
|---|---|---|
| Gateway timeouts under load | Too few workers or blocking calls | Add workers, threads or move work to a queue |
| Memory grows steadily | Leak in application or library | Set a maximum request count per worker |
| Wrong client IP in logs | Proxy headers ignored | Configure trusted forwarded headers |
| Static files served slowly | Python serving assets | Let the front web server deliver them |
- 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.