Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Lab · 30 min · revision 3

Lab: An Authenticated WebSocket Feed Across Workers

Build a horizontally scalable, authenticated WebSocket cluster using FastAPI and Redis Pub/Sub, enforcing Origin header validation against CSWSH and bounded buffer backpressure.

Contentsand lesson path

What you will learn

  • Serve WebSocket connections that authenticate and check the origin at the handshake, follow a versioned message protocol, bound each connection's send queue, and fan out events across server processes through a pub/sub channel.

Prerequisites: Async I/O in Python

01. Why it matters

A WebSocket server in one process is easy to demo on a laptop. In production, three problems appear: messages must reach users connected to other server processes, a hostile web page must not be able to open a socket in a logged-in user's name, and one slow client must not use up the server's memory.

First, suppose a collaboration app runs four replicas behind a load balancer, and Alice and Bob, in the same document room, land on workers 1 and 2. Processes do not share memory, so when Alice posts an edit, worker 1 cannot hand it to Bob. Without a shared message channel between the workers, often called a backplane (Redis Pub/Sub, NATS or RabbitMQ), the message stays inside the process that received it.

Second, WebSockets are not covered by CORS (the browser rules that decide which other sites may read a response). When a page runs new WebSocket("wss://api.example.com/ws"), the browser may attach the user's cookies for api.example.com, even when the page comes from another site. That happens for cookies marked SameSite=None; cookies marked Lax or Strict (and, in Chromium-based browsers, cookies with no SameSite attribute) are not sent on a cross-site handshake. If the session cookie is sent, an attacker's page can open an authenticated socket to your backend: Cross-Site WebSocket Hijacking (CSWSH). Do not rely on cookie settings alone: check the Origin header in the handshake, before websocket.accept().

Third, the browser's WebSocket API cannot set custom headers such as Authorization: Bearer <token>. You choose between a session cookie (which then needs the Origin check), a short-lived ticket in the query string, or a login message sent as the first frame after the connection opens. This lab uses tickets.

Finally, a client on a poor mobile link may read more slowly than the server writes. With an unbounded outbound queue, its unsent frames pile up until the process runs out of memory.

02. Goal and setup

Goal: run one WebSocket service as two worker processes that share a Redis Pub/Sub backplane, and show that a message sent to worker 1 reaches a user on worker 2, that the handshake rejects a forged Origin, a missing ticket and a reused ticket, and that a stalled client is closed instead of holding the room up.

You need Python 3.12 or later, Redis 6.2 or later (for GETDEL) on localhost:6379, and three terminals. The run below used Python 3.12.13 and Redis 8.10. The finished folder looks like this: ws-lab/app/__init__.py (empty), ws-lab/app/websocket_cluster.py (step 1), ws-lab/client.py (step 4) and ws-lab/slow_consumer.py (step 5). Create it and install the pinned packages:

Shell · project folder and pinned packages
mkdir -p ws-lab/app && cd ws-lab && touch app/__init__.py
uv venv --python 3.12 .venv && source .venv/bin/activate
uv pip install "fastapi==0.165.0" "uvicorn==0.54.0" "redis==8.2.0" \
    "websockets==17.4" "httpx==0.28.1"
python -c "import fastapi, redis, websockets as w; print(fastapi.__version__,
    redis.__version__, w.__version__)"
Expected output
0.165.0 8.2.0 17.4

03. Redis Pub/Sub backplane and connection manager architecture

To fan messages out across worker processes, each worker keeps its own list of local connections and shares one Redis Pub/Sub channel per room with the other workers:

  • A local connection registry. Each worker keeps a dictionary from room id (room_id) to the set of connections open on that worker. When a socket closes, it is removed at once, so the dictionary does not grow without limit.
  • Separate reader and writer tasks. For each client, one task reads incoming frames and another writes outgoing ones, so a slow write never blocks reading, and neither blocks the event loop.
  • Redis Pub/Sub subscriptions per room. When a client sends a message, the worker that received it publishes it to a Redis channel such as room:{room_id}. Every worker with local members in that room subscribes to the channel and passes each message to its own clients in the room. When the last local member leaves, the worker unsubscribes.
  • Bounded outboxes for backpressure. Outgoing messages pass through a per-connection asyncio.Queue(maxsize=100) drained by that connection's own writer task. If a slow client fills its queue, the server closes that socket with code 1008 (Policy Violation); for purely ephemeral updates such as cursor positions you could drop the oldest frame instead.

