python network_error ai_generated true

asyncio.TimeoutError: WebSocket receive timed out

ID: python/starlette-websocket-timeout

Also available as: JSON · Markdown · 中文
80%Fix Rate
81%Confidence
0Evidence
2024-08-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

A WebSocket receive operation exceeds the configured timeout period.

generic

中文

WebSocket接收操作超过了配置的超时时间。

Workarounds

  1. 90% success Use asyncio.wait_for with a reasonable timeout
    try:
        data = await asyncio.wait_for(websocket.receive_text(), timeout=10)
    except asyncio.TimeoutError:
        await websocket.close(code=1000)
  2. 85% success Set timeout in the WebSocket endpoint configuration
    from starlette.websockets import WebSocketEndpoint
    class MyEndpoint(WebSocketEndpoint):
        receive_timeout = 30

Dead Ends

Common approaches that don't work:

  1. Increasing timeout to an extremely high value 60% fail

    May cause resource exhaustion; not a real fix.

  2. Ignoring the timeout and retrying indefinitely 85% fail

    Leads to infinite loop and resource leak.