0Pricing
WebSockets & Realtime Systems Programming · บทเรียน

การจัดการสถานะแบบกระจาย

สำรวจการใช้ตัวกลางส่งข้อความภายนอก เช่น Redis Pub/Sub และ Kafka เพื่อซิงโครไนซ์สถานะระหว่างเซิร์ฟเวอร์ WebSocket หลายตัว

การจัดการสถานะแบบกระจาย เป็นบทเรียน WebSockets & Realtime Systems Programming ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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 A receives a message it needs to share, it publishes that message to a Redis channel (e.g., 'global_chat').
  • Server B has 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.

คำถามที่พบบ่อย

บทเรียน “การจัดการสถานะแบบกระจาย” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การจัดการสถานะแบบกระจาย” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส WebSockets & Realtime Systems Programming ให้อัปเกรดเป็น CoddyKit PRO คอร์ส WebSockets & Realtime Systems Programming มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การจัดการสถานะแบบกระจาย”

สำรวจการใช้ตัวกลางส่งข้อความภายนอก เช่น Redis Pub/Sub และ Kafka เพื่อซิงโครไนซ์สถานะระหว่างเซิร์ฟเวอร์ WebSocket หลายตัว คุณปฏิบัติ WebSockets & Realtime Systems Programming ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน WebSockets & Realtime Systems Programming หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน WebSockets & Realtime Systems Programming บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “การจัดการสถานะแบบกระจาย” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน WebSockets & Realtime Systems Programming นี้ได้ไหม

ได้ บทเรียน WebSockets & Realtime Systems Programming ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. กลยุทธ์การปรับขนาดแนวนอน
  2. การกระจายภาระงาน WebSockets
  3. การจัดการสถานะแบบกระจาย
  4. แบ็กเพลน Pub/Sub ด้วย Redis
← กลับไปที่ WebSockets & Realtime Systems Programming