04. Step 1: write the service

Save the code below as app/websocket_cluster.py. It works in four phases:

  • Phase 1: authenticate and authorise at the handshake. The browser's WebSocket API cannot send an Authorization header, so the client first calls POST /ws-ticket with its normal bearer token; the route accepts only a header of the form Bearer <token>. The server checks that the user is a member of the room and stores a random ticket in Redis for 30 seconds. The client opens /ws/rooms/{room_id}?ticket=..., and before accept() the server checks the Origin against an allowlist and redeems the ticket with GETDEL, so it works once. The Origin check only stops cross-site hijacking from browsers, because any non-browser client can send whatever Origin it likes; the ticket is what authenticates. Closing before accept() rejects the handshake itself: the client sees an HTTP 403 response (browsers report a failed connection, close code 1006), not close code 1008.
  • Phase 2: register the local client. Once accepted, the socket is added to the worker's dictionary under its room. If it is the first member of that room on this worker, the manager starts a background task that listens to the Redis channel room:{room_id}.
  • Phase 3: versioned messages, Redis fan-out and bounded outboxes. Every frame is an envelope {"v": 1, "type": ..., "id": ..., "data": {...}}; an unknown version or type gets an error frame instead of being relayed. The error frame goes through the same bounded outbox with put_nowait; a client whose outbox is already full is dropped rather than letting await put() block the receive loop forever. The receiving worker publishes valid envelopes to Redis, and every worker subscribed to the channel puts them into each local connection's own asyncio.Queue(maxsize=100). A writer task per connection drains its queue, so a slow client only delays itself. When a queue is full, that client is closed with code 1008 instead of letting it hold memory or stall the room. The close runs as its own task, and the manager keeps a reference to it until it finishes, because asyncio holds only a weak reference to a running task.
  • Phase 4: remove dead sockets. When a client disconnects, even abruptly, the manager removes it and cancels the room's Redis subscription if no local members are left, so no listener tasks linger.
Python · app/websocket_cluster.py (tickets, Origin check, envelope, bounded outboxes)
import asyncio
import json
import logging
import os
import secrets
from collections import defaultdict

from fastapi import Depends, FastAPI, Header, HTTPException, WebSocket, status
from fastapi import WebSocketDisconnect
from pydantic import BaseModel
from redis.asyncio import Redis

logging.basicConfig(level=logging.INFO, format="%(message)s")
log = logging.getLogger("ws")
WORKER = os.environ.get("WORKER_NAME", "worker")
app = FastAPI()
# Browser origins allowed to open sockets; include your dev server locally
ALLOWED_ORIGINS = set(os.environ.get(
    "ALLOWED_ORIGINS", "https://app.example.com,http://localhost:5173").split(","))
SESSIONS = {"token_alice": "alice", "token_bob": "bob", "token_mallory": "mallory"}
ROOM_MEMBERS = {"sprint": {"alice", "bob"}}
MESSAGE_TYPES = {"card_moved", "comment_added"}  # protocol version 1
redis = Redis(host=os.environ.get("REDIS_HOST", "localhost"),
              port=int(os.environ.get("REDIS_PORT", "6379")))


class Connection:
    """One socket plus its own bounded outbox and writer task."""

    def __init__(self, ws: WebSocket, user: str, maxsize: int = 100):
        self.ws, self.user = ws, user
        self.outbox: asyncio.Queue[str] = asyncio.Queue(maxsize=maxsize)
        self.writer = asyncio.create_task(self._write())

    async def _write(self):
        while True:  # a slow client only ever blocks its own task
            await self.ws.send_text(await self.outbox.get())


