Concepts 🚀 Project 🧮 Labs
📚 Learn / Real-time & WebSockets / Connection manager pattern

Connection manager pattern

Track active connections in a dict. broadcast() sends to all; send_json() sends to one.

Code example

class ConnectionManager:
    def __init__(self):
        self.active = {}

    async def connect(self, ws, cid):
        await ws.accept()
        self.active[cid] = ws

    async def broadcast(self, msg):
        for ws in list(self.active.values()):
            await ws.send_json(msg)

How it works

Every WebSocket server needs a registry of active connections. The ConnectionManager class in main.py is a thin wrapper around a dict: connect() accepts the WS and stores it; disconnect() removes it; broadcast() iterates and sends to all; send_json() sends to one. The notebook terminal has its own per-user manager because each terminal is a dedicated PTY, not a broadcast channel. Always handle send failures — a closed connection will raise, and you need to clean it up.

🔍 Where this is used in OpenBenchML app/main.py — ws_manager is the global ConnectionManager. app/routes/notebook.py — _terminal_manager for per-user PTYs.