Back to series
· 15 min read

WebSocket and Persistent Connection Technology


1. Why Do We Need Long-Lived Connections?

Traditional HTTP communication uses a request-response model: the client initiates a request, and the server returns a response. An exchange is usually initiated by the client, and the server cannot proactively send messages to the client through the same request at any time.

This model is suitable for web page loading, API queries, and resource downloads, but it has clear limitations in real-time communication scenarios.

For example:

  • Instant messaging: after a user sends a message, they expect the other party to receive it immediately.
  • Real-time market data: the server needs to continuously push price changes to clients.
  • Online collaboration: multiple users edit a document at the same time and need to synchronize operations.
  • Game communication: the client and server need to exchange state frequently.
  • Real-time monitoring: the server needs to proactively notify clients of alert events.

If traditional HTTP polling is used, the client must continuously initiate requests to check whether there are new messages.

1.1 HTTP Short Polling

Short polling is the simplest way to simulate real-time communication.

The client sends HTTP requests at fixed intervals to ask the server whether there is new data.

sequenceDiagram
    participant C as Client
    participant S as Server

    loop Every interval
        C->>S: GET /messages
        S-->>C: Return new messages or an empty result
    end

For example, send a request every 2 seconds:

async function poll() {
  try {
    const response = await fetch("/api/messages");
    const messages = await response.json();

    if (messages.length > 0) {
      console.log("收到消息", messages);
    }
  } catch (error) {
    console.error("轮询失败", error);
  }
}

setInterval(poll, 2000);

This approach is simple to implement, but it has several problems:

  1. Requests are continuously generated even when there are no new messages.
  2. Requests and responses contain duplicate HTTP headers.
  3. Message arrival time is affected by the polling interval.
  4. As the number of users increases, the server has to handle a large number of invalid requests.

Suppose there are 100,000 clients, each polling once every 2 seconds:

QPS = \frac{100000}{2}=50000

That is, the server needs to handle about 50,000 requests per second, even though most requests contain no actual data.

1.2 HTTP Long Polling

Long polling reduces invalid requests by delaying responses.

After the client initiates a request, if the server temporarily has no data, it keeps the request waiting; as soon as a new message arrives, the server immediately returns a response.

sequenceDiagram
    participant C as Client
    participant S as Server

    C->>S: GET /messages
    Note over S: No new messages yet; keep the request waiting
    S-->>C: Return data when a new message arrives
    C->>S: Initiate the request again
    Note over S: Wait for the next message

On the server side, pseudocode similar to the following can be used:

async function handleLongPolling(req, res) {
  const messages = await waitForMessages({
    userId: req.user.id,
    timeout: 30000
  });

  res.json(messages);
}

Compared with short polling, long polling reduces invalid requests, but the following issues still exist:

  • After each response is completed, the next request must be established again.
  • HTTP request headers and response headers are repeatedly transmitted.
  • A large number of waiting requests consume server resources such as connections and memory.
  • Bidirectional message exchange is still not natural enough.

1.3 The Emergence of WebSocket

WebSocket provides a true bidirectional communication mechanism.

It establishes a connection through an HTTP handshake and then upgrades the communication protocol to WebSocket. After the connection is established, both the client and the server can proactively send messages.

sequenceDiagram
    participant C as Client
    participant S as WebSocket Server

    C->>S: HTTP Upgrade handshake request
    S-->>C: 101 Switching Protocols
    Note over C,S: WebSocket connection established
    C->>S: Client message
    S-->>C: Server message
    S-->>C: Proactive push notification
    C->>S: Client continues sending messages

The core value of WebSocket is:

  • Full-duplex communication.
  • A single handshake, with continuous connection reuse.
  • Both sides can proactively send data.
  • No need to re-establish an HTTP request for every message.
  • Supports text frames and binary frames.

Note that WebSocket is an application-layer communication protocol, not a new TCP replacement protocol. Classic WebSocket runs on top of TCP.

