CodexBloom - Programming Q&A Platform

Django channels not correctly handling WebSocket connections under high load

πŸ‘€ Views: 93 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-10
django channels websocket asyncio Python

Could someone explain I'm working with an scenario with Django Channels while trying to handle multiple WebSocket connections under high load... I have configured Django Channels to work with Redis as the channel layer, but when I try to connect about 100 clients simultaneously, I'm seeing intermittent connection drops and receiving the following behavior in the logs: `ConnectionClosedError: 1006`. Here’s a simplified version of my configuration: ```python # settings.py CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [ ("127.0.0.1", 6379), ], }, }, } ``` I'm using Django 4.0 and Channels 3.0. My consumer looks like this: ```python from channels.generic.websocket import AsyncWebsocketConsumer class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() async def disconnect(self, close_code): pass async def receive(self, text_data): await self.send(text_data="Message received!") ``` To test this, I created a simple HTML page that connects to the WebSocket endpoint using JavaScript: ```javascript const socket = new WebSocket('ws://localhost:8000/ws/chat/'); socket.onopen = function() { console.log('WebSocket connected!'); }; socket.onclose = function(event) { console.log('WebSocket closed: ', event); }; for (let i = 0; i < 100; i++) { // simulate multiple connections socket.send('Hello!'); } ``` When I run this, I noticed that the connections drop after sending several messages, and the clients receive the `ConnectionClosedError`. I tried adjusting the `ASGI_APPLICATION` and increasing the Redis connection pool limit, but that didn't seem to help. Is there anything else I can do to ensure that my WebSocket connections remain stable under load? I'm coming from a different tech stack and learning Python. Is this even possible?