การปรับขนาดระบบเรียลไทม์ด้วยอะแดปเตอร์ Redis Pub/Sub
ซิงโครไนซ์สถานะซ็อกเก็ตข้ามหลายอินสแตนซ์ด้วย Redis IoAdapter เพื่อการปรับขนาดในแนวนอน
การปรับขนาดระบบเรียลไทม์ด้วยอะแดปเตอร์ Redis Pub/Sub เป็นบทเรียน NestJS Enterprise Backend APIs ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน NestJS Enterprise Backend APIs และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส NestJS Enterprise Backend APIs มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
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.
Installing the Pieces
You need three packages: a Redis client (ioredis or the official redis client), the Socket.IO Redis adapter, and Socket.IO itself (already pulled in by @nestjs/platform-socket.io).
The adapter needs two Redis connections: one pubClient for publishing and one subClient for subscribing. A connection in subscribe mode cannot issue normal commands, which is why they must be separate.
// package.json dependencies (excerpt)
{
"dependencies": {
"@nestjs/platform-socket.io": "^11.0.0",
"@nestjs/websockets": "^11.0.0",
"@socket.io/redis-adapter": "^8.3.0",
"socket.io": "^4.7.0",
"ioredis": "^5.4.0"
}
}A Custom IoAdapter
NestJS wraps Socket.IO behind an IoAdapter class. To inject the Redis adapter, you subclass IoAdapter and override createIOServer so that every namespace server is given the Redis adapter via server.adapter(...).
connectToRedis()creates the duplicated pub/sub clients once at bootstrap.createIOServer()attaches the adapter created bycreateAdapter(pubClient, subClient).
This is the central piece of the whole lesson.
// redis-io.adapter.ts
import { IoAdapter } from '@nestjs/platform-socket.io';
import { ServerOptions } from 'socket.io';
import { createAdapter } from '@socket.io/redis-adapter';
import { Redis } from 'ioredis';
export class RedisIoAdapter extends IoAdapter {
private adapterConstructor: ReturnType<typeof createAdapter>;
async connectToRedis(url: string): Promise<void> {
const pubClient = new Redis(url);
const subClient = pubClient.duplicate();
this.adapterConstructor = createAdapter(pubClient, subClient);
}
createIOServer(port: number, options?: ServerOptions): any {
const server = super.createIOServer(port, options);
server.adapter(this.adapterConstructor);
return server;
}
}Wiring It at Bootstrap
The adapter must be connected to Redis before the app starts listening, and registered with app.useWebSocketAdapter(). Do this in main.ts.
- Instantiate
RedisIoAdapterwith the app instance. awaitthe Redis connection so a failure aborts startup cleanly.- Register it, then call
app.listen().
// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { RedisIoAdapter } from './redis-io.adapter';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const redisIoAdapter = new RedisIoAdapter(app);
await redisIoAdapter.connectToRedis(
process.env.REDIS_URL ?? 'redis://localhost:6379',
);
app.useWebSocketAdapter(redisIoAdapter);
await app.listen(3000);
}
bootstrap();The Gateway Stays Unchanged
The beauty of this approach: your @WebSocketGateway code does not change at all. You keep using server.to(room).emit() and the adapter transparently fans it out across instances.
- Join a room with
client.join(room)as usual. - Broadcast with
this.server.to(room).emit(event, payload).
The same gateway now works whether you run 1 or 50 replicas.
// chat.gateway.ts
import {
WebSocketGateway,
WebSocketServer,
SubscribeMessage,
MessageBody,
ConnectedSocket,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
@WebSocketGateway({ cors: { origin: '*' } })
export class ChatGateway {
@WebSocketServer() server: Server;
@SubscribeMessage('joinRoom')
onJoin(@ConnectedSocket() client: Socket, @MessageBody() room: string) {
client.join(room);
return { joined: room };
}
@SubscribeMessage('sendMessage')
onMessage(@MessageBody() data: { room: string; text: string }) {
// Fans out to every instance thanks to the Redis adapter
this.server.to(data.room).emit('message', data.text);
}
}Sticky Sessions vs. Polling
The Redis adapter fixes broadcasting, but it does not fix the HTTP long-polling handshake. With multiple instances, Socket.IO's polling transport sends several HTTP requests during the upgrade; if those requests hit different instances, the handshake fails.
- Option A: Enable sticky sessions on the load balancer so a client always reaches the same instance.
- Option B: Force the WebSocket transport only, skipping polling entirely.
Most production setups enable sticky sessions at the ingress/load balancer layer.
// Force WebSocket-only to sidestep multi-request polling handshakes
@WebSocketGateway({
transports: ['websocket'],
cors: { origin: '*' },
})
export class ChatGateway {}Graceful Reconnection of the Bus
If Redis goes down, the adapter cannot relay events between instances. With ioredis you get automatic reconnection out of the box, but you should log and observe failures so you know broadcasts are degraded.
- Attach listeners to both pub and sub clients.
- A
retryStrategylets you cap backoff and avoid hammering Redis.
// redis-io.adapter.ts (hardened connect)
async connectToRedis(url: string): Promise<void> {
const pubClient = new Redis(url, {
retryStrategy: (times) => Math.min(times * 100, 3000),
});
const subClient = pubClient.duplicate();
for (const client of [pubClient, subClient]) {
client.on('error', (err) => console.error('Redis adapter error', err));
client.on('reconnecting', () => console.warn('Redis adapter reconnecting'));
}
this.adapterConstructor = createAdapter(pubClient, subClient);
}Reasoning About Fan-Out Cost
Every cross-instance emit becomes Redis traffic. Understanding the fan-out helps you size Redis. A pure standalone calculation makes the scaling intuition concrete: if each broadcast must reach N instances, Redis relays roughly one publish that N−1 other instances consume.
The snippet below is a plain TypeScript program estimating published messages per second across a cluster — no framework or Redis needed to run it.
// Estimate Redis pub/sub relay load for a cluster
function relayLoad(
instances: number,
broadcastsPerSecPerInstance: number,
): { publishes: number; deliveries: number } {
const publishes = instances * broadcastsPerSecPerInstance;
// each publish is consumed by the other (instances - 1) nodes
const deliveries = publishes * (instances - 1);
return { publishes, deliveries };
}
const scenarios = [
{ instances: 2, rate: 100 },
{ instances: 10, rate: 100 },
{ instances: 50, rate: 100 },
];
for (const s of scenarios) {
const { publishes, deliveries } = relayLoad(s.instances, s.rate);
console.log(
`${s.instances} instances -> ${publishes} publishes/s, ${deliveries} deliveries/s`,
);
}Targeting Specific Sockets Across Nodes
Beyond rooms, the Redis adapter also supports cluster-wide operations Socket.IO exposes on the server object:
server.fetchSockets()returns socket info from all instances.server.in(socketId).disconnectSockets()can disconnect a socket living on another node.server.socketsJoin(room)/socketsLeave(room)move sockets cluster-wide.
These are async because they round-trip through Redis to reach remote instances.
// admin.gateway.ts
@SubscribeMessage('kick')
async onKick(@MessageBody() socketId: string) {
// Works even if that socket is connected to another instance
const remoteSockets = await this.server.in(socketId).fetchSockets();
for (const s of remoteSockets) {
s.emit('kicked', { reason: 'admin action' });
s.disconnect(true);
}
}Redis Pub/Sub vs. Streams Adapter
Socket.IO offers two Redis-based adapters with different delivery guarantees:
- Pub/Sub adapter (
@socket.io/redis-adapter): fire-and-forget. If an instance is briefly disconnected from Redis, it misses messages during that window. Lowest latency, simplest. - Streams adapter (
@socket.io/redis-streams-adapter): uses Redis Streams so a reconnecting instance can replay missed messages. Slightly more overhead but better for at-least-once needs.
For typical chat/notification fan-out, the Pub/Sub adapter is the default recommendation. Choose Streams when missed broadcasts during a blip are unacceptable.
Quick Check: Why Two Clients?
The Redis adapter requires a separate pubClient and subClient. Why can't you reuse a single Redis connection for both?
Recap
You learned how to scale a NestJS realtime app horizontally with a Redis Pub/Sub adapter:
- In-memory Socket.IO state does not span instances — Redis Pub/Sub relays broadcasts across the cluster.
- Subclass
IoAdapter, connect a pubClient and subClient, and attachcreateAdapter(...)increateIOServer. - Register it in
main.tswithapp.useWebSocketAdapter()beforelisten(); your gateway code stays unchanged. - Enable sticky sessions (or force the WebSocket transport) so the polling handshake survives load balancing.
- Cluster-wide ops like
fetchSockets()anddisconnectSockets()round-trip through Redis. - Choose the Streams adapter instead when you need replay of broadcasts missed during a Redis blip.
เรียนรู้ TypeScript ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 20
- บทเรียน
- 76
คำถามที่พบบ่อย
บทเรียน “การปรับขนาดระบบเรียลไทม์ด้วยอะแดปเตอร์ Redis Pub/Sub” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การปรับขนาดระบบเรียลไทม์ด้วยอะแดปเตอร์ Redis Pub/Sub” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส NestJS Enterprise Backend APIs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส NestJS Enterprise Backend APIs มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การปรับขนาดระบบเรียลไทม์ด้วยอะแดปเตอร์ Redis Pub/Sub”
ซิงโครไนซ์สถานะซ็อกเก็ตข้ามหลายอินสแตนซ์ด้วย Redis IoAdapter เพื่อการปรับขนาดในแนวนอน คุณปฏิบัติ NestJS Enterprise Backend APIs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน NestJS Enterprise Backend APIs หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน NestJS Enterprise Backend APIs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน
บทเรียน “การปรับขนาดระบบเรียลไทม์ด้วยอะแดปเตอร์ Redis Pub/Sub” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน NestJS Enterprise Backend APIs นี้ได้ไหม
ได้ บทเรียน NestJS Enterprise Backend APIs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- เกตเวย์ WebSocket ด้วยอะแดปเตอร์ Socket.IO
- การยืนยันตัวตนและการป้องกันการเชื่อมต่อซ็อกเก็ต
- เหตุการณ์ที่เซิร์ฟเวอร์ส่งสำหรับการพุชทางเดียว
- การปรับขนาดระบบเรียลไทม์ด้วยอะแดปเตอร์ Redis Pub/Sub