C.W.K.
Stream
Lesson 03 of 07 · published

Client Identification

~12 min · management, user-id, multi-device

Level 0Poller
0 XP0/60 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

One user, many devices

Real users connect from a phone, a laptop, and an iPad simultaneously. A naive user_id → ws map breaks the moment that happens — the second connection silently overwrites the first. The fix is a one-to-many index: user_id → set of connection_ids, and a separate connection_id → WebSocket.

Connection IDs

Generate a random ID at connect time and use it everywhere internally. The client does not need to know it. This makes broadcasting "to this connection" possible without exposing implementation details, and lets you add per-connection rate limits, telemetry, and session metadata.

Code

Multi-device-aware manager·python
import uuid
from typing import Dict, Set

class IdentifiedConnectionManager:
    def __init__(self):
        self.connections: Dict[str, WebSocket] = {}      # conn_id -> ws
        self.user_conns: Dict[str, Set[str]] = {}        # user_id -> conn_ids

    async def connect(self, ws: WebSocket, user_id: str) -> str:
        await ws.accept()
        conn_id = uuid.uuid4().hex[:8]
        self.connections[conn_id] = ws
        self.user_conns.setdefault(user_id, set()).add(conn_id)
        return conn_id

    def disconnect(self, conn_id: str, user_id: str):
        self.connections.pop(conn_id, None)
        conns = self.user_conns.get(user_id)
        if conns:
            conns.discard(conn_id)
            if not conns:
                self.user_conns.pop(user_id, None)

    async def send_to_user(self, user_id: str, message: dict) -> int:
        '''Send to ALL connections for a user (multi-device fan-out).'''
        sent = 0
        for conn_id in list(self.user_conns.get(user_id, ())):
            ws = self.connections.get(conn_id)
            if ws is None:
                continue
            try:
                await ws.send_json(message)
                sent += 1
            except Exception:
                self.disconnect(conn_id, user_id)
        return sent

External links

Exercise

Connect from two browsers (different windows) as the same user_id. Send a direct message via send_to_user(user_id, ...). Verify both browsers receive it. Now close one — the other must keep working without any code change.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.