Django and Channels and ASGI Thread Problem

Viewed 1974

I have a problem using django and channels(in asgi mode) when I set django channels and use asgi mode, my app create a new thread for every http request and every message that I send from channel

for example suppose that my app is a simple echo chat server when I run my server and request to connect to socket as client, threads increased and also when I send something to socket again thread increased by every message.

Do you know why? How can I fix or limit it?

1 Answers

For synchronous requests Channels makes a ThreadPool. If it ran HTTP requests in the event loop every database query and cache hit would lock up the event loop.

If you do not set the environment variable ASGI_THREADS it uses the default set by concurrent.futures.ThreadPool which IMO is way too high as it is the number of CPU cores multiplied by 5. Set ASGI_THREADS to a lower number and use multiple Daphne processes. By using a lower number of threads and multiple processes you avoid some of the slowdown caused by Python's global interpreter lock.

Related