Skip to content

WebSocket Events: Disconnection

Disconnections are a normal part of any WebSocket system. They can occur for many reasonsβ€”user-initiated, server-initiated, timeouts, or network failures. Handling these cleanly is essential for a reliable real-time experience.


πŸ”š 1. Why Disconnections Happen

Disconnections can occur due to:

  • User navigates away or closes the browser.
  • Server closes the connection (e.g., due to auth failure, idle timeout, maintenance).
  • Network issues (e.g., mobile devices switching networks).
  • Application-level logic (e.g., user kicked from a room).

🧠 2. Server-Initiated Disconnects

When the server decides to disconnect a client, it should first send a message (if possible) explaining why.

Example:

{
  "type": "disconnect",
  "data": {
    "reason": "unauthorized",
    "code": 4003
  }
}

Then:

await websocket.close(code=4003)

Common Reasons

Code Reason
1008 Policy violation
4001 Inactivity timeout
4003 Unauthorized
4004 Rate limit / Ban

πŸ‘‹ 3. Client-Initiated Disconnects

Clients may close the connection voluntarily:

  • Logging out
  • Navigating away from the app
  • Closing a chat or room

Client Example (JS):

socket.close(1000, "User logged out");

πŸ’‘ 4. Detecting Disconnection on Server

In many frameworks (e.g., FastAPI, Django Channels), you can catch a disconnect with an exception:

FastAPI Example
try:
    while True:
        data = await websocket.receive_text()
        # handle message
except WebSocketDisconnect:
    # Clean up resources, notify other users, etc.
    await handle_disconnect(user_id)

πŸ”„ 5. Reconnection Strategies

Your frontend should attempt reconnection when appropriate:

socket.onclose = (event) => {
  if (event.code !== 1000) {
    setTimeout(() => {
      reconnectSocket();
    }, 3000); // backoff
  }
};

You can use exponential backoff, session resume tokens, or persistent client IDs to restore user state after reconnecting.


πŸ“‹ Disconnection Event Summary

Event Type Direction Description
disconnect Server β†’ Client Server intends to close connection
onclose Browser Event Fired when connection closes
WebSocketDisconnect Server Exception Triggered when client disconnects

βœ… Best Practices

  • Always send a final disconnect event when closing a connection server-side (if time permits).
  • Use proper close codes so clients can act appropriately.
  • Clean up user state (rooms, sessions, database locks) after disconnects.
  • Reconnect intelligentlyβ€”don’t hammer the server on failure.
  • Log all disconnects with reasons and codes for observability.

πŸ”š Next Steps