WebSockets & Realtime Systems Programming · 강의

수평 확장 전략

성능을 향상하기 위해 여러 서버 인스턴스에 WebSocket 연결을 분산하는 방법을 이해합니다.

레슨 1/411개 단계

수평 확장 전략은(는) CoddyKit의 무료 WebSockets & Realtime Systems Programming 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 WebSockets & Realtime Systems Programming 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. WebSockets & Realtime Systems Programming 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Why Scale WebSockets?

Imagine your awesome app suddenly gets super popular! Thousands, even millions, of users want to connect simultaneously.

A single server can only handle so many active WebSocket connections before it gets overwhelmed. It's like a single lane highway trying to handle rush hour traffic!

To keep your app fast and reliable, we need strategies to handle this high traffic.

Grow Up or Grow Out?

When a single server isn't enough, you have two main options to scale:

  • Vertical Scaling: Upgrade your existing server with more CPU, RAM, or faster storage. Think of it as making your single highway lane wider.
  • Horizontal Scaling: Add more servers to share the load. This is like adding more lanes to your highway, or even building parallel highways!

For WebSockets, horizontal scaling is often preferred. It offers better resilience and flexibility.

The Stateful Challenge

WebSockets are different from traditional HTTP requests. While HTTP is often stateless (each request is independent), WebSockets create a stateful, persistent connection.

This means a client and server maintain an open line of communication. If you just randomly send a client to a different server mid-conversation, it won't know what's going on!

This 'state' makes horizontal scaling a bit trickier than with stateless APIs.

Meet the Load Balancer

To distribute traffic across multiple servers, we use a load balancer. Think of it as a smart traffic cop standing at the entrance of your server farm.

Its job is to efficiently direct incoming client connections to one of your available backend WebSocket servers. This prevents any single server from becoming a bottleneck.

WebSocket Handshake & LB

Remember, a WebSocket connection starts as an HTTP request and then 'upgrades' to a WebSocket. Your load balancer needs to understand this process.

It must be configured to correctly handle the Upgrade header in the HTTP request and then maintain the TCP connection for the WebSocket traffic. Without this, the connection won't establish!

Keeping It 'Sticky': Sticky Sessions

Because WebSockets are stateful, it's often important that a client continues talking to the same backend server it initially connected to.

This is achieved using a technique called sticky sessions (or session affinity). The load balancer remembers which server a client used and directs all subsequent requests from that client to the same server.

Common methods include using the client's IP address or a special cookie.

Sticky Session Example

Let's see a simple Node.js WebSocket server. Imagine you have multiple instances of this server running. With sticky sessions, your client would consistently connect to the same server, getting the same 'Server ID'.

To run this: npm install ws then node server.js

const WebSocket = require('ws');
const http = require('http');

const serverId = `Server-${Math.floor(Math.random() * 100) + 1}`; 

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end(`Hello from HTTP on ${serverId}\n`);
});

const wss = new WebSocket.Server({ server });

wss.on('connection', ws => {
  console.log(`Client connected to ${serverId}`);
  ws.send(`Welcome from ${serverId}!`);

  ws.on('message', message => {
    console.log(`Received on ${serverId}: ${message}`);
    ws.send(`Echo from ${serverId}: ${message}`);
  });

  ws.on('close', () => {
    console.log(`Client disconnected from ${serverId}`);
  });
});

server.listen(8080, () => {
  console.log(`${serverId} listening on port 8080`);
});

Sticky Sessions' Limits

While sticky sessions are great for maintaining a client's connection to a single server, they have drawbacks:

  • Server Failure: If the sticky server crashes, the client loses its connection and might need to re-establish state on a new server.
  • Cross-Server Communication: If a client on Server A needs to send a message to a client on Server B, sticky sessions alone won't solve this.

For more complex scenarios, you'll need more advanced strategies, which we'll cover later!

Load Balancer Methods

Load balancers use different algorithms to decide where to send new connections:

  • Round Robin: Sends connections to servers in a rotating order (Server A, then B, then C, then A...).
  • Least Connections: Sends connections to the server with the fewest active connections.
  • IP Hash: Uses the client's IP address to consistently direct it to the same server (ideal for sticky sessions).

The choice depends on your application's needs.

Quick Check: Scaling WebSockets

You've learned about horizontal scaling and the role of load balancers and sticky sessions. Let's test your understanding!

Recap: Scaling Up!

Great job! In this lesson, you learned why horizontal scaling is vital for high-traffic WebSocket applications.

  • Horizontal scaling adds more servers to handle increased load.
  • Load balancers distribute incoming connections across these servers.
  • They must support the WebSocket upgrade process.
  • Sticky sessions ensure a client consistently connects to the same backend server, maintaining its state.

Next, we'll explore how to configure these load balancers effectively!

무료로 시작

AI 튜터와 함께 WebSockets & Realtime Systems Programming을(를) 배우세요 — 무료

브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.

코스
12
레슨
47

자주 묻는 질문

“수평 확장 전략” 강의는 무료인가요?

네 — “수평 확장 전략” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 WebSockets & Realtime Systems Programming 강의 전체를 잠금 해제할 수 있습니다. WebSockets & Realtime Systems Programming 강의에는 총 4개의 강의가 포함되어 있습니다.

“수평 확장 전략”에서 뭘 배우나요?

성능을 향상하기 위해 여러 서버 인스턴스에 WebSocket 연결을 분산하는 방법을 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 WebSockets & Realtime Systems Programming을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

WebSockets & Realtime Systems Programming을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 WebSockets & Realtime Systems Programming은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“수평 확장 전략” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 WebSockets & Realtime Systems Programming 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 WebSockets & Realtime Systems Programming 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 수평 확장 전략
  2. WebSocket 부하 분산
  3. 분산 상태 관리
  4. Redis를 활용한 Pub/Sub 백플레인
← WebSockets & Realtime Systems Programming(으)로 돌아가기