djangoazureredisdjango-channelsuvicorn

Django Channels: Error UNKNOWN while writing to socket. Connection lost


We have Django Channels coupled with uvicorn and azure redis instance. Our sentry is getting swamped with errors such as:

Exception in ASGI application
 
ssd.consumers in disconnect

Error UNKNOWN while writing to socket. Connection lost.

The exception is thrown in asyncio/streams.py file as shown on example Snippet that throws exception.

My main issue is that I have no idea if redis cuts this connection, or server is not keen to keep it? Any hints appreciated. I haven't observed such behaviour on local instance of redis. We opearte on following packages:

Django = "~4.2"
redis = "^4.3.1"
channels = {extras = ["daphne"], version = "^4.0.0"}
channels-redis = "^4.1.0"
uvicorn = {extras = ["standard"], version = "^0.24.0.post1"}

It's worth to point that it works majority of the times, websockets are operational, sometimes it just randomly throw an exception mentioned above.


Solution

  • Apparently there is more config in channels_redis lib that can be specified which is not explicitly stated in documentation. Since Azure Cache For Redis is not liberal one it was timing out idle connections. Changing my setting to this one solved issue:

        CHANNEL_LAYERS = {
            "default": {
                "BACKEND": "channels_redis.core.RedisChannelLayer",
                "CONFIG": {
                    "hosts": [
                        { # specifying host as dict with additional keys for redis-py client was a key to solve it.
                            "address": CHANNELS_REDIS_URL,
                            "retry_on_timeout": True,
                            "health_check_interval": 1,
                            "socket_keepalive": True,
                        }
                    ],
                    "capacity": 1500,
                    "expiry": 5,
                },
            },
        }