home / skills / hoangnguyen0403 / agent-skills-standard / real-time
This skill guides NestJS real-time patterns with WebSocket and SSE scaling, security, and architecture for reliable, scalable communications.
npx playbooks add skill hoangnguyen0403/agent-skills-standard --skill real-timeReview the files below or copy the command above to add this skill to your agents.
---
name: NestJS Real-Time
description: WebSocket and SSE selection strategies and scaling.
metadata:
labels: [nestjs, websockets, sse, socket.io]
triggers:
files: ['**/*.gateway.ts', '**/*.controller.ts']
keywords: [WebSocketGateway, SubscribeMessage, Sse, Socket.io]
---
# Real-Time & WebSockets
## **Priority: P1 (OPERATIONAL)**
WebSocket and real-time communication patterns with NestJS.
- **WebSockets (Bi-directional)**: Use for Chat, Multiplayer Games, Collaborative Editing.
- _High Complexity_: Requires custom scaling (Redis Adapter) and sticky sessions (sometimes).
- **Server-Sent Events (SSE) (Uni-directional)**: Use for Notifications, Live Feeds, Tickers, CI Log streaming.
- _Low Complexity_: Standard HTTP. Works with standard Load Balancers. Easy to secure.
- _NestJS_: Use `@Sse('route')` returning `Observable<MessageEvent>`.
- **Long Polling**: Use **only** as a fallback or for extremely low-frequency updates (e.g., job status check every 10m).
- _Impact_: High header overhead. Blocks threads if not handled carefully.
## WebSockets Implementation
- **Socket.io**: Default choice. Features "Rooms", "Namespaces", and automatic reconnection. Heavy protocol.
- **Fastify/WS**: Use `ws` adapter if performance is critical (e.g., high-frequency trading updates) and you don't need "Rooms" logic.
## Scaling (Critical)
- **WebSockets**: In K8s, a client connects to Pod A. If Pod B emits an event, the client won't receive it.
- **Solution**: **Redis Adapter** (`@socket.io/redis-adapter`). Every pod publishes to Redis; Redis distributes to all other pods.
- **SSE**: Stateless. No special adapter needed, but be aware of **Connection Limits** (6 concurrent connections per domain in HTTP/1.1; virtually unlimited in HTTP/2).
- **Rule**: Must use **HTTP/2** for SSE at scale.
## Security
- **Handshake Auth**: Standard HTTP Guards don't trigger on Ws connection efficiently.
- **Pattern**: Validate JWT during the `handleConnection()` lifecycle method. Disconnect immediately if invalid.
- **Rate Limiting**: Sockets are expensive. Apply strict throttling on "Message" events to prevent flooding.
## Architecture
- **Gateway != Service**: The `WebSocketGateway` should **only** handle client comms (Join Room, Ack message).
- **Rule**: Delegate business logic to a Service or Command Bus.
- **Events**: Use `AsyncApi` or `SocketApi` decorators (from community packages) to document WS events similarly to OpenAPI.
This skill captures NestJS real-time patterns, WebSocket vs SSE selection, and scaling strategies for production systems. It focuses on practical choices—Socket.io vs ws, SSE trade-offs, scaling with Redis, and security for socket connections. The guidance is concise and oriented toward operational readiness and maintainability.
It explains where to use bi-directional WebSockets, uni-directional SSE, and long polling, and describes implementation options (Socket.io, ws/Fastify). It outlines scaling approaches: Redis Adapter for multi-pod WebSockets and HTTP/2 for high-scale SSE. It also prescribes security and architectural patterns for gateways, authentication, and rate limiting.
Do I always need Redis for WebSockets?
No. Redis is required only when you run multiple pods and need events delivered across them. Single-node deployments or sticky sessions can avoid Redis, but Redis is the reliable horizontal-scaling solution.
When should I prefer SSE over WebSockets?
Prefer SSE when updates are uni-directional, frequency is moderate, and you want simpler HTTP-based scaling and security. For many browser notifications, SSE over HTTP/2 is lighter and easier to operate than WebSockets.