Skip to content

Deploying Django Channels for WebSocket production traffic

Run a Django Channels app under Daphne with Redis as the channel layer, supervised by systemd, with Nginx WebSocket upgrade and load-balanced workers.

Django Channels turns a Django app into an ASGI application that handles WebSockets, long-poll, and server-sent events alongside regular HTTP. Production deployment is two new pieces: an ASGI server (Daphne or Uvicorn) and a channel layer (Redis), both wired so multiple Daphne workers can broadcast to a single client. This article wires the full stack with systemd, Nginx termination, and the operational details that surface only at load.

How to verify

Check the ASGI server, the channel layer, and an actual WebSocket round-trip:

systemctl status daphne-app channels-worker --no-pager | head -30
redis-cli ping
redis-cli pubsub channels 'asgi:group:*'
journalctl -u daphne-app -n 100 --no-pager | tail -30
curl -i -N \
  -H "Connection: Upgrade" -H "Upgrade: websocket" \
  -H "Sec-WebSocket-Version: 13" \
  -H "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==" \
  http://127.0.0.1:8000/ws/echo/

The Sec-WebSocket-Key value is the example from RFC 6455 — the server should answer 101 Switching Protocols with a deterministic Sec-WebSocket-Accept.

What’s happening

Channels splits a Django request into two paths. HTTP requests go through Django’s ASGI app and your usual view functions. WebSocket requests are routed through Channels’ URLRouter to AsyncWebsocketConsumer classes, which run inside the ASGI server’s event loop. Both flow through the same Daphne (or Uvicorn) process.

The channel layer is Redis pub/sub plus a list per consumer. When consumer A wants to send a message to “everyone watching the order page,” it calls group_send("order-42", ...) — the channel layer publishes to a Redis channel, every Daphne worker subscribed to that group receives it, and each one delivers to its connected WebSockets. This is how N workers stay coherent without sticky sessions.

Daphne is the reference ASGI server for Channels. Uvicorn works too if you prefer one runtime for FastAPI and Channels, but Daphne handles the HTTP/2 and SSE edges that Channels exercises slightly better. Either way, you need Redis, you need workers (background consumers that aren’t tied to a connection), and you need Nginx to forward the WebSocket Upgrade header.

The procedure

  1. Install Daphne, Channels, and the Redis backend:

    /opt/venvs/app/bin/pip install daphne 'channels[daphne]' 'channels-redis>=4'
  2. Configure the channel layer in settings.py:

    ASGI_APPLICATION = "project.asgi.application"
    
    CHANNEL_LAYERS = {
        "default": {
            "BACKEND": "channels_redis.core.RedisChannelLayer",
            "CONFIG": {
                "hosts": [("127.0.0.1", 6379)],
                "capacity": 1500,        # per channel, before backpressure
                "expiry": 60,            # seconds a message lives if unread
            },
        },
    }
  3. Write project/asgi.py to mount both protocols:

    import os
    import django
    from channels.routing import ProtocolTypeRouter, URLRouter
    from channels.auth import AuthMiddlewareStack
    from django.core.asgi import get_asgi_application
    
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
    django.setup()
    
    from app.routing import websocket_urlpatterns  # noqa: E402
    
    application = ProtocolTypeRouter({
        "http": get_asgi_application(),
        "websocket": AuthMiddlewareStack(URLRouter(websocket_urlpatterns)),
    })
  4. Systemd unit at /etc/systemd/system/daphne-app.service:

    [Unit]
    Description=Daphne ASGI server for Channels app
    After=network.target redis-server.service
    
    [Service]
    User=deploy
    Group=www-data
    WorkingDirectory=/var/www/app
    RuntimeDirectory=daphne-app
    EnvironmentFile=/etc/app/env
    Environment=PYTHONUNBUFFERED=1
    ExecStart=/opt/venvs/app/bin/daphne \
      -u /run/daphne-app/daphne.sock \
      --proxy-headers \
      --access-log - \
      project.asgi:application
    ExecReload=/bin/kill -s HUP $MAINPID
    Restart=on-failure
    RestartSec=2
    
    [Install]
    WantedBy=multi-user.target

    Run multiple Daphne instances if you need more than one core — Daphne is single-process. Use a template unit daphne-app@.service and bind each instance to its own socket, then load-balance via Nginx upstream.

  5. Background consumers (anything decorated with @channel_layer.send from a non-HTTP path) need a runworker unit. /etc/systemd/system/channels-worker.service:

    [Unit]
    Description=Channels background worker
    After=redis-server.service
    
    [Service]
    User=deploy
    WorkingDirectory=/var/www/app
    EnvironmentFile=/etc/app/env
    ExecStart=/opt/venvs/app/bin/python manage.py runworker default
    Restart=on-failure
    
    [Install]
    WantedBy=multi-user.target
  6. Nginx config for the WebSocket upgrade — this is the part teams break most often:

    map $http_upgrade $connection_upgrade {
      default upgrade;
      '' close;
    }
    
    upstream daphne {
      server unix:/run/daphne-app/daphne.sock;
    }
    
    server {
      listen 443 ssl http2;
      server_name app.example.com;
    
      location /ws/ {
        proxy_pass http://daphne;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_read_timeout 3600s;     # WS connections live long
        proxy_send_timeout 3600s;
      }
    
      location / {
        proxy_pass http://daphne;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
      }
    }

Common pitfalls

  • Forgetting the map $http_upgrade block — without it, $connection_upgrade is empty and Nginx never forwards the WebSocket handshake. Symptom: client sees 101 Switching Protocols was never sent.
  • Running Channels HTTP traffic through Daphne and serving the same site under Gunicorn-WSGI — the routes split and the codebase loads twice. Route everything through Daphne or run a stable URL split with Nginx and accept the duplicate process tree.
  • Using the in-memory channel layer in production — it ships with Channels and “just works” in dev, but each Daphne process has its own memory. Two workers will never see each other’s messages. Use Redis.
  • proxy_read_timeout defaulting to 60 s — chat connections die every minute. Set it to your longest expected idle plus a margin.
  • Sharing one Redis between channel layer and Celery without separating with db=N — Celery’s KEYS scans bleed into pub/sub debugging, and a FLUSHDB in the wrong place takes down both.

For the Gunicorn-vs-Daphne deployment decision when you’re not using Channels, see Django: Gunicorn vs Daphne, when to switch. Stack Harbor’s managed operations practice runs Channels production stacks with a separate daphne@ template unit per CPU core, Redis on a dedicated host or AOF-persisted instance, and Prometheus alerting on asgi:group:* queue depth so the team sees backpressure before clients do.