Skip to content

Gunicorn, WSGI and Django

Posted on:November 22, 2023 at 12:00 AM

Here is the Q&A list with insights from the context:

What does WSGI do?

WSGI is a gateway interface specification that decouples web servers from Python web applications. It acts as a middleware between the web server and the application.

When a client request comes in, WSGI receives it and passes it on to the Python application. The application processes the request and returns a response. WSGI then passes this response back to the web server, which in turn sends it to the client.

Some key responsibilities of WSGI:

Why do we need WSGI?

Without WSGI, web applications have to be written specifically for each web server like Apache or Nginx. This reduces flexibility and portability.

WSGI provides a standard that web applications can conform to. This makes it easy to run a WSGI compliant app on any WSGI web server.

Some benefits of using WSGI:

What is the WSGI interface spec?

The WSGI app interface is a callable object like a function or class. It accepts two arguments:

And it returns a response body.

def application(environ, start_response):

How does middleware work with WSGI?

Normally web server talks directly to the app. With middleware, the request goes through middleware first before reaching the app.

The middleware can modify the request, pass it to app, get response, modify the response, and pass it back to server. This allows additional processing and flexibility.

How can WSGI improve performance?

WSGI allows cleanly separating responsibilities between components:

This makes it easy to scale by adding more WSGI workers.

What is a good value for Gunicorn timeout setting?

The default timeout of 30 seconds is good in most cases. For non-sync workers, higher values like 60-90 seconds are fine as it doesn’t affect request handling time.

For sync workers, avoid very high timeouts as it directly impacts request time.

What is a good number of workers for Gunicorn?

A general rule of thumb is to have 2-4 workers per CPU core.

But optimal value depends on the application load. Perform load testing and tweak workers setting to find the best value.

Start with default of 1 worker and slowly increase as needed.

When does Nginx pass request to Gunicorn/Django?

Nginx passes request to Gunicorn+Django only for dynamic content like rendering HTML pages.

For static files, Nginx serves them directly without passing through Gunicorn.

How can Gunicorn’s logging help debug issues?

Enable debug level logs in Gunicorn to troubleshoot timeouts and worker failures.

--log-level debug 
--timeout 90

Debug logs provide insights into what’s happening inside Gunicorn.

ref: