0Pricing
WebSockets & Realtime Systems Programming · レッスン

WebSocketパフォーマンスのベンチマーク

ツールと手法を使って、WebSocketサーバーのパフォーマンス、レイテンシ、スループットを測定します。

「WebSocketパフォーマンスのベンチマーク」はCoddyKit上の無料WebSockets & Realtime Systems Programmingレッスンです。 これはレッスン1/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはWebSockets & Realtime Systems Programming学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 WebSockets & Realtime Systems Programmingコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

Why Benchmark WebSockets?

When building realtime applications with WebSockets, performance is key. Benchmarking helps us understand how our server behaves under different loads.

It's like stress-testing your system before it goes live. You want to know its limits, identify bottlenecks, and ensure it can handle the expected user traffic without breaking a sweat.

  • Capacity Planning: How many users can your server handle?
  • Performance Tuning: Identify slow parts of your code.
  • Regression Testing: Ensure new changes don't degrade performance.

Key WebSocket Metrics

To evaluate performance, we look at specific metrics:

  • Latency: The time it takes for a message to travel from client to server and back (Round-Trip Time). Lower is better.
  • Throughput: The number of messages or bytes processed per second. Higher is better.
  • Concurrency: The maximum number of simultaneous active connections or clients the server can handle. Higher is better.
  • Error Rate: The percentage of failed operations. Lower is better.

Tools for Benchmarking

Several tools can help you benchmark WebSocket applications. These range from simple scripts to dedicated load testing platforms.

  • Custom Scripts: Using libraries like ws (Node.js) to write your own client simulators.
  • Load Testing Tools: Tools like Apache JMeter, k6 (Grafana Labs), or Gatling can simulate thousands of concurrent users and connections.
  • Monitoring Tools: Often integrated with benchmarking to observe server resource usage (CPU, Memory) during tests.

Simple Echo WebSocket Server

Before we can benchmark, we need a WebSocket server to test against. Here's a basic Node.js "echo" server that sends back whatever it receives.

Save this as server.js and run with node server.js (ensure ws is installed: npm install ws).

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', ws => {
  console.log('Client connected');
  ws.on('message', message => {
    // Echo back the received message
    ws.send(message.toString());
  });
  ws.on('close', () => console.log('Client disconnected'));
  ws.on('error', error => console.error('WS Error:', error));
});

console.log('WebSocket server started on port 8080');

Creating a Single Test Client

Now, let's create a client that connects to our echo server, sends a message, and receives it back. This forms the basis for our performance tests.

Save this as client.js and run with node client.js after starting the server.

const WebSocket = require('ws');

const ws = new WebSocket('ws://localhost:8080');

ws.onopen = () => {
  console.log('Connected to server');
  ws.send('Hello WebSocket!');
};

ws.onmessage = event => {
  console.log('Received:', event.data);
  ws.close(); // Close after receiving the echo
};

ws.onerror = error => console.error('WS Error:', error.message);
ws.onclose = () => console.log('Disconnected');

Simulating Multiple Clients

Benchmarking requires simulating many concurrent clients. We can modify our client script to create multiple WebSocket connections.

Each client will connect, send a message, and measure its own performance. Aggregating these results gives us a system-wide view.

  • Use a loop to create many WebSocket instances.
  • Manage connection states and message counts for each client.
  • Collect performance data (e.g., latency) from each client.

Measuring Message Latency

To measure latency, the client sends a message containing a timestamp. When the server echoes it back, the client calculates the time difference.

This example extends our client to measure the round-trip time for a single message.

const WebSocket = require('ws');

const ws = new WebSocket('ws://localhost:8080');
let startTime;

ws.onopen = () => {
  console.log('Connected for latency test');
  startTime = Date.now();
  ws.send(JSON.stringify({ timestamp: startTime, msg: 'Ping' }));
};

ws.onmessage = event => {
  const endTime = Date.now();
  const data = JSON.parse(event.data);
  const latency = endTime - data.timestamp;
  console.log(`Received echo: ${data.msg}. Latency: ${latency} ms`);
  ws.close();
};

ws.onerror = error => console.error('WS Error:', error.message);
ws.onclose = () => console.log('Latency test finished');

Measuring Message Throughput

Throughput is often measured as messages per second. A client can continuously send messages and count how many responses it receives within a set timeframe.

This script sends 1000 messages and reports the total time and messages per second.

const WebSocket = require('ws');

const ws = new WebSocket('ws://localhost:8080');
const totalMessages = 1000;
let messagesReceived = 0;
let testStartTime;

ws.onopen = () => {
  console.log('Connected for throughput test');
  testStartTime = Date.now();
  for (let i = 0; i < totalMessages; i++) {
    ws.send(`Message ${i}`);
  }
};

ws.onmessage = event => {
  messagesReceived++;
  if (messagesReceived === totalMessages) {
    const endTime = Date.now();
    const duration = (endTime - testStartTime) / 1000; // seconds
    const throughput = totalMessages / duration;
    console.log(`Received ${totalMessages} messages in ${duration.toFixed(2)}s.`);
    console.log(`Throughput: ${throughput.toFixed(2)} messages/second.`);
    ws.close();
  }
};

ws.onerror = error => console.error('WS Error:', error.message);
ws.onclose = () => console.log('Throughput test finished');

Interpreting Your Results

Raw numbers from benchmarking are just the start. The real value comes from interpreting them in context:

  • Compare to Baselines: How do your current results compare to previous tests or expected performance?
  • Look for Trends: Does latency increase drastically with more concurrent users? Does throughput plateau?
  • Identify Bottlenecks: High CPU usage on the server, network saturation, or database contention are common culprits.
  • Iterate and Improve: Use the data to make changes, then re-benchmark to see the impact.

Quick Check on Metrics

You're testing a WebSocket server and observe that as more clients connect, the time it takes for a message to be sent and received back increases significantly. Which performance metric is primarily degrading?

Recap: Benchmarking WebSockets

In this lesson, we explored the importance of benchmarking WebSocket applications. We learned about key metrics like latency, throughput, and concurrency.

You saw how to set up a simple echo server and write client-side scripts to measure these metrics. Interpreting these results is crucial for optimizing your realtime systems and ensuring they can handle production loads.

よくある質問

「WebSocketパフォーマンスのベンチマーク」レッスンは無料ですか?

はい。「WebSocketパフォーマンスのベンチマーク」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、WebSockets & Realtime Systems Programmingコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 WebSockets & Realtime Systems Programmingコースには全4レッスンが含まれています。

「WebSocketパフォーマンスのベンチマーク」で何を学びますか?

ツールと手法を使って、WebSocketサーバーのパフォーマンス、レイテンシ、スループットを測定します。 ブラウザで直接実行するハンズオンコードでWebSockets & Realtime Systems Programmingを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

WebSockets & Realtime Systems Programmingを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのWebSockets & Realtime Systems Programmingは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/4です。

「WebSocketパフォーマンスのベンチマーク」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このWebSockets & Realtime Systems Programmingレッスンでコードを書いて実行できますか?

はい。すべてのWebSockets & Realtime Systems Programmingレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. WebSocketパフォーマンスのベンチマーク
  2. リアルタイム問題のプロファイリングとデバッグ
  3. リアルタイム監視とアラート
  4. WebSocketsの負荷テストとキャパシティプランニング
← WebSockets & Realtime Systems Programmingに戻る