class ClusterConnectionManager:
    def __init__(self, redis_client: Redis):
        self.redis = redis_client
        self.rooms: dict[str, set[Connection]] = defaultdict(set)
        self.subscriptions: dict[str, asyncio.Task] = {}
        self.closing: set[asyncio.Task] = set()  # keep close tasks alive

    def connect(self, room_id: str, conn: Connection):
        self.rooms[room_id].add(conn)
        if room_id not in self.subscriptions:  # first local peer in the room
            log.info("[%s] subscribing to Redis channel room:%s", WORKER, room_id)
            self.subscriptions[room_id] = asyncio.create_task(
                self._listen_redis(room_id))

    def disconnect(self, room_id: str, conn: Connection):
        conn.writer.cancel()
        self.rooms[room_id].discard(conn)
        if not self.rooms[room_id] and room_id in self.subscriptions:
            self.subscriptions.pop(room_id).cancel()

    def broadcast_local(self, room_id: str, message: str):
        for conn in list(self.rooms[room_id]):  # copy: the set may change
            try:
                conn.outbox.put_nowait(message)
            except asyncio.QueueFull:  # slow consumer: drop it, not the room
                log.info("[%s] %s is too slow, closing", WORKER, conn.user)
                self.disconnect(room_id, conn)
                task = asyncio.create_task(conn.ws.close(
                    code=status.WS_1008_POLICY_VIOLATION, reason="too slow"))
                self.closing.add(task)  # the loop keeps only a weak reference
                task.add_done_callback(self.closing.discard)

    async def _listen_redis(self, room_id: str):
        pubsub = self.redis.pubsub()
        await pubsub.subscribe(f"room:{room_id}")
        try:
            async for msg in pubsub.listen():
                if msg["type"] == "message":
                    log.info("[%s] Redis event on room:%s", WORKER, room_id)
                    self.broadcast_local(room_id, msg["data"].decode())
        finally:
            await pubsub.aclose()

    async def publish_global(self, room_id: str, envelope: dict):
        await self.redis.publish(f"room:{room_id}", json.dumps(envelope))


manager = ClusterConnectionManager(redis)


class TicketRequest(BaseModel):
    room_id: str


def current_user(authorization: str = Header(default="")) -> str:
    scheme, _, token = authorization.partition(" ")
    user = SESSIONS.get(token) if scheme.lower() == "bearer" else None
    if user is None:
        raise HTTPException(401, headers={"WWW-Authenticate": "Bearer"})
    return user


@app.post("/ws-ticket")
async def issue_ticket(req: TicketRequest, user: str = Depends(current_user)):
    if user not in ROOM_MEMBERS.get(req.room_id, set()):
        raise HTTPException(403, "not a member of this room")
    ticket = secrets.token_urlsafe(24)
    value = json.dumps({"user": user, "room": req.room_id})
    await redis.set(f"ws-ticket:{ticket}", value, ex=30)  # short-lived
    return {"ticket": ticket}


async def redeem(ticket: str | None, room_id: str) -> str | None:
    """Single use: GETDEL removes the ticket as it is read."""
    raw = await redis.getdel(f"ws-ticket:{ticket}") if ticket else None
    data = json.loads(raw) if raw else None
    return data["user"] if data and data["room"] == room_id else None


def error_frame(reason: str) -> str:
    return json.dumps({"v": 1, "type": "error", "data": {"reason": reason}})


@app.websocket("/ws/rooms/{room_id}")
async def websocket_endpoint(websocket: WebSocket, room_id: str):
    # 1. Check the Origin (stops cross-site hijacking from browsers) and
    #    redeem the ticket (authenticates every client). Closing before
    #    accept() rejects the handshake: the client sees HTTP 403.
    origin = websocket.headers.get("origin")
    user = None
    if origin in ALLOWED_ORIGINS:
        user = await redeem(websocket.query_params.get("ticket"), room_id)
    if user is None:
        log.info("[%s] rejected handshake (origin=%s, user=%s)", WORKER, origin, user)
        await websocket.close(code=status.WS_1008_POLICY_VIOLATION)
        return
    await websocket.accept()
    conn = Connection(websocket, user)
    manager.connect(room_id, conn)
    log.info("[%s] %s joined room:%s from %s", WORKER, user, room_id, origin)
    try:
        while True:
            try:
                msg = json.loads(await websocket.receive_text())
            except ValueError:
                msg = None
            # 2. Versioned envelope: {"v": 1, "type": ..., "id": ..., "data": {...}}
            if (not isinstance(msg, dict) or msg.get("v") != 1
                    or msg.get("type") not in MESSAGE_TYPES):
                try:  # never await a full outbox: that would hang this loop
                    conn.outbox.put_nowait(error_frame("unsupported message"))
                except asyncio.QueueFull:
                    break  # too slow even for an error frame: drop the client
                continue
            envelope = {"v": 1, "type": msg["type"], "id": msg.get("id"),
                        "from": user, "data": msg.get("data", {})}
            log.info("[%s] %s sent %s, publishing", WORKER, user, msg["type"])
            await manager.publish_global(room_id, envelope)
    except WebSocketDisconnect:
        pass
    finally:
        manager.disconnect(room_id, conn)

