websockets-channels
Skill1 starsChanged 5 months agoMITView on GitHub
Real-time events on this stack with Django Channels 4.2+ on ASGI — an AsyncJsonWebsocketConsumer, JWT-cookie auth middleware that rejects anonymous sockets, tenant-scoped group names per entreprise, and channel_layer.group_send fired from transaction.on_commit over a Redis channel layer. Use when adding a WebSocket endpoint, building a consumer, pushing live notifications, wiring the ASGI application, fixing a socket that receives no events or leaks across tenants, or asking how real-time works here. Not for background jobs or fan-out compute (see celery-tasks), tenant filtering of REST querysets (see multi-tenancy), or the production ASGI/Procfile setup (see deploy-aws).
In this repository49 other files it gives its agents.
- accessibilitySkill
- ai-evalsSkill
- ai-integrationSkill
- architecture-decisionsSkill
- audit-loggingSkill
- aws-servicesSkill
- browser-e2e-testingSkill
- celery-tasksSkill
- changelogSkill
- ci-cdSkill
- codebase-guideSkill
- code-reviewSkill
- commit-messageSkill
- cookie-auth-csrfSkill
- dashboard-data-designSkill
- db-concurrencySkill
- debugSkill
- dependency-auditSkill
- deploy-awsSkill
- design-systemSkill
- drf-apiSkill
- drf-zod-contractSkill
- frontend-perfSkill
- git-workflowSkill
- i18n-rtlSkill
- incident-responseSkill
- migrationsSkill
- money-decimalSkill
- multi-tenancySkill
- nextjs-moduleSkill
- observabilitySkill
- perf-reviewSkill
- production-readinessSkill
- product-ux-designSkill
- rbac-permissionsSkill
- react-querySkill
- security-reviewSkill
- skill-authoringSkill
- tailwind-shadcnSkill
- tenant-session-switchSkill
- threat-modelingSkill
- verifySkill
- version-checkSkill
- visual-ui-designSkill
- webhook-handlerSkill
- write-testsSkill
- zod-formsSkill
- zustand-stateSkill
- example-skillSkill
The file
We split this skill into the rules it gives an agent
2 rules. About 0 are common, 1 is distinctive, and 1 is very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 76
Under Uvicorn (production): run uvicorn myproject.asgi:application against the same ASGI app.
- Distinctive: line 90
Fall back to polling: when websockets are unavailable (blocked network, proxy strips the upgrade) so the UI still updates, just slower.
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
WebSockets (Django Channels on ASGI)
When to use
Pushing server-initiated events to the browser — live notifications, presence,
progress bars, collaborative updates. If the client just polls or the work is a
one-off background job with no live push, you want celery-tasks, not a socket.
Pattern
Four invariants, held together:
- Async consumer —
AsyncJsonWebsocketConsumer, one per logical channel. - Auth from the JWT cookie in
scopevia ASGI middleware — aBaseMiddlewaresubclass reads the HttpOnly cookie fromscope["cookies"], resolves the user withAccessToken(token)["user_id"]wrapped indatabase_sync_to_async, and setsscope["user"]. Anonymous sockets areclose()d, never left open — it mirrors the REST cookie auth. - Group names are tenant-scoped (
entreprise_<id>_...) sogroup_sendcan never fan out across tenants — the same fail-closed rule as REST scoping. - Events fire after the DB commit, inside
transaction.on_commit, so clients never see a row that a rollback erased. A Redis channel layer carries the fan-out.
The consumer rejects anonymous sockets and joins a tenant group; a plain function emits into that group only after the row commits:
# realtime/consumers.py
from channels.generic.websocket import AsyncJsonWebsocketConsumer
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from django.db import transaction
class NotificationConsumer(AsyncJsonWebsocketConsumer):
async def connect(self):
user = self.scope["user"] # set by JWT-cookie middleware
if not user.is_authenticated:
return await self.close(code=4401) # reject anonymous, fail closed
self.group = f"entreprise_{user.entreprise_id}_notifs" # tenant-scoped name
await self.channel_layer.group_add(self.group, self.channel_name)
await self.accept()
async def disconnect(self, code):
group = getattr(self, "group", None)
if group: # rejected sockets never joined one
await self.channel_layer.group_discard(group, self.channel_name)
async def notify(self, event): # handler for {"type": "notify"}
await self.send_json(event["payload"])
# call from a view, signal, or Celery task — only after the row is committed
def emit_notification(invoice):
group = f"entreprise_{invoice.entreprise_id}_notifs"
payload = {"type": "notify", "payload": {"id": invoice.id, "kind": "invoice"}}
transaction.on_commit(
lambda: async_to_sync(get_channel_layer().group_send)(group, payload)
)Wire it in asgi.py: call get_asgi_application() first so apps load before routes are
imported, then build a ProtocolTypeRouter with "http" mapped to that app and
"websocket" mapped to AllowedHostsOriginValidator(JWTCookieMiddleware(URLRouter([...])))
routing path("ws/notifications/", NotificationConsumer.as_asgi()) — the origin validator
is mandatory, not optional: cookie auth is ambient, so without it any origin can open an
authenticated socket (CSWSH). AllowedHostsOriginValidator reuses settings.ALLOWED_HOSTS;
use OriginValidator(app, ["https://app.example.com"]) when the browser origin differs from
the API host. Set CHANNEL_LAYERS["default"]
to channels_redis.core.RedisChannelLayer with a hosts entry pointing at Redis.
Dev vs production
- Dev server is Daphne, not Uvicorn — add
"daphne"above"django.contrib.staticfiles"inINSTALLED_APPSandrunserverspeaks ASGI automatically. - Under Uvicorn (production) run
uvicorn myproject.asgi:applicationagainst the same ASGI app. Uvicorn is a fine ASGI server but is not bundled with Channels; the Procfile lives indeploy-aws.
Client side
The backend is only half of it — the browser has to hold the socket open and react to events sanely.
- One connection per session, shared across the app, not one per component. Auto-reconnect with backoff (grow the delay, cap it) when it drops.
- Keepalive ping on an interval below your proxy/load-balancer idle timeout. An LB drops an idle socket after its quiet-timeout window; with no traffic under it the connection dies and events silently stop arriving — the classic "socket works, then goes dead after a minute of quiet." Keep the interval a relative rule (comfortably below whatever your proxy timeout is), not a hard-coded number.
- Fall back to polling when websockets are unavailable (blocked network, proxy strips the upgrade) so the UI still updates, just slower.
- On each event, invalidate/refetch the affected query — don't hand-patch UI state
from the payload. The socket signals what changed; the refetch fetches the
authoritative value. Patching state from the payload drifts from the server and
races other writers. With
react-query, an event maps toqueryClient.invalidateQueries({ queryKey: [...] }).
Adapt to your repo
Rename Entreprise/entreprise and the tenant accessor (user.entreprise_id vs
user.profile.entreprise_id), the cookie name (access_token), the app label
(realtime), and the group prefix to match your project. Point CHANNEL_LAYERS
at your ElastiCache Redis in production, and keep the socket cookie in sync with
your simplejwt/dj-rest-auth cookie name.
Gotchas
- No
AllowedHostsOriginValidator= CSWSH. WebSockets are exempt from CORS and the same-origin policy, so a cross-site page can handshake against your socket and the browser attaches the HttpOnly auth cookie regardless of origin — the connection authenticates as your user and reads the tenant's event stream. Always wrap the websocket branch; never rely onALLOWED_HOSTSalone (it only guards HTTP). - No
transaction.on_commit= race: sending inside the transaction can reach the client before commit (or after a rollback) — always defer the send. - Never build a group name from client input — derive it from
scope["user"], same fail-closed rule as REST tenant scoping (seemulti-tenancy). - The in-memory channel layer works only in one process; multi-worker or multi-dyno fan-out needs the Redis layer, or events silently vanish.
- Blocking ORM calls in an async consumer freeze the event loop — wrap them in
database_sync_to_async(or@sync_to_async). AccessToken(token)raises on expired/invalid — catch it and fall back toAnonymousUser, or the socket 500s on connect.
See also
multi-tenancycelery-tasksdeploy-awsreact-query
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