2. Overall Architecture of the WebSocket Protocol

The WebSocket communication process can be divided into two phases:

  1. Use HTTP to complete the connection upgrade.
  2. Use WebSocket frames for ongoing communication.

2.1 Protocol Stack

The protocol stack for traditional WebSocket communication is as follows:

flowchart TD
    A["Application business<br/>chat, notifications, real-time data"] --> B["WebSocket protocol"]
    B --> C["TCP transport layer"]
    C --> D["IP network layer"]
    D --> E["Ethernet or wireless network"]

    style A fill:#F0EAFE,stroke:#B7A1E8,color:#334155
    style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style C fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style D fill:#FFF1D6,stroke:#E8C982,color:#735A20
    style E fill:#F1F5F9,stroke:#CBD5E1,color:#334155

If wss:// is used, WebSocket communication is encrypted through TLS:

flowchart TD
    A["Business application"] --> B["WebSocket"]
    B --> C["TLS encryption layer"]
    C --> D["TCP"]
    D --> E["IP"]

    style A fill:#F0EAFE,stroke:#B7A1E8,color:#334155
    style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style C fill:#FFF1D6,stroke:#E8C982,color:#735A20
    style D fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style E fill:#F1F5F9,stroke:#CBD5E1,color:#334155

Common address formats:

Address Meaning
ws:// Unencrypted WebSocket
wss:// WebSocket over TLS encryption

In production environments, wss:// should generally be preferred, especially when login credentials, user messages, and business data are involved.

2.2 The Relationship Between WebSocket and HTTP

WebSocket is not a connection establishment process that is completely independent of HTTP.

In the classic WebSocket handshake, the client first sends an HTTP Upgrade request.

For example:

GET /ws/chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Origin: https://example.com

The role of each field:

Field Purpose
GET Initiates the handshake using HTTP GET
Upgrade: websocket Requests an upgrade to WebSocket
Connection: Upgrade Declares the intent to upgrade the connection
Sec-WebSocket-Key Random handshake key generated by the client
Sec-WebSocket-Version WebSocket protocol version
Origin Origin of the browser page, used for server-side origin validation

Once the server accepts the handshake, it returns:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

Where:

Sec-WebSocket-Accept is not a simple echo of the client's key; it is computed from the client's Sec-WebSocket-Key.

The calculation rule:

Accept = Base64(SHA1(Key + GUID))

The fixed GUID is:

258EAFA5-E914-47DA-95CA-C5AB0DC85B11

After the client receives a valid 101 Switching Protocols response and verifies Sec-WebSocket-Accept, the WebSocket handshake is complete.

2.3 Handshake Sequence

sequenceDiagram
    participant C as WebSocket Client
    participant S as WebSocket Server

    C->>S: Establish TCP connection
    Note over C,S: If using wss, complete TLS handshake first
    C->>S: HTTP GET Upgrade request
    Note over S: Validate path, Origin, authentication information, and protocol version
    S-->>C: HTTP 101 Switching Protocols
    Note over C,S: Validate Sec-WebSocket-Accept
    Note over C,S: Enter WebSocket frame communication phase
    C->>S: WebSocket data frame
    S-->>C: WebSocket data frame

Note: 101 indicates a successful protocol switch, but it does not mean that subsequent business authentication will necessarily succeed. The business layer still needs to perform identity authentication and permission checks.

3. WebSocket Frame Structure

After the handshake is complete, both parties no longer use normal HTTP request and response formats to transmit messages; instead, they use WebSocket frames.

3.1 Why Are Frames Needed?

TCP is a byte-stream protocol and does not preserve application-layer message boundaries.

For example, the client sends two messages in succession:

Hello
World

The TCP receiver may receive the complete data at once, may receive it in multiple parts, or the data from both messages may appear in the same read result.

Therefore, the application-layer protocol needs to define message boundaries.

WebSocket uses a frame mechanism to organize data.