05. Steps 2 to 4: start Redis and two workers, then run the client

  1. Start Redis on port 6379 and check that it answers. With Docker: docker run -d --name lab-redis -p 6379:6379 redis:8-alpine; with a local install: redis-server --port 6379 --daemonize yes. Then run the check below.
Shell · step 2
redis-cli -p 6379 ping
Expected output
PONG
  1. Start two workers, each in its own terminal and each with its own name so the logs show which worker handled what. Then, from a third terminal, ask each worker for a ticket without a token: both must refuse with 401.
Shell · step 3 (terminal 1, terminal 2, then terminal 3)
# terminal 1
WORKER_NAME=Worker-1 uvicorn app.websocket_cluster:app --port 5001 --log-level warning
# terminal 2
WORKER_NAME=Worker-2 uvicorn app.websocket_cluster:app --port 5002 --log-level warning
# terminal 3
for port in 5001 5002; do
  curl -s -o /dev/null -w "$port %{http_code}\n" -X POST \
    -H "Content-Type: application/json" -d '{"room_id": "sprint"}' \
    "http://127.0.0.1:$port/ws-ticket"
done
Expected output (terminal 3)
5001 401
5002 401
  1. Save the client below as client.py and run python client.py in terminal 3. Alice connects to worker 1 and Bob to worker 2, so Bob can only receive Alice's event through Redis. The client then tries a forged Origin, a missing ticket and a reused ticket. Before you run it, predict for each of the three attacks whether the handshake fails, and which line of the service stops it.
Python · client.py (two users on two workers, then three attacks)
import asyncio
import json

import httpx
from websockets.asyncio.client import connect
from websockets.exceptions import InvalidStatus

GOOD = "http://localhost:5173"


async def ticket(port, token, room="sprint"):
    async with httpx.AsyncClient() as c:
        r = await c.post(f"http://127.0.0.1:{port}/ws-ticket", json={"room_id": room},
                         headers={"Authorization": f"Bearer {token}"})
        return r.status_code, r.json().get("ticket")


def url(port, t, room="sprint"):
    q = f"?ticket={t}" if t else ""
    return f"ws://127.0.0.1:{port}/ws/rooms/{room}{q}"


async def try_connect(label, port, t, origin):
    try:
        async with connect(url(port, t), origin=origin):
            print(f"{label}: connected (unexpected)")
    except InvalidStatus as e:
        print(f"{label}: handshake rejected with HTTP {e.response.status_code}")


async def main():
    _, ta = await ticket(5001, "token_alice")
    _, tb = await ticket(5002, "token_bob")
    async with connect(url(5001, ta), origin=GOOD) as alice, \
            connect(url(5002, tb), origin=GOOD) as bob:
        await asyncio.sleep(0.3)  # let both workers subscribe
        await alice.send(json.dumps({"v": 1, "type": "card_moved", "id": "m1",
                                     "data": {"card": "c7", "to": "done"}}))
        e = json.loads(await asyncio.wait_for(bob.recv(), 5))
        print("bob on worker 2 received:", e["type"], "from", e["from"], e["data"])
        await asyncio.wait_for(alice.recv(), 5)  # alice gets her own event too
        await alice.send(json.dumps({"v": 2, "type": "card_moved"}))
        e = json.loads(await asyncio.wait_for(alice.recv(), 5))
        print("alice sent v=2, got:", e["type"], e["data"])
    status, _ = await ticket(5001, "token_mallory")
    print("mallory (not a member) asks for a ticket:", status)
    async with httpx.AsyncClient() as c:
        r = await c.post("http://127.0.0.1:5001/ws-ticket", json={"room_id": "sprint"},
                         headers={"Authorization": "token_alice"})  # no scheme
    print("ticket request without the Bearer scheme:", r.status_code)
    _, t1 = await ticket(5001, "token_alice")
    await try_connect("valid ticket, forged origin https://evil.example", 5001, t1,
                      "https://evil.example")
    await try_connect("no ticket, allowed origin", 5001, None, GOOD)
    _, t2 = await ticket(5001, "token_alice")
    async with connect(url(5001, t2), origin=GOOD):
        pass
    await try_connect("same ticket used twice", 5001, t2, GOOD)

