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:
Then:
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):
π‘ 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
- Custom Events: Handle app-specific events like
user_left
. - Error Handling: Handle unexpected disconnects gracefully.
- Clients: Implement reconnection and state recovery.