user8434155
user8434155

Reputation:

Curious behaviour with default Django http server

I've always been told that Django is a synchronous Web framework, and that its default webserver is slow, insecure, and worst of all - singly threaded. Looking at Django's documentation on their implementation of a webserver does not reveal much details: I'm told that it is "lightweight", and that the Django team recommends against its use in production. Searching on Stackoverflow reveals that any single request would hang another until the first is completed - what you'd expect.

But here's the surprising bit I encountered while playing around with it - If I send a request for the server to sleep for 10 seconds (simulating long-running I/O), and another simultaneous request to simply load the index page, the index page is able to load immediately while the other request is processed.

The exact same test, when tried on a configuration running behind NGINX/Gunicorn with a single Gunicorn worker process shows that the loading of the index page is stalled until the first request (sleep for 10 seconds) completes. This behavior is mirrored in a third test where Gunicorn is run without NGINX in front. This is behaviour I'd expect - but completely different from the default server!

Why does this happen? What goes on behind the scenes with Django's default webserver?

Upvotes: 0

Views: 77

Answers (1)

knbk
knbk

Reputation: 53699

The built-in development server is not single-threaded, and hasn't been for a long time.

Django subclasses Python's WSGIServer, along with the ThreadingMixin. This spawns a new thread for every request, so a request never has to wait for a thread to become available. This does slow down the request -- each thread has its own database connection, so every new thread has to open a new connection -- but the number of concurrent requests is only limited by the available resources.

Spawning threads on demand is convenient, but it's also a very easy target for denial-of-service attacks. That's one of the reasons why the development server is considered insecure, and why production-ready WSGI servers don't use the same setup.

Upvotes: 1

Related Questions