# WebSockets in Python with asyncio — WebSockets & Server-Sent Events

Source: https://www.skillbyai.com/en/realtime-web/rt-ws-python

> Write an asyncio WebSocket server with the websockets library and explain how one coroutine per connection scales.

## One coroutine per connection

Python's popular `websockets` library is built on `asyncio`. You write a **handler coroutine** that receives one connection object; the library runs one handler per client. `async for message in websocket` waits for messages without blocking the thread, so a single process can hold thousands of idle connections, because waiting costs memory but almost no CPU. When the client disconnects, the loop ends, or a `ConnectionClosed` exception is raised if the close was not clean. Recent versions provide the `websockets.asyncio.server.serve` API used below. The catch with asyncio is that **one blocking call stalls every connection**: a synchronous database driver, `time.sleep()` or heavy CPU work inside a handler freezes all clients on that event loop. Use async drivers, `await asyncio.sleep()`, and `asyncio.to_thread()` or a process pool for CPU-bound work. Frameworks such as FastAPI and Django Channels wrap the same ideas behind their own WebSocket routes.

## An echo server with websockets

Install with `pip install websockets`. The handler loops over incoming messages and replies to each.

```python
import asyncio

from websockets.asyncio.server import serve
from websockets.exceptions import ConnectionClosed

async def echo(websocket):
    try:
        async for message in websocket:
            await websocket.send(f"echo: {message}")
    except ConnectionClosed:
        pass  # client went away without a clean close

async def main():
    async with serve(echo, "localhost", 8765) as server:
        await server.serve_forever()

if __name__ == "__main__":
    asyncio.run(main())
```

## Find blocking calls early

Run the event loop in debug mode with `PYTHONASYNCIODEBUG=1` (or `asyncio.run(main(), debug=True)`). asyncio then logs callbacks that take longer than 100 ms, which points straight at the blocking call.

## One waiter, many tables

An asyncio server is a single efficient waiter serving many tables: while one table reads the menu, the waiter takes another order. If the waiter stops to cook a dish personally, every table waits. CPU-heavy work belongs in the kitchen, meaning a thread or process pool.

**Quiz:** Inside an asyncio WebSocket handler, a developer calls `time.sleep(2)`. What happens?

- [ ] Only that client waits 2 seconds
- [ ] The library automatically moves it to a thread
- [x] Every connection served by that event loop is frozen for 2 seconds
- [ ] The connection is closed with code 1011

*Answer:* Every connection served by that event loop is frozen for 2 seconds. `time.sleep` blocks the single event loop thread, so no other coroutine can run. Use `await asyncio.sleep(2)` instead.