asyncio.run(main())
Expected output (terminal 3, then the logs of terminals 1 and 2; Redis 8.10)
bob on worker 2 received: card_moved from alice {'card': 'c7', 'to': 'done'}
alice sent v=2, got: error {'reason': 'unsupported message'}
mallory (not a member) asks for a ticket: 403
ticket request without the Bearer scheme: 401
valid ticket, forged origin https://evil.example: handshake rejected with HTTP 403
no ticket, allowed origin: handshake rejected with HTTP 403
same ticket used twice: handshake rejected with HTTP 403

# worker 1 log
[Worker-1] subscribing to Redis channel room:sprint
[Worker-1] alice joined room:sprint from http://localhost:5173
[Worker-1] alice sent card_moved, publishing
[Worker-1] Redis event on room:sprint
[Worker-1] rejected handshake (origin=https://evil.example, user=None)
[Worker-1] rejected handshake (origin=http://localhost:5173, user=None)
[Worker-1] subscribing to Redis channel room:sprint
[Worker-1] alice joined room:sprint from http://localhost:5173
[Worker-1] rejected handshake (origin=http://localhost:5173, user=None)

# worker 2 log
[Worker-2] subscribing to Redis channel room:sprint
[Worker-2] bob joined room:sprint from http://localhost:5173
[Worker-2] Redis event on room:sprint

06. Step 5: check backpressure without a slow network

  1. A slow consumer is hard to produce on a laptop, because TCP buffers absorb a lot. This in-process check replaces the sockets with fakes: one records what it receives, the other never finishes a send. Save it as slow_consumer.py and run python slow_consumer.py. Redis is not contacted: the module creates its Redis client, but the client connects only when it is first used.
Python · slow_consumer.py
"""In-process check of backpressure: one stalled socket must not hold up the room."""
import asyncio

from app.websocket_cluster import Connection, manager


class FakeWS:
    def __init__(self, name, stall=False):
        self.name, self.stall, self.got, self.closed = name, stall, [], None

    async def send_text(self, text):
        if self.stall:
            await asyncio.Event().wait()  # never completes: a stalled client
        self.got.append(text)

    async def close(self, code, reason=""):
        self.closed = code


async def main():
    fast, slow = FakeWS("fast"), FakeWS("slow", stall=True)
    cf, cs = Connection(fast, "fast"), Connection(slow, "slow")
    manager.rooms["r"].update({cf, cs})  # skip the Redis subscription here
    for i in range(150):
        manager.broadcast_local("r", f"m{i}")
        await asyncio.sleep(0)
    await asyncio.sleep(0.1)
    print("fast client received:", len(fast.got), "of 150")
    print("slow client closed with code:", slow.closed,
          "| still in room:", cs in manager.rooms["r"])

asyncio.run(main())
Expected output
[worker] slow is too slow, closing
fast client received: 150 of 150
slow client closed with code: 1008 | still in room: False

07. Check your understanding

Practice check · 3 questions

WebSocket cluster architecture and security check

Three questions evaluating multi-worker fanout, CSWSH defences, and buffer backpressure.

Q1. A server checks the Origin header but accepts any WebSocket without a ticket. What can a script running outside a browser do?
Q2. Why is the WebSocket ticket redeemed with GETDEL rather than GET?
Q3. The server closes the WebSocket before calling accept(). What does a browser client see?
Practice only: not graded, not saved, not evidence.

08. Apply it

Use the same pattern for a different feature of your practice service: a live list of who is viewing each project.

  • Issue single-use tickets from an authenticated route, and check Origin and the ticket before accept().
  • Publish joined and left events to one Redis channel per project, so viewers on different workers see the same list, and unsubscribe when the last local viewer leaves.
  • Presence updates go stale quickly, so when a viewer's outbox is full, drop the oldest update and later send a fresh snapshot instead of closing the socket. Write an in-process check like step 5 that proves a stalled viewer cannot hold up the others.

In the next lesson, you will learn how to design, sign, and deliver reliable outgoing webhooks that partner backend systems can safely trust.

09. Review prompt

Explain how Cross-Site WebSocket Hijacking (CSWSH) works and why CORS does not protect WebSocket endpoints. Describe how a Redis Pub/Sub backplane allows multiple independent worker processes to distribute messages to room members across server instances, and explain the architectural danger of unbounded outbound WebSocket buffers.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check