WebSocket limits¶
Enforce separate limits on WebSocket connection handshakes (limiter.limit) and per-message throughput (limiter.meter + meter.hit()):
connections = limiter.limit("10/minute")
messages = limiter.meter("3/minute", scope="chat messages")
@app.websocket("/chat", dependencies=[Depends(connections)])
async def chat(websocket: WebSocket, meter: Annotated[Meter, Depends(messages)]) -> None:
await websocket.accept()
async for text in websocket.iter_text():
decision = await meter.hit()
if decision.allowed:
await websocket.send_text(text.upper())
else:
wait = math.ceil(decision.retry_after)
await websocket.send_text(f"Slow down: try again in {wait} seconds.")
Key details¶
- Per-message handling:
await meter.hit()consumes a unit only if it fits and returns aDecision. Decide whether to send a warning, drop the frame, or close with code1008(Policy Violation). - Handshake rejections: Callers over the connection limit—or already out of message quota—receive HTTP
429before the WebSocket handshake completes, on servers that implement the ASGI WebSocket Denial Response extension. On other servers the handshake still fails, without that status. - Persistent across reconnects: Message quotas follow the caller key, not the socket instance, so reconnecting does not reset the allowance.
- Distinct scopes: Give the message meter its own
scope=if it uses the same rate as the connection limit. - Use
HTTPConnectionin custom keys: FastAPI does not injectRequeston WebSocket routes; type custom keys against Starlette'sHTTPConnection(as all built-inpaceapikeys do).
Full source: examples/websocket_messages.py.