✓ Recommended
WebSocket Real-Time Patterns
WebSocket connections for real-time features with reconnection, heartbeats, and state sync.
CLAUDE.md
# WebSocket Real-Time Patterns
You are an expert in WebSocket protocols, real-time web applications, and event-driven architecture.
Connection Management:
- Create connection: `const ws = new WebSocket('wss://api.example.com/ws')`
- Always use wss:// in production — never unencrypted ws://
- Handle all lifecycle events: onopen, onmessage, onclose, onerror
- Implement exponential backoff reconnection: 1s, 2s, 4s, 8s... up to 30s max
- Use a reconnection counter and give up after N attempts with user notification
Message Protocol:
- Use JSON for messages with a consistent envelope: `{ type: 'chat.message', payload: { ... }, id: 'uuid' }`
- Type discriminated unions for message types: `type WSMessage = ChatMessage | PresenceUpdate | SystemEvent`
- Include message IDs for acknowledgment and deduplication
- Use binary messages (ArrayBuffer) for high-frequency data (game state, audio)
Heartbeat / Keep-Alive:
- Send ping every 30 seconds to detect dead connections
- Server responds with pong — if no pong in 5s, reconnect
- Use the WebSocket ping/pong frames or application-level JSON pings
- Reset heartbeat timer on any incoming message
State Synchronization:
- On reconnect, request full state snapshot — don't assume incremental updates suffice
- Use version vectors or sequence numbers to detect missed messages
- Implement optimistic updates: apply locally, confirm with server ack
- Buffer outgoing messages during disconnection; flush on reconnect
Scaling Patterns:
- Use rooms/channels to scope message delivery: `{ type: 'subscribe', channel: 'room-123' }`
- Server-side: use pub/sub (Redis) to fan out messages across WebSocket server instances
- Consider Socket.IO for automatic fallback (long-polling) in hostile network environments
- Use Server-Sent Events (SSE) instead of WebSocket for server-to-client-only streams
Security:
- Authenticate via token in the initial HTTP upgrade request (query param or cookie)
- Validate and sanitize all incoming messages on the server
- Rate limit messages per connection: max 50 messages/second per client
- Never trust client-provided user IDs — resolve from auth token server-side
Add to your project root CLAUDE.md file, or append to an existing one.