WebSocket Events: Connection Lifecycle
This section describes how WebSocket connections are initiated, maintained, and terminated. Understanding the lifecycle events is critical for managing real-time sessions and user state effectively.
π 1. Connection Open
When a client initiates a WebSocket connection, the server must decide whether to accept or reject the request.
Client β Server
- Initiates connection via
new WebSocket()
or equivalent. - Optionally provides query parameters (e.g., token) for authentication.
Server Actions
- Validate the client (e.g., auth token).
- Accept the connection using
websocket.accept()
. - Optionally send an acknowledgment message.
Example:
{
"type": "connection_established",
"data": {
"user_id": "abc123",
"timestamp": "2025-08-04T12:00:00Z"
}
}
Server-side (FastAPI):
@app.websocket("/ws")
async def connect(websocket: WebSocket):
await websocket.accept()
await websocket.send_json({
"type": "connection_established",
"data": {
"user_id": "abc123",
"timestamp": datetime.utcnow().isoformat()
}
})
β€οΈ 2. Heartbeats (Ping/Pong)
To detect broken connections or idle clients, many systems use ping/pong messages.
Client-side (Optional):
Server Response:
Or vice versaβsome servers send ping
, and clients respond with pong
.
Purpose:
- Detect disconnected clients.
- Prevent idle timeouts (common on load balancers and proxies).
- Keep connections alive in backgrounded apps.
β 3. Connection Close
The server or client can choose to close the connection at any time.
Server β Client:
- The server can follow this message with a call to
websocket.close(code=4003)
. - Clients should gracefully handle
onclose
events.
Standard Close Codes:
Code | Meaning |
---|---|
1000 |
Normal closure |
1008 |
Policy violation (e.g. auth fail) |
1011 |
Internal error |
4003 |
Custom code: Unauthorized |
4004 |
Custom code: Banned / Throttled |
π Recommended Event Types
Event Type | Direction | Description |
---|---|---|
connection_established |
Server β Client | Sent after a successful connection |
ping |
Client β Server | Optional heartbeat message |
pong |
Server β Client | Response to ping |
disconnect |
Server β Client | Server intends to close connection |
error |
Server β Client | Fatal connection error or violation |
π§ Best Practices
- Acknowledge successful connections explicitly (e.g.,
connection_established
). - Implement ping/pong heartbeats every 30β60 seconds.
- Use close codes consistently for client-side handling.
- Log all connect/disconnect events on the backend for debugging and metrics.
π Next Steps
- Custom Events: Define your application's business-level messages.
- Authentication: Secure connections before accepting.
- Error Handling: Manage failures gracefully.