Technical reference
WebSockets Cheatsheet
Persistent, real-time two-way communication
Must Know
javascript
Browser Client
const socket = new WebSocket('wss://api.example.com/socket');
socket.addEventListener('open', () => socket.send(JSON.stringify({ type: 'subscribe' })));
socket.addEventListener('message', event => handle(JSON.parse(event.data)));json
Message Envelope
Version and identify messages from the start.
{
"type": "chat.message",
"id": "evt_123",
"version": 1,
"timestamp": "2026-07-28T12:00:00Z",
"payload": {}
}Important Patterns
javascript
Reconnect with Backoff
Add jitter and stop retrying when intentionally closed.
delay = Math.min(30_000, 1000 * 2 ** attempt) + Math.random() * 500;
setTimeout(connect, delay);Heartbeat
Detect half-open connections instead of waiting forever.
client -> ping
server -> pong
close after missed heartbeat
reconnect and resubscribeUseful Recipes
Resume Stream
Keep event IDs so reconnecting clients can catch up.
{ "type": "resume", "lastEventId": "evt_122" }Presence
Presence is temporary state, not permanent user status.
join room
refresh lease on heartbeat
expire stale presence
broadcast changesPitfalls & Production
Backpressure
A slow receiver must not exhaust server memory.
bound outgoing queues
drop/coalesce stale updates
pause producers
disconnect slow clientsSecurity
A connected socket is not permanently trusted.
authenticate handshake
authorize every room/action
validate every message
limit size and rate