Search code examples
djangopython-asynciodjango-channels

ASGI vs WSGI, WSGI compatibility issues


When reading about ASGI specification, I noticed this sentence in WSGI compatibility paragraph:

WSGI applications, being synchronous, must be run in a threadpool in order to be served, but otherwise their runtime maps onto the HTTP connection scope’s lifetime.

I don't understand why it must be run in threadpool?


Solution

  • I don't understand why [a WSGI application] must be run in threadpool?

    A WSGI application running inside an ASGI server must be run in a separate thread. If it were to run in the event loop thread, a single WSGI application would block the whole event loop, including all other ASGI applications running on the server. Native ASGI applications don't have this problem because they are async, and as such designed to run inside an event loop alongside other coroutines and callbacks.

    A thread pool is just an optimization: it caches the threads already created so that you don't need to spawn a new thread for each request. (It also provides a cap on the maximum number of threads running at once and queues the extra requests.)