3.2 WebSocket Frame Structure

The main fields of a WebSocket frame include:

Field Length Description
FIN 1 bit Whether this is the last frame of the message
RSV1-3 3 bit Reserved bits for extension protocols
Opcode 4 bit Frame type
MASK 1 bit Whether masking is used
Payload Length 7 bits or extended length Data length
Masking Key 0 or 4 bytes Masking key
Payload Data Variable length Actual data

Main Opcodes:

Opcode Type Description
0x0 Continuation Continuation frame
0x1 Text Text frame
0x2 Binary Binary frame
0x8 Close Close connection
0x9 Ping Heartbeat probe
0xA Pong Heartbeat response

3.3 Text Frames and Binary Frames

WebSocket supports two common data types.

Text Frame

Used to transmit UTF-8 encoded text, such as JSON:

{
  "type": "chat",
  "userId": "1001",
  "message": "Hello WebSocket"
}

Binary Frame

Used to transmit:

  • Image data.
  • Audio data.
  • Video clips.
  • File contents.
  • Custom binary protocols.

Browser clients can use ArrayBuffer or Blob to handle binary messages.

const ws = new WebSocket("wss://example.com/ws");

ws.binaryType = "arraybuffer";

ws.onmessage = (event) => {
  if (event.data instanceof ArrayBuffer) {
    console.log("收到二进制数据", event.data.byteLength);
  }
};

3.4 Message Fragmentation

A WebSocket message does not necessarily correspond to only one frame.

For larger messages, transmission can be split into multiple frames:

flowchart TD
    A["Complete business message"] --> B["First data frame<br/>FIN=0"]
    B --> C["Intermediate continuation frame<br/>FIN=0"]
    C --> D["Final continuation frame<br/>FIN=1"]
    D --> E["Receiver reassembles the complete message"]

    style A fill:#F0EAFE,stroke:#B7A1E8,color:#334155
    style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style C fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style D fill:#FFF1D6,stroke:#E8C982,color:#735A20
    style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976

Fragmentation serves the following purposes:

  • Avoid constructing excessively large frames at once.
  • Allow the sender to process data in segments.
  • Allow control frames to be interleaved between data fragments when appropriate.

Two concepts need to be distinguished:

  • TCP segmentation: handled by the transport layer.
  • WebSocket message fragmentation: handled by the WebSocket protocol.

They are not the same thing.

3.5 Why do frames sent by the client need to be masked?

According to the WebSocket protocol, data frames sent from the client to the server must set the MASK bit and use a 4-byte Masking Key to mask the payload.

Data frames sent from the server to the client are usually not masked.

Masking calculation:

Payload_i = Original_i \oplus MaskingKey_{i \bmod 4}

Masking is not an encryption algorithm and cannot be used to protect message confidentiality.

It is mainly used to reduce the risk that certain intermediary network devices misinterpret the content of WebSocket data.

Actual communication encryption should use TLS, that is, wss://.

4. WebSocket Communication Model

The most notable feature of WebSocket is full-duplex communication.

4.1 Full-Duplex Communication

Traditional HTTP communication usually has the client initiate a request and the server return a response.

After a WebSocket connection is established, both parties can send messages at any time:

sequenceDiagram
    participant C as Client
    participant S as Server

    Note over C,S: WebSocket connection established
    C->>S: User sends a chat message
    S->>C: Confirmation that the message was sent successfully
    S-->>C: New message notification
    C->>S: User sends read status
    S-->>C: Online status update

This means the server can proactively push data without waiting for the client to initiate a new request.

4.2 Bidirectional Communication Does Not Mean Unrestricted Simultaneous Sending

Although WebSocket is a full-duplex protocol, real systems still have resource and concurrency limits:

  • TCP connection bandwidth is limited.
  • Both browsers and servers have send buffers.
  • The server needs to manage a large number of connections.
  • Network congestion affects data transmission.
  • The business layer may need to control message order and rate.

For example, the browser's send() method does not mean the data has successfully reached the server.

You can use bufferedAmount to check the amount of data that has not yet been fully sent:

const ws = new WebSocket("wss://example.com/ws");

function sendMessage(data) {
  if (ws.readyState !== WebSocket.OPEN) {
    return false;
  }

  const MAX_BUFFER = 1024 * 1024;

  if (ws.bufferedAmount > MAX_BUFFER) {
    console.warn("发送缓冲区过大,暂缓发送");
    return false;
  }

  ws.send(data);
  return true;
}

In real projects, message queues, send rate limiting, and drop policies should be designed according to business requirements.

5. Heartbeat Mechanism: How to Determine Whether a Connection Is Alive?

One of the biggest problems with long-lived connections is that the connection may fail without explicit notification.

For example:

  • User switches networks.
  • Phone enters sleep mode.
  • Router disconnects.
  • NAT mapping expires.
  • Server process exits abnormally.
  • Intermediary proxy closes idle connections.

In some cases, a TCP connection may have no data transmission for a long time, but the application does not know whether the peer is still available.

Therefore, long-lived connections usually require a heartbeat mechanism.

5.1 WebSocket Ping/Pong

The WebSocket protocol defines two types of control frames:

  • Ping: the sender initiates a probe.
  • Pong: the receiver returns a response.

After receiving a Ping, the receiver should send the corresponding Pong response as soon as possible.

sequenceDiagram
    participant C as Client
    participant S as Server

    Note over C,S: Connection idle
    S->>C: Ping
    C-->>S: Pong
    Note over C,S: The connection can still communicate
    S->>C: Ping
    C-->>S: Pong

Note that the browser-native WebSocket API does not provide a method to send Ping control frames directly, nor does it expose Ping/Pong control frames to JavaScript.

Protocol-level Ping/Pong is usually handled by the underlying WebSocket implementation or the server side.

5.2 Application-layer heartbeats

If browser JavaScript needs to actively detect the connection, it can use application-layer heartbeat messages.

For example:

{
  "type": "heartbeat",
  "timestamp": 1796486400000
}

The server returns:

{
  "type": "heartbeat_ack",
  "timestamp": 1796486400000
}

Browser implementation example:

const HEARTBEAT_INTERVAL = 25000;
const HEARTBEAT_TIMEOUT = 10000;

let heartbeatTimer = null;
let timeoutTimer = null;

function startHeartbeat(ws) {
  stopHeartbeat();

  heartbeatTimer = setInterval(() => {
    if (ws.readyState !== WebSocket.OPEN) {
      return;
    }

    ws.send(JSON.stringify({
      type: "heartbeat",
      timestamp: Date.now()
    }));

    clearTimeout(timeoutTimer);

    timeoutTimer = setTimeout(() => {
      console.warn("心跳超时,连接可能异常");
      ws.close();
    }, HEARTBEAT_TIMEOUT);
  }, HEARTBEAT_INTERVAL);
}

function stopHeartbeat() {
  clearInterval(heartbeatTimer);
  clearTimeout(timeoutTimer);

  heartbeatTimer = null;
  timeoutTimer = null;
}

Receiving heartbeat responses:

ws.addEventListener("message", (event) => {
  const message = JSON.parse(event.data);

  if (message.type === "heartbeat_ack") {
    clearTimeout(timeoutTimer);
  }
});

In production, further handling is needed for:

  • JSON parsing errors.
  • Correlating heartbeat requests with responses.
  • Reconnecting after a heartbeat timeout.
  • Cleaning up timers when the page closes.
  • Restoring the connection after network recovery.
  • Coordinating server-side and client-side heartbeats.

5.3 How should the heartbeat interval be set?

There is no fixed standard for the heartbeat interval; it needs to be determined based on the network environment and infrastructure configuration.

For example:

Scenario Heartbeat interval to consider
General web applications 20–60 seconds
Real-time collaboration 10–30 seconds
Mobile environments with poor networks Dynamically adjusted based on network and battery
High-frequency trading or real-time control Designed separately based on business SLAs

If heartbeats are too frequent:

  • Increases network traffic.
  • Increases server processing overhead.
  • Increases power consumption on mobile devices.

If heartbeats are too sparse:

  • Failures are detected late.
  • May exceed the idle connection timeout of proxies or NAT.

The actual interval should be shorter than the shortest idle timeout in the link, with some margin reserved.

6. Reconnection: How to Restore a Persistent Connection?

A persistent connection does not mean the connection will never drop.

A reliable WebSocket system must be able to reconnect after disconnection.

6.1 Why do connections drop?

Common causes:

Cause Typical symptom
Network switching Switching from Wi-Fi to mobile data
Network interruption The TCP connection can no longer transmit data
Server restart The server actively closes the connection
Proxy timeout Idle connections are closed by intermediary devices
Load balancer migration Backend nodes change
Browser sleep The page is suspended or throttled in the background
Server overload The server actively rejects or closes the connection

After a WebSocket disconnects, the original connection cannot be directly resumed as the same connection.

The client needs to establish a new connection.

6.2 Exponential backoff reconnection

If a server fails, many clients reconnecting at the same time can create a reconnection storm.

For example, after the server recovers, 100,000 clients immediately initiate connections:

flowchart TD
    A["Server recovers"] --> B["Many clients reconnect at the same time"]
    B --> C["Connection requests spike instantly"]
    C --> D["Server resources are exhausted"]
    D --> E["Connections fail again"]
    E --> B

    style A fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style B fill:#FFF1D6,stroke:#E8C982,color:#735A20
    style C fill:#FCE8E6,stroke:#E6A6A1,color:#7B3E3A
    style D fill:#FCE8E6,stroke:#E6A6A1,color:#7B3E3A
    style E fill:#F0EAFE,stroke:#B7A1E8,color:#334155

One solution is exponential backoff.

After each failed reconnection, the wait time gradually increases:

Delay_n = \min(Delay_{max}, Delay_0 \times 2^n)

Then add random jitter to avoid many clients reconnecting at the same time:

ActualDelay = Random(0, Delay_n)

For example:

Reconnection attempt Maximum wait time
1st attempt 1 second
2nd attempt 2 seconds
3rd attempt 4 seconds
4th attempt 8 seconds
5th attempt 16 seconds
Subsequent At most 30 seconds

6.3 JavaScript Auto-Reconnect Example

class WebSocketClient {
  constructor(url) {
    this.url = url;
    this.ws = null;
    this.retryCount = 0;
    this.maxDelay = 30000;
    this.closedByUser = false;
    this.retryTimer = null;
  }

  connect() {
    if (this.closedByUser) {
      return;
    }

    this.ws = new WebSocket(this.url);

    this.ws.onopen = () => {
      console.log("WebSocket连接成功");
      this.retryCount = 0;
    };

    this.ws.onmessage = (event) => {
      this.handleMessage(event.data);
    };

    this.ws.onerror = (error) => {
      console.error("WebSocket异常", error);
    };

    this.ws.onclose = () => {
      console.warn("WebSocket连接关闭");

      if (!this.closedByUser) {
        this.reconnect();
      }
    };
  }

  reconnect() {
    if (this.retryTimer !== null) {
      return;
    }

    const baseDelay = 1000;
    const maxDelay = Math.min(
      this.maxDelay,
      baseDelay * 2 ** this.retryCount
    );

    const delay = Math.random() * maxDelay;

    this.retryCount++;

    this.retryTimer = setTimeout(() => {
      this.retryTimer = null;
      this.connect();
    }, delay);
  }

  send(data) {
    if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
      return false;
    }

    this.ws.send(data);
    return true;
  }

  handleMessage(data) {
    console.log("收到消息", data);
  }

  close() {
    this.closedByUser = true;

    clearTimeout(this.retryTimer);
    this.retryTimer = null;

    if (this.ws) {
      this.ws.close(1000, "Client closed");
    }
  }
}

Usage:

const client = new WebSocketClient(
  "wss://example.com/ws"
);

client.connect();

This example demonstrates basic reconnection logic. A production environment also needs to add:

  • Maximum reconnect attempts or maximum reconnect duration.
  • Page lifecycle management.
  • Authentication token refresh.
  • Connection state notifications.
  • Subscription recovery after reconnection.
  • Caching and resending unsent messages.
  • Classified handling of close codes.
  • Preventing old connection events from affecting the new connection.

6.4 Why Does Business State Need to Be Restored After Reconnection?

Re-establishing a WebSocket connection only restores the transport channel; it does not automatically restore the previous business state.

For example:

During a user's disconnection, 20 chat messages arrive, and after reconnection the server does not automatically know which messages the client is missing.

Therefore, the business system needs to design a message recovery mechanism.

A common approach is to use message sequence numbers:

{
  "type": "message",
  "conversationId": "room-1001",
  "sequence": 1024,
  "content": "Hello"
}

The client records the sequence number of the last successfully processed message:

{
  "type": "resume",
  "conversationId": "room-1001",
  "lastSequence": 1020
}

The server resends missing messages based on the sequence number:

sequenceDiagram
    participant C as Client
    participant S as Server
    participant D as Message Store

    C->>S: Re-establish WebSocket connection
    C->>S: Request resume with lastSequence=1020
    S->>D: Query messages with sequence numbers greater than 1020
    D-->>S: Return missing messages
    S-->>C: Resend 1021 to 1024
    C->>C: Deduplicate and update local sequence number
    C->>S: Confirm processed up to 1024
    Note over C,S: Resume normal real-time communication

Such a mechanism can compensate for messages after a disconnection.

However, the following must be clear:

  • WebSocket itself does not provide message persistence.
  • WebSocket itself does not guarantee that business messages are processed exactly once.
  • Reliable TCP transport is not the same as successful business processing.
  • The application layer needs to design ACK, sequence number, deduplication, and compensation logic.

7. Connection Closure: How to Release Resources Correctly?

WebSocket defines a closing handshake mechanism.

Either the client or the server can actively initiate closure, and both parties negotiate to end the connection through Close control frames.

7.1 Normal Closing Process

sequenceDiagram
    participant C as Client
    participant S as Server

    C->>S: Close frame
    S-->>C: Close frame
    Note over C,S: Both sides complete the closing handshake
    Note over C,S: Underlying TCP connection is closed

The server can also initiate it:

sequenceDiagram
    participant C as Client
    participant S as Server

    S->>C: Close frame
    C-->>S: Close frame
    Note over C,S: WebSocket closed

Browser API:

ws.close(1000, "Normal closure");

7.2 Common Close Status Codes

Status Code Meaning
1000 Normal closure
1001 Endpoint leaving, e.g. page navigation
1002 Protocol error
1003 Unsupported data type received
1006 Local representation of abnormal closure, must not be sent on the wire
1007 Invalid message data format
1008 Policy violation
1009 Message too large
1011 Internal server error
1012 Service restart
1013 Service temporarily unavailable

Browser JavaScript can obtain close information through CloseEvent:

ws.addEventListener("close", (event) => {
  console.log({
    code: event.code,
    reason: event.reason,
    wasClean: event.wasClean
  });
});

Among them:

  • code: Close status code.
  • reason: Close reason.
  • wasClean: Whether the normal close handshake was completed.

1006 is a reserved status used to indicate an abnormal closure and cannot be actively sent via close().

8. How does a WebSocket server handle a large number of connections?

WebSocket maintains long-lived connections at the application layer, so the server needs to manage connection state over the long term.

When the number of connections reaches tens of thousands, hundreds of thousands, or even more, the server architecture becomes the core issue.

8.1 Why do long-lived connections consume resources?

Each connection may occupy:

  • File descriptors.
  • Socket kernel buffers.
  • User-space connection objects.
  • TLS session-related resources.
  • Read/write buffers.
  • Heartbeat timers or scheduled tasks.
  • User and session state.
  • Subscription relationships and message queues.

Simple estimate:

Assume each connection occupies an average of 20 KB of memory at the application layer:

Memory = Connections \times MemoryPerConnection

1 million connections:

1000000 \times 20KB \approx 19.1GB

This does not yet include operating system Socket buffers, TLS, business caches, and other runtime overhead.

Therefore, you cannot simply assume that the number of WebSocket connections is determined only by CPU.

8.2 I/O multiplexing

The traditional blocking network model may allocate one thread per connection.

When the number of connections is large, the number of threads brings high memory and scheduling costs.

Modern network servers usually use I/O multiplexing.

Common mechanisms on Linux:

  • select
  • poll
  • epoll

Other operating systems have corresponding mechanisms, for example:

  • macOS: kqueue
  • Windows: IOCP

Taking Linux epoll as an example:

flowchart TD
    A["Many client connections"] --> B["Socket file descriptors"]
    B --> C["epoll registration and monitoring"]
    C --> D["Kernel detects I/O events"]
    D --> E["Return ready connections"]
    E --> F["Event loop handles reads and writes"]
    F --> G["Update connection state"]
    G --> C

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#F1F5F9,stroke:#CBD5E1,color:#334155
    style C fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style D fill:#FFF1D6,stroke:#E8C982,color:#735A20
    style E fill:#F0EAFE,stroke:#B7A1E8,color:#334155
    style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style G fill:#DCEFE5,stroke:#8EBFA5,color:#24563F

I/O multiplexing allows a small number of threads to manage a large number of connections, avoiding the creation of an independent thread for each connection.

8.3 Reactor model

Many high-performance network frameworks use the Reactor model.

It handles connections, reads/writes, and business tasks in an event-driven manner.

flowchart TD
    A["Client connection"] --> B["Acceptor"]
    B --> C["Register connection"]
    C --> D["Event Loop"]
    D --> E["Read data"]
    E --> F["Protocol parsing"]
    F --> G["Business processing"]
    G --> H["Write to response queue"]
    H --> I["Send data"]
    I --> D

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style C fill:#F1F5F9,stroke:#CBD5E1,color:#334155
    style D fill:#F0EAFE,stroke:#B7A1E8,color:#334155
    style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style G fill:#FFF1D6,stroke:#E8C982,color:#735A20
    style H fill:#F1F5F9,stroke:#CBD5E1,color:#334155
    style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976

Common network frameworks:

Language Framework
Java Netty, Spring WebSocket
Go Gorilla WebSocket, nhooyr/websocket, standard library ecosystem implementations
Node.js ws, Socket.IO
Python websockets, FastAPI WebSocket
Rust tokio-tungstenite, axum

Note that Socket.IO is not equivalent to native WebSocket. It provides additional events, reconnection, rooms, and fallback mechanisms on top of WebSocket, and the client and server must use a compatible Socket.IO protocol.

8.4 Connection Management and Resource Limits

Production environments should monitor:

Metric Description
Current connections Currently online WebSocket connections
New connection rate Number of new connections per unit time
Disconnection rate Number disconnected per unit time
Message throughput Number of messages sent and received per second
Message latency Time from message sending to processing
Send queue length Amount of data not yet sent
Heartbeat timeout rate Proportion of connections with failed heartbeats
Memory usage Memory used by connection objects and buffers
File descriptor usage Socket resource usage
Connection error rate Proportion of handshake failures and abnormal disconnections

The following also need to be configured:

  • Maximum number of connections.
  • Maximum message size per connection.
  • Maximum number of connections per user.
  • Message rate limit per second.
  • Maximum send buffer size.
  • Idle connection timeout.
  • Slow client handling strategy.

9. WebSocket Cluster Architecture

A single server can handle a certain number of long-lived connections, but large systems usually require multi-instance deployment.

9.1 Typical Architecture

flowchart TD
    A["Web browser or mobile client"] --> B["Load balancer"]
    B --> C["WebSocket Node A"]
    B --> D["WebSocket Node B"]
    B --> E["WebSocket Node C"]
    C --> F["Message bus"]
    D --> F
    E --> F
    F --> G["Business service"]
    F --> H["Redis or message storage"]
    G --> H

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style C fill:#F0EAFE,stroke:#B7A1E8,color:#334155
    style D fill:#F0EAFE,stroke:#B7A1E8,color:#334155
    style E fill:#F0EAFE,stroke:#B7A1E8,color:#334155
    style F fill:#FFF1D6,stroke:#E8C982,color:#735A20
    style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style H fill:#F1F5F9,stroke:#CBD5E1,color:#334155

Responsibilities of each component:

  • Load balancer: distributes connections across different WebSocket nodes.
  • WebSocket node: maintains long-lived client connections.
  • Message bus: propagates business messages between different nodes.
  • Business service: handles business such as chat, notifications, and collaboration.
  • Redis or message storage: stores online status, message records, and subscription information.

9.2 Why Is a Message Bus Needed?

Suppose:

  • User A is connected to Node 1.
  • User B is connected to Node 2.

User A sends a message to User B.

If Node 1 only knows about connections on itself, it cannot directly find User B on Node 2.

Therefore, cross-node message routing is required.

sequenceDiagram
    participant A as User A
    participant N1 as WebSocket Node 1
    participant M as Message Bus
    participant N2 as WebSocket Node 2
    participant B as User B

    A->>N1: Send message to User B
    N1->>M: Publish message event for User B
    M-->>N2: Push message event
    N2->>B: Send WebSocket message
    B->>N2: Return business acknowledgment
    N2->>M: Publish processing result
    M-->>N1: Return acknowledgment event

Common message middleware:

  • Redis Pub/Sub.
  • Redis Streams.
  • RabbitMQ.
  • Kafka.
  • NATS.

When choosing, consider message reliability, throughput, ordering guarantees, consumption model, and operational cost.

For example, Redis Pub/Sub is suitable for simple real-time broadcasting, but subscribers do not automatically receive historical messages when they are offline. If reliable redelivery is required, consider a persistent message mechanism.

9.3 Load Balancing and Connection Stickiness

Once a WebSocket connection is established, it remains bound to a backend node for a long time.

For example:

Client A -> Load balancer -> WebSocket Node 1

Subsequent WebSocket messages typically continue to use the already established connection; the backend server is not reselected for every message.

However, when the connection is broken and reconnects, the client may be assigned to a different node.

Therefore:

  • Do not rely on a particular node to store unique business state.
  • User online status must be shared across nodes.
  • Subscription relationships must be recoverable.
  • After reconnection, re-authentication and re-subscription are required.
  • State recovery after node failure must be considered.

The load balancer must support WebSocket Upgrade and properly configure connection timeouts and idle timeouts.

10. Differences Between WebSocket, SSE, and HTTP Polling

WebSocket is not the only choice for all real-time push scenarios.

Common approaches include:

  • Short polling.
  • Long polling.
  • SSE.
  • WebSocket.

10.1 What Is SSE?

SSE, short for Server-Sent Events, is an HTTP-based one-way server-to-client push mechanism.

The client uses EventSource to establish a connection, and the server continuously sends events via text/event-stream.

For example:

HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache
Connection: keep-alive

The server can continuously send:

event: message
id: 1001
data: {"content":"Hello"}

event: message
id: 1002
data: {"content":"World"}

Browser client:

const source = new EventSource("/api/events");

source.onmessage = (event) => {
  console.log("收到事件", event.data);
};

source.onerror = () => {
  console.error("SSE连接异常");
};