0Pricing
NestJS Enterprise Backend APIs · Lesson

Scaling Realtime with a Redis Pub/Sub Adapter

Synchronize socket state across multiple instances using the Redis IoAdapter for horizontal scaling.

The Multi-Instance Problem

A single NestJS WebSocket gateway keeps every connected socket in the memory of one Node process. The moment you scale horizontally behind a load balancer, that assumption breaks.

  • Client A connects to instance 1.
  • Client B connects to instance 2.
  • When instance 1 emits to a room, instance 2 never hears about it — so Client B misses the message.

To fix this we need a shared message bus that lets every instance broadcast events to every other instance. Redis Pub/Sub is the canonical choice, and Socket.IO ships an adapter for exactly this.

How the Redis Adapter Works

The @socket.io/redis-adapter replaces Socket.IO's in-memory adapter. Whenever your code calls server.to(room).emit(...), the adapter publishes that event to a Redis channel instead of only delivering it locally.

  • Every instance subscribes to the same Redis channels.
  • An emit on instance 1 is published to Redis, then every subscribed instance (including instance 2) receives it and delivers it to its own local sockets.
  • Redis is only a relay — socket connections still live on each node; no socket state is stored in Redis.

This means room membership, broadcasts, and even server.emit() fan out correctly across the whole cluster.

All lessons in this course

  1. WebSocket Gateways with the Socket.IO Adapter
  2. Authenticating and Guarding Socket Connections
  3. Server-Sent Events for One-Way Push
  4. Scaling Realtime with a Redis Pub/Sub Adapter
← Back to NestJS Enterprise Backend APIs