WebSocket & Real-Time Expert
Build reliable real-time communication systems using WebSockets, Server-Sent Events, and managed real-time services.
Activation Triggers
Activate on: "WebSocket", "real-time", "SSE", "Socket.io", "live updates", "push notifications", "bidirectional", "presence", "live cursors", "collaborative editing"
NOT for: Message queue setup → event-driven-architecture-expert | Gateway WebSocket routing → api-gateway-reverse-proxy-expert | Streaming data pipelines → streaming-pipeline-architect
Quick Start
- Choose protocol — WebSocket for bidirectional, SSE for server-push, WebTransport for low-latency
- Plan reconnection — exponential backoff with jitter, resume from last event ID
- Design message format — typed JSON with
type discriminator and monotonic sequence IDs
- Scale horizontally — use Redis Pub/Sub or NATS as a broadcast backplane
- Handle presence — heartbeat-based with configurable timeout (30s default)
Core Capabilities
| Domain |
Technologies |
| WebSocket |
ws (Node), Socket.io 4.8+, uWebSockets.js |
| SSE |
Native EventSource, @microsoft/fetch-event-source |
| Managed |
Supabase Realtime, Ably, Pusher, PartyKit |
| Scaling |
Redis Pub/Sub, NATS, @socket.io/redis-adapter |
| Protocols |
WebSocket (RFC 6455), SSE, WebTransport (HTTP/3) |
Architecture Patterns
Scaled WebSocket with Redis Backplane
Client A ──ws──→ Server 1 ←──redis pub/sub──→ Server 2 ←──ws── Client B
│ │
└─────── Redis Cluster ───────┘
Each server subscribes to channels. When Server 1 receives a message
for a room, it publishes to Redis. Server 2 picks it up and forwards
to its connected clients.
SSE with Last-Event-ID Resume
// Server: SSE endpoint with resume support
app.get('/events', (req, res) => {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
});
const lastId = parseInt(req.headers['last-event-id'] || '0');
// Replay missed events from store
const missed = eventStore.since(lastId);
missed.forEach(evt => {
res.write(`id: ${evt.id}\nevent: ${evt.type}\ndata: ${JSON.stringify(evt.data)}\n\n`);
});
// Subscribe to new events
const unsub = eventBus.subscribe(evt => {
res.write(`id: ${evt.id}\nevent: ${evt.type}\ndata: ${JSON.stringify(evt.data)}\n\n`);
});
req.on('close', unsub);
});
Presence with Heartbeat
// Client sends heartbeat every 15s
const HEARTBEAT_INTERVAL = 15_000;
const PRESENCE_TIMEOUT = 45_000; // 3 missed heartbeats = offline
// Server tracks presence
const presence = new Map<string, { userId: string; lastSeen: number }>();
ws.on('message', (msg) => {
const { type, userId } = JSON.parse(msg);
if (type === 'heartbeat') {
presence.set(userId, { userId, lastSeen: Date.now() });
}
});
// Sweep stale presence every 10s
setInterval(() => {
const cutoff = Date.now() - PRESENCE_TIMEOUT;
for (const [id, p] of presence) {
if (p.lastSeen < cutoff) {
presence.delete(id);
broadcast({ type: 'presence:leave', userId: id });
}
}
}, 10_000);
Anti-Patterns
- No reconnection logic — connections will drop; always implement reconnect with exponential backoff and jitter
- Polling disguised as real-time — if you poll every 1s over WebSocket, just use SSE or actual polling
- Single server assumption — WebSocket state is per-server; you need a pub/sub backplane for horizontal scaling
- Unbounded message buffers — set max buffer size and drop/queue when clients are slow (backpressure)
- Missing heartbeat — idle connections get killed by proxies and load balancers (typical timeout: 60s)
Quality Checklist
1---
2license: Apache-2.0
3name: websocket-realtime-expert
4description: "WebSockets, SSE, and real-time communication with Socket.io and native APIs. Activate on: WebSocket, real-time, SSE, Socket.io, live updates, push notifications, bidirectional, presence. NOT for: message queue infrastructure (use event-driven-architecture-expert), API gateway routing (use api-gateway-reverse-proxy-expert)."
5allowed-tools: Read,Write,Edit,Bash(npm:*,npx:*)
6category: Backend & Infrastructure
7tags:
8 - websocket
9 - realtime
10 - sse
11 - socket-io
12 - push
13pairs-with:
14 - skill: event-driven-architecture-expert
15 reason: Backend events feed real-time channels
16 - skill: cache-strategy-invalidation-expert
17 reason: Cache invalidation triggers real-time updates
18 - skill: api-gateway-reverse-proxy-expert
19 reason: WebSocket upgrade handling at the gateway
20metadata:
21 source: https://skillmd.com/skills/curiositech/websocket-realtime-expert
22---
23
24# WebSocket & Real-Time Expert
25
26Build reliable real-time communication systems using WebSockets, Server-Sent Events, and managed real-time services.
27
28## Activation Triggers
29
30**Activate on:** "WebSocket", "real-time", "SSE", "Socket.io", "live updates", "push notifications", "bidirectional", "presence", "live cursors", "collaborative editing"
31
32**NOT for:** Message queue setup → `event-driven-architecture-expert` | Gateway WebSocket routing → `api-gateway-reverse-proxy-expert` | Streaming data pipelines → `streaming-pipeline-architect`
33
34## Quick Start
35
361. **Choose protocol** — WebSocket for bidirectional, SSE for server-push, WebTransport for low-latency
372. **Plan reconnection** — exponential backoff with jitter, resume from last event ID
383. **Design message format** — typed JSON with `type` discriminator and monotonic sequence IDs
394. **Scale horizontally** — use Redis Pub/Sub or NATS as a broadcast backplane
405. **Handle presence** — heartbeat-based with configurable timeout (30s default)
41
42## Core Capabilities
43
44| Domain | Technologies |
45|--------|-------------|
46| **WebSocket** | ws (Node), Socket.io 4.8+, uWebSockets.js |
47| **SSE** | Native EventSource, @microsoft/fetch-event-source |
48| **Managed** | Supabase Realtime, Ably, Pusher, PartyKit |
49| **Scaling** | Redis Pub/Sub, NATS, @socket.io/redis-adapter |
50| **Protocols** | WebSocket (RFC 6455), SSE, WebTransport (HTTP/3) |
51
52## Architecture Patterns
53
54### Scaled WebSocket with Redis Backplane
55
56```
57Client A ──ws──→ Server 1 ←──redis pub/sub──→ Server 2 ←──ws── Client B
58 │ │
59 └─────── Redis Cluster ───────┘
60
61Each server subscribes to channels. When Server 1 receives a message
62for a room, it publishes to Redis. Server 2 picks it up and forwards
63to its connected clients.
64```
65
66### SSE with Last-Event-ID Resume
67
68```typescript
69// Server: SSE endpoint with resume support
70app.get('/events', (req, res) => {
71 res.writeHead(200, {
72 'Content-Type': 'text/event-stream',
73 'Cache-Control': 'no-cache',
74 'Connection': 'keep-alive',
75 });
76
77 const lastId = parseInt(req.headers['last-event-id'] || '0');
78 // Replay missed events from store
79 const missed = eventStore.since(lastId);
80 missed.forEach(evt => {
81 res.write(`id: ${evt.id}\nevent: ${evt.type}\ndata: ${JSON.stringify(evt.data)}\n\n`);
82 });
83
84 // Subscribe to new events
85 const unsub = eventBus.subscribe(evt => {
86 res.write(`id: ${evt.id}\nevent: ${evt.type}\ndata: ${JSON.stringify(evt.data)}\n\n`);
87 });
88 req.on('close', unsub);
89});
90```
91
92### Presence with Heartbeat
93
94```typescript
95// Client sends heartbeat every 15s
96const HEARTBEAT_INTERVAL = 15_000;
97const PRESENCE_TIMEOUT = 45_000; // 3 missed heartbeats = offline
98
99// Server tracks presence
100const presence = new Map<string, { userId: string; lastSeen: number }>();
101
102ws.on('message', (msg) => {
103 const { type, userId } = JSON.parse(msg);
104 if (type === 'heartbeat') {
105 presence.set(userId, { userId, lastSeen: Date.now() });
106 }
107});
108
109// Sweep stale presence every 10s
110setInterval(() => {
111 const cutoff = Date.now() - PRESENCE_TIMEOUT;
112 for (const [id, p] of presence) {
113 if (p.lastSeen < cutoff) {
114 presence.delete(id);
115 broadcast({ type: 'presence:leave', userId: id });
116 }
117 }
118}, 10_000);
119```
120
121## Anti-Patterns
122
1231. **No reconnection logic** — connections will drop; always implement reconnect with exponential backoff and jitter
1242. **Polling disguised as real-time** — if you poll every 1s over WebSocket, just use SSE or actual polling
1253. **Single server assumption** — WebSocket state is per-server; you need a pub/sub backplane for horizontal scaling
1264. **Unbounded message buffers** — set max buffer size and drop/queue when clients are slow (backpressure)
1275. **Missing heartbeat** — idle connections get killed by proxies and load balancers (typical timeout: 60s)
128
129## Quality Checklist
130
131- [ ] Reconnection with exponential backoff and jitter implemented
132- [ ] Last-Event-ID or sequence-based resume for missed messages
133- [ ] Heartbeat/ping-pong keeps connections alive (every 15-30s)
134- [ ] Redis/NATS backplane for multi-server deployments
135- [ ] Message schema versioned with `type` discriminator
136- [ ] Backpressure handling for slow consumers
137- [ ] Connection count monitoring with alerts
138- [ ] Graceful degradation: SSE fallback if WebSocket blocked
139- [ ] Authentication on connection (verify token before upgrade)
140- [ ] Load tested: target connections per server validated