WebSockets in Python with `websockets` and asyncio
Python's websockets library, built on asyncio, is the most common way to implement WebSocket servers and clients without a full web framework: it exposes async/await-based coroutines where each connection runs as an independent asyncio task, letting a single-threaded event loop handle thousands of concurrent connections as long as handlers don't block on synchronous I/O. Because Python's GIL means true parallel CPU work still needs multiprocessing or a thread pool, any CPU-heavy processing inside a message handler (e.g. image resizing) should be offloaded via loop.run_in_executor() rather than run inline, or it will stall every other connection sharing that event loop.
Cricket analogy: It's like a single umpire efficiently managing signals across several simultaneous net practice sessions by quickly attending to whichever bowler is ready next, but if one session needs a lengthy pitch inspection, that umpire is stuck and can't attend to the others until it's done.
Building an Async Server
A minimal server registers an async def handler(websocket) coroutine passed to websockets.serve(), iterating incoming messages with async for message in websocket, which cleanly exits the loop when the client disconnects instead of requiring manual close-detection logic. State that must be shared across connections, such as a set of currently connected clients for broadcasting, needs to live outside individual handler closures (commonly a module-level set() or a class instance) and be guarded against concurrent-modification issues if handlers can run interleaved awaits that touch it.
Cricket analogy: It's like a scorer's shared master scoreboard that every commentator's individual booth reads from and updates, rather than each commentator keeping a private, disconnected tally that never syncs with the others.
import asyncio
import json
import websockets
CONNECTED = set()
async def handler(websocket):
CONNECTED.add(websocket)
try:
async for message in websocket:
data = json.loads(message)
outgoing = json.dumps({"from": id(websocket), "text": data["text"]})
# Broadcast to everyone except the sender
await asyncio.gather(*[
client.send(outgoing) for client in CONNECTED if client != websocket
])
except websockets.exceptions.ConnectionClosed:
pass
finally:
CONNECTED.remove(websocket)
async def main():
async with websockets.serve(handler, "0.0.0.0", 8765, ping_interval=20, ping_timeout=20):
await asyncio.Future() # run forever
if __name__ == "__main__":
asyncio.run(main())
Client-Side Connections
On the client side, websockets.connect(uri) used as an async with context manager gives you a connection that closes automatically when the block exits, which is the idiomatic pattern for scripts and services rather than manually calling .close() in a finally block. Because it's built on asyncio, a Python WebSocket client integrates naturally with other async code (database queries, HTTP calls via aiohttp) in the same event loop, letting you await a socket message and an unrelated async database write in the same coroutine without threads.
Cricket analogy: It's like a fielder returning to their designated position automatically the instant the ball is dead, rather than the captain having to manually walk over and remind them every time.
Passing ping_interval and ping_timeout to websockets.serve() (or connect()) enables automatic keepalive pings; the library closes the connection if a pong isn't received within ping_timeout, which is a simple way to get the heartbeat behavior you'd otherwise hand-roll in Node's ws.
Integrating with FastAPI
FastAPI has WebSocket support built directly into its routing system via @app.websocket('/ws'), giving you await websocket.accept(), await websocket.receive_text() / receive_json(), and await websocket.send_json() inside the same application that also serves your REST endpoints, dependency injection, and Pydantic validation. This is convenient for apps that need both a REST API and a small number of real-time endpoints, but FastAPI's WebSocket routes still run on the same asyncio event loop as everything else, so the blocking-call caveat from the raw websockets library applies equally here.
Cricket analogy: It's like a stadium's operations center handling both the official scoreboard feed and the live ticket-gate system from the same control room, sharing staff and infrastructure rather than running two disconnected operations.
A synchronous blocking call anywhere inside a FastAPI async WebSocket route (a non-async database driver, a CPU-bound loop, time.sleep) stalls the entire event loop, freezing every other WebSocket and HTTP request the process is handling, not just the one connection. Use async drivers or run_in_executor for anything that can block.
- The
websocketslibrary runs on asyncio, handling each connection as an independent coroutine on one event loop. - Python's GIL means CPU-heavy work inside a handler must be offloaded via run_in_executor to avoid stalling other connections.
async for message in websocketcleanly iterates until disconnect without manual close-detection logic.- Shared state like a connected-clients set must live outside individual handler closures at module or class scope.
websockets.connect()as an async context manager auto-closes the connection when the block exits.- ping_interval and ping_timeout provide built-in heartbeat/keepalive behavior.
- FastAPI integrates WebSocket routes into the same app as REST endpoints, but shares the same event loop and blocking-call caveats.
Practice what you learned
1. Why must CPU-heavy work inside a Python websockets handler be offloaded via run_in_executor?
2. What does `async for message in websocket` do when the client disconnects?
3. Where should state shared across multiple WebSocket connections (like a set of connected clients) live?
4. What do ping_interval and ping_timeout configure in the websockets library?
5. In FastAPI, why does a blocking synchronous database call inside a WebSocket route matter beyond that one connection?
Was this page helpful?
You May Also Like
Building a WebSocket Server with Node.js
Learn how to stand up a production-ready WebSocket server in Node.js using the `ws` library, from the handshake through broadcasting and horizontal scaling.
Authenticating WebSocket Connections
Learn how to securely authenticate long-lived WebSocket connections, including handshake-time token validation, per-message authorization, and common security pitfalls.
Socket.IO Explained
Understand what Socket.IO adds on top of raw WebSockets — rooms, namespaces, automatic reconnection, and transport fallback — and when it's the wrong tool for the job.
Related Reading
Related Study Notes in Web Development
Browse all study notesWebAssembly Study Notes
WebAssembly · 30 topics
Web DevelopmentgRPC Study Notes
Protocol Buffers · 30 topics
Web DevelopmentSpring Boot Study Notes
Java · 30 topics
Web DevelopmentFlask Study Notes
Python · 30 topics
Web DevelopmentDjango Study Notes
Python · 30 topics
Web DevelopmentNext.js Study Notes
JavaScript · 30 topics