Connection Management
Best practices for maintaining reliable WebSocket connections.Subscription Management
Subscribe
Subscribe to one or multiple streams:Unsubscribe
Unsubscribe using the subscription ID:Reconnection Strategy
WebSocket connections can drop due to network issues. Always implement reconnection logic.Heartbeat / Ping-Pong
Keep the connection alive with periodic pings.Rate Limits
Best Practices
Always implement reconnection logic
Always implement reconnection logic
Network issues are inevitable. Your application should automatically reconnect with exponential backoff.
Store subscriptions for resubscription
Store subscriptions for resubscription
After reconnecting, you must resubscribe to all channels. Store your subscription list.
Handle message ordering
Handle message ordering
Messages may arrive out of order during high load. Use timestamps and sequence numbers.
Implement timeouts
Implement timeouts
If no message is received for 60 seconds, consider the connection stale and reconnect.
Use compression
Use compression
Enable per-message deflate for bandwidth savings on high-frequency streams.
Separate connections for trading
Separate connections for trading
Use one connection for market data and another for trading to avoid mixing concerns.
Connection States
Monitor connection state to handle different scenarios:| State | Description | Action |
|---|---|---|
CONNECTING | Initial connection | Wait for open event |
OPEN | Connected and ready | Can send/receive messages |
CLOSING | Connection closing | Stop sending messages |
CLOSED | Connection closed | Reconnect if needed |
Error Codes
Common WebSocket close codes:| Code | Reason | Action |
|---|---|---|
| 1000 | Normal closure | No action needed |
| 1001 | Going away | Reconnect |
| 1002 | Protocol error | Check message format |
| 1003 | Unsupported data | Check message content |
| 1006 | Abnormal closure | Reconnect |
| 1008 | Policy violation | Check rate limits |
| 1011 | Server error | Retry with backoff |