Why WebSockets Over Polling?
HTTP polling sends a request every N seconds regardless of whether data changed. WebSockets maintain an open connection — the server pushes data only when something happens.
For a dashboard tracking 500+ concurrent users, polling at 5-second intervals meant 6,000 requests per minute doing nothing. WebSockets dropped that to zero idle requests.
Django Channels Setup
``python
consumers.py
import json
from channels.generic.websocket import AsyncWebsocketConsumer
class DashboardConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.user = self.scope['user']
if not self.user.is_authenticated:
await self.close()
return
self.group_name = f'dashboard_{self.user.pk}'
await self.channel_layer.group_add(self.group_name, self.channel_name)
await self.accept()
async def disconnect(self, close_code):
await self.channel_layer.group_discard(self.group_name, self.channel_name)
async def dashboard_update(self, event):
await self.send(text_data=json.dumps(event['data']))
`
Sending Updates From Django Signals
`python
signals.py
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
def send_dashboard_update(user_id: int, data: dict):
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
f'dashboard_{user_id}',
{'type': 'dashboard.update', 'data': data}
)
@receiver(post_save, sender=Order)
def order_updated(sender, instance, **kwargs):
send_dashboard_update(instance.customer.user_id, {
'type': 'order_update',
'order_id': str(instance.pk),
'status': instance.status,
})
`
React WebSocket Hook
`ts
import { useEffect, useRef, useCallback } from 'react'
function useWebSocket(url: string, onMessage: (data: unknown) => void) {
const ws = useRef
const reconnectTimeout = useRef
const connect = useCallback(() => {
ws.current = new WebSocket(url)
ws.current.onmessage = (event) => {
onMessage(JSON.parse(event.data))
}
ws.current.onclose = () => {
reconnectTimeout.current = setTimeout(connect, 3000)
}
}, [url, onMessage])
useEffect(() => {
connect()
return () => {
clearTimeout(reconnectTimeout.current)
ws.current?.close()
}
}, [connect])
}
``
This hook handles automatic reconnection with a 3-second backoff — essential for production use.