Django Websocket Failing right after handshake if using PostgresSql
I developed the application using Django and I used Django channels in it for messages. My websocket connections were working fine as soon as I was using my local db.sqlite3 but when I shifted to using PostgreSQL hosted on AWS RDS, I start getting connection error:
HTTP GET /community/groups/5/ 200 [5.13, 127.0.0.1:1905]
WebSocket HANDSHAKING /ws/group/5/ [127.0.0.1:1908]
HTTP GET /AI/tools-list/ 200 [2.72, 127.0.0.1:1905]
WebSocket DISCONNECT /ws/group/5/ [127.0.0.1:1908]
WebSocket HANDSHAKING /ws/notifications/ [127.0.0.1:1913]
WebSocket DISCONNECT /ws/notifications/ [127.0.0.1:1913]
Disconnected with close code: 1006
Note: Sometime, my notification websocket gets connected but group chat websocket never gets connected
I tried connecting to websocket but it keeps on failing
It looks like the issue might be due to your environment configuration after moving to AWS RDS. Try the following suggestions to resolve it:
1. Redis Configuration
Django Channels relies on Redis as a channel layer backend for managing WebSocket connections. Make sure Redis is running and properly configured in your settings.py
file:
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1', 6379)], # Replace with your Redis server host/port if needed
},
},
}
If you're using a cloud-hosted Redis instance, update the "hosts"
field accordingly.
2. PostgreSQL Configuration
Ensure your PostgreSQL database hosted on AWS RDS is correctly configured in settings.py
. The connect_timeout
option can help handle network delays, especially in cloud environments:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'your_db_name',
'USER': 'your_db_user',
'PASSWORD': 'your_db_password',
'HOST': 'your_aws_rds_host',
'PORT': '5432',
'OPTIONS': {
'connect_timeout': 10, # Adjust as necessary
},
},
}
3. ASGI Server Configuration
Django Channels requires an ASGI server (like Daphne or Uvicorn) to handle WebSocket connections. Ensure you're running the server with the correct command:
daphne -u /path/to/your/asgi.py application
If using Uvicorn:
uvicorn your_project.asgi:application
Also, the problem might be related to your load balancer or firewall configuration. Ensure they are correctly set up to support WebSocket connections.