분산 상태 관리
여러 WebSocket 서버에서 상태를 동기화하기 위해 외부 메시지 브로커(예: Redis Pub/Sub, Kafka)를 사용하는 방법을 살펴봅니다.
분산 상태 관리은(는) CoddyKit의 무료 WebSockets & Realtime Systems Programming 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 WebSockets & Realtime Systems Programming 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. WebSockets & Realtime Systems Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Scaling Challenges: Shared State
You've learned about scaling WebSocket applications by running multiple server instances behind a load balancer. But what happens when a client connects to Server A, and another client connected to Server B needs to send a message to the first client?
This is the challenge of distributed state management: how do your servers share information and coordinate?
Why Centralize State?
Imagine a chat application. If Client 1 is on Server A and Client 2 is on Server B, and Client 1 sends a message, how does Server A tell Server B to deliver it to Client 2?
Without a way for servers to communicate, messages or updates might only reach clients connected to the same server, breaking the real-time experience.
Introducing Message Brokers
To solve this, we use a message broker. Think of it as a central post office for your servers.
- Servers send messages to the broker.
- Other servers can then receive messages from the broker.
This allows all your WebSocket servers to communicate indirectly, without needing to know about each other's existence.
The Pub/Sub Pattern
Many message brokers use a Publisher-Subscriber (Pub/Sub) pattern. It works like this:
- Publishers send messages to specific channels or topics.
- Subscribers express interest in one or more channels and receive all messages published to them.
This pattern is perfect for broadcasting data across multiple server instances.
Redis Pub/Sub Example
Redis is a popular, open-source, in-memory data store that's often used as a message broker. Its Pub/Sub feature is fast and simple to use.
You can have multiple Node.js WebSocket servers, all connected to a single Redis instance, using it to exchange messages.
Redis Pub/Sub Basics
Let's say you have two WebSocket servers, Server A and Server B, both connected to Redis.
- When
Server Areceives a message it needs to share, it publishes that message to a Redis channel (e.g.,'global_chat'). Server Bhas subscribed to'global_chat', so it instantly receives the message from Redis.
Then, Server B can forward that message to its own connected clients.
Server Publishes to Redis
Here's a simplified Node.js example for a WebSocket server publishing messages to a Redis channel. We'll use the ws library for WebSockets and ioredis for Redis.
Make sure you have Redis running and ws and ioredis installed (`npm i ws ioredis`).
const WebSocket = require('ws');
const Redis = require('ioredis');
const wss = new WebSocket.Server({ port: 8080 });
const publisher = new Redis(); // Connects to localhost:6379
wss.on('connection', ws => {
console.log('Client connected to Server 1');
ws.on('message', message => {
const msg = message.toString();
console.log(`Server 1 received: ${msg}`);
// Publish message to 'chat_messages' channel
publisher.publish('chat_messages', msg);
ws.send(`You said: ${msg}`); // Echo back to sender
});
});
console.log('Server 1 listening on ws://localhost:8080');Server Subscribes & Relays
Now, here's another Node.js WebSocket server (running on a different port) that subscribes to the same Redis channel. When it gets a message from Redis, it broadcasts it to its own connected clients.
You would run this in a separate terminal from server1.js.
const WebSocket = require('ws');
const Redis = require('ioredis');
const wss = new WebSocket.Server({ port: 8081 });
const subscriber = new Redis(); // Connects to localhost:6379
// Subscribe to the 'chat_messages' channel
subscriber.subscribe('chat_messages', (err, count) => {
if (err) console.error('Failed to subscribe:', err.message);
else console.log(`Subscribed to ${count} channel(s)`);
});
// Handle messages received from Redis
subscriber.on('message', (channel, message) => {
console.log(`Server 2 received from Redis [${channel}]: ${message}`);
// Broadcast to all connected clients on Server 2
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(`Global Chat: ${message}`);
}
});
});
wss.on('connection', ws => {
console.log('Client connected to Server 2');
ws.send('Welcome to Server 2!');
});
console.log('Server 2 listening on ws://localhost:8081');Benefits for Scaling
Using a message broker like Redis Pub/Sub offers significant advantages for scaling WebSocket applications:
- Decoupling: Servers don't need direct knowledge of each other. They only interact with the broker.
- Horizontal Scalability: You can easily add more WebSocket servers as traffic grows, and they'll all connect to the same broker.
- Global Broadcasts: Messages can be efficiently broadcast to all clients, regardless of which server they are connected to.
Beyond Broadcasts: Presence
Message brokers aren't just for broadcasting chat messages. They are vital for synchronizing other types of distributed state, like user presence.
For example, when a user logs in, their connected server can publish an 'online' status to a Redis channel. Other servers subscribe to this to keep their lists of online users updated.
Message Broker Check
Consider a scenario where you have multiple WebSocket servers, and a message sent to one server needs to reach a client connected to another server. Which pattern best addresses this?
Recap: Distributed State
We learned that scaling WebSocket applications requires managing distributed state. Message brokers like Redis, using the Pub/Sub pattern, are crucial for allowing multiple WebSocket servers to communicate and synchronize data, ensuring all clients receive relevant updates regardless of which server they're connected to.
This makes your application more resilient and scalable as you add more server instances.
자주 묻는 질문
“분산 상태 관리” 강의는 무료인가요?
네 — “분산 상태 관리” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 WebSockets & Realtime Systems Programming 강의 전체를 잠금 해제할 수 있습니다. WebSockets & Realtime Systems Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
“분산 상태 관리”에서 뭘 배우나요?
여러 WebSocket 서버에서 상태를 동기화하기 위해 외부 메시지 브로커(예: Redis Pub/Sub, Kafka)를 사용하는 방법을 살펴봅니다. 브라우저에서 직접 실행하는 실습 코드로 WebSockets & Realtime Systems Programming을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
WebSockets & Realtime Systems Programming을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 WebSockets & Realtime Systems Programming은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“분산 상태 관리” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 WebSockets & Realtime Systems Programming 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 WebSockets & Realtime Systems Programming 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.