home / skills / hoangnguyen0403 / agent-skills-standard / real-time

real-time skill

/skills/nestjs/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-time

Review the files below or copy the command above to add this skill to your agents.

Files (1)
SKILL.md
2.4 KB
---
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.

Overview

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.

How this skill works

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.

When to use it

  • Use WebSockets for interactive, low-latency bi-directional features (chat, multiplayer, collaborative editing).
  • Use SSE for server-to-client streams like notifications, live feeds, tickers, and CI log streaming.
  • Use long polling only as a fallback or for extremely low-frequency updates (e.g., job status checks every 10 minutes).
  • Choose ws (Fastify) adapter when extreme throughput and minimal protocol overhead matter.
  • Prefer Socket.io when you need rooms, namespaces, automatic reconnection, and richer semantics.

Best practices

  • Keep WebSocket gateways thin: delegate all business logic to Services or a Command Bus.
  • Scale WebSockets across pods with a Redis adapter (@socket.io/redis-adapter) to publish/subscribe events cluster-wide.
  • For SSE at scale use HTTP/2 to avoid connection limits and ensure stateless, load-balancer-friendly behavior.
  • Validate JWT or other credentials during handleConnection() and disconnect immediately on failure; do not rely on standard HTTP guards alone.
  • Apply strict rate limiting and per-event throttling to prevent socket flooding and resource exhaustion.

Example use cases

  • Chat application with rooms and presence using Socket.io and Redis adapter for scaling.
  • Live trading ticker using ws adapter on Fastify for minimal latency and high throughput.
  • Notification center using SSE over HTTP/2 for browser-friendly, uni-directional updates.
  • CI log streaming using SSE to push build logs with low server-side complexity.
  • Collaborative editor using WebSockets for real-time cursors and edits, delegating conflict resolution to backend services.

FAQ

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.