WebSocket: simple about the complex. Part 2 — practical application and nuances

Julia here again, a systems analyst at EvApps, and we continue exploring WebSocket technology. In the first part, we learned the basics of WebSocket, and now let's look under the hood of a real website, for example, a crypto exchange. Let's try to understand how this sophisticated mechanism works: what happens when you see instantly changing quotes and charts, and what goes on “behind the scenes”.

It's Yulia again, a systems analyst from EvApps, and we continue to explore WebSocket technology. In the first part (WebSocket for beginner systems analysts: simplifying the complex. Part 1), we got acquainted with the basics of WebSocket, and now let's take a look under the hood of a real website, like a cryptocurrency exchange. Let's try to understand how this complex mechanism works: what happens when you see the instantly changing quotes and charts, and what's going on "behind the scenes."

This article is for you if you:

  • Are a beginner systems analyst and want to understand how complex web applications are structured.

  • Are interested in how frontend and backend work.

  • Are simply curious and want to learn how WebSocket technology works.

What questions will we address?

  • How does data exchange through WebSocket happen between the browser and the cryptocurrency exchange server?

  • How to ensure that the connection is secure and your data won't fall into the wrong hands?

  • How does WebSocket affect server performance?

  • Will the website crash if too many users try to trade simultaneously?

Ready to dive into the world of WebSocket technology? Let's go!

WebSocket in real-time: a cryptocurrency exchange example

Let's consider a cryptocurrency trading website, where speed and accuracy of data transmission are crucial. For example, when you see the Bitcoin exchange rate update in real-time or get a trade notification, all of this works thanks to WebSocket.

Frontend and Backend: How do they interact?

Frontend is what the user sees: the website interface, charts, buttons. When you visit the website, the frontend sends a request to establish a WebSocket connection with the backend.

Backend is the "brain" of the system. It processes requests, works with the database, and sends data back to the frontend. In the case of the website, the backend is responsible for transmitting data on currency rates, user balances, etc.

How does this work in practice?

  1. The user opens the platform website.

  2. The frontend establishes a WebSocket connection with the backend.

  3. The backend starts sending real-time data: exchange updates, trade notifications, etc.

  4. The frontend displays this data on the user's screen.

How to ensure WebSocket is being used?

  • You can use the browser's developer tools (DevTools) to see WebSocket connections.

Let's look at an example of one such website

  • Go to the page https://www.bybit.com/en

  • Open Developer Tools (F12)

  • Go to the Network tab

  • Select the WS (WebSocket) filter

  • Select a specific connection to view the headers

The image demonstrates a message exchange scheme between client and server via WebSocket

If WebSocket is being used, you'll see active connections with the WebSocket type, request headers, data frames being sent and received.

How does the backend work with WebSocket? Or what happens under the hood?

Let's take a closer look.

1. Establishing the connection

(*From the first part, we remember that a WebSocket connection begins with a regular HTTP request.)

When a user opens the site, the frontend sends an HTTP request with the “Upgrade: websocket” header.
The backend checks this request and, if everything is fine, responds with the status “101 Switching Protocols”. The connection switches to the WebSocket protocol, and HTTP is no longer used.


Screenshot of WebSocket connection setup code in JavaScript

*Can WebSocket work without HTTP?

- No, without the initial HTTP request the WebSocket cannot be established. This is a required step to start WebSocket communication.

What does the backend do at this stage?

  • Checks the request headers (for example, “Sec-WebSocket-Key”).

  • Generates the response key (“Sec-WebSocket-Accept”).

  • Establishes the connection and allocates resources to maintain it.

The Headers Tab
This is where you can find general information as well as request and response headers.
So,
General contains:

- Request URL: The WebSocket server URL that the client connects to. wss:// indicates an encrypted connection (we’ll discuss secure connections in a bit more detail below).

- Request Method: The HTTP request method used for the handshake.

- Status Code: 101 Switching Protocols - confirms that the protocol was successfully switched from HTTP to WebSocket.


Infographic of the differences between WebSocket and HTTP

Request Headers:

These are the headers the client sends to the server.

  • Connection: Upgrade - indicates the client wants to upgrade the connection to another protocol.

  • Upgrade: websocket - tells the server that the client wants to switch to WebSocket.

  • Sec-WebSocket-Key - a random key used for the handshake.

  • Sec-WebSocket-Version - the WebSocket protocol version (usually 13).


Fragment of a web application interface with a WebSocket connection status indicator

Response Headers:

These are the headers the server sends back to the client.

  • Connection: upgrade - confirms that the server agrees to switch protocols.

  • Upgrade: websocket - confirms that the server has switched to WebSocket protocol.

  • Date - the date and time the server sent the response.

  • Sec-WebSocket-Accept - a key generated by the server to verify the handshake response.


Sequence diagram of events during WebSocket session establishment and teardown

(* We’re looking at standard headers)

The set of headers during a WebSocket connection may differ depending on implementation and the requirements of the client and server.

2. Data Exchange

After the connection is established, a two-way exchange of data starts between the client and the server.

The Messages Tab
Here you can view the data transferred via WebSocket:

  • Incoming ⬇️ and outgoing ⬆️ messages.

  • The time each message was sent or received

  • The contents of the messages (text or binary data)


Browser debug window with the Network tab showing WebSocket traffic

How does the backend process messages?

The backend receives messages from the client (for example, requests for data), processes them, accesses the database, and sends a response back to the client.

3. Keeping the connection alive (Ping/Pong)

To ensure that the client (frontend) and the server (backend) know the connection is active, they regularly exchange Ping and Pong messages.

--- Get reliable web hosting services with high performance and excellent customer support from Godlike Host. [Learn more](https://pollinations.ai/redirect/1826593)

The client sends a message:
“ping”


Real-life chat example featuring fast message exchange via WebSocket

The server responds:
{
“pong”: 1742678942258
}.


Table showing common errors and their solutions when working with WebSocket

4. Closing the connection

If the server does not receive a Pong from the client within a certain period, it considers the connection broken and closes it. This frees up resources and avoids hanging connections.


What does this look like in code?


Collage of client icons that support WebSocket

For example, on a crypto exchange, the ping/pong frame is configured so that the client sends “ping” and the server responds with “pong”.
Don’t be alarmed if you encounter another implementation where the server sends “ping”—that’s also possible and doesn’t contradict standard recommendations.

“ • RFC 6455 recommends, but does not require, that ping is initiated by one side and pong is sent in response by the other side.

• The RFC says either side can send a ping frame at any time.

• The recipient of a ping frame must send a pong frame back with exactly the same payload as was in the ping. This is important for correct operation.”

For example, on our project (we’re working on a platform for a call center), the ping/pong frame is implemented so that the ping is sent from the server and pong from the client.
Why did we do this?
Stability and availability of the application are critical for us.
Our server maintains many client connections.

If the server thinks a client has disconnected (i.e., does not receive a pong from the client after sending a ping), it means the operator cannot accept calls and chats, which affects customer service. The server must quickly detect problems with client connections. That’s why this implementation was chosen.
Keep these points in mind when developing systems using WebSocket.

Security: Don’t forget about WSS

The WebSocket connection must be secure, especially when it comes to financial data. A systems analyst cannot ignore security. Here’s how it is achieved:

  • WSS (WebSocket Secure) — this is the encrypted version of the WebSocket protocol, similar to HTTPS. All data is transmitted over a secure wss:// connection using TLS/SSL encryption. This prevents data interception by attackers.

  • Authentication and authorization: before establishing a WebSocket connection, the user must be authenticated. For example, on our site, this is done via API keys or tokens.
    The backend checks these credentials and decides whether a connection can be established.

  • Request limiting: the backend checks if too many requests are coming from a single client to prevent attacks such as DDoS. For example, if a client sends too many messages in a short period, the server may temporarily block it.

How to make sure WSS is used?

Open the developer tools (DevTools) in your browser to check WebSocket connections. This information can be seen in the Network tab.

  • ws://... – a regular, non-secure WebSocket.

  • wss://... – a secure (encrypted) WebSocket (WebSocket Secure).

Don’t forget about security)

How does WebSocket affect performance?

WebSocket allows for fast data transmission, but this creates a load on the server. For example, if thousands of users are connected to a website simultaneously, the server must handle a huge number of messages. How is this managed?

  • Load balancers (e.g., Nginx or AWS Elastic Load Balancer) that distribute requests among multiple servers.

  • Clustering: multiple servers work together, handling requests in parallel.

  • Message queues (e.g., RabbitMQ or Kafka) that help manage data streams.

Advantages and Disadvantages of WebSocket

Advantages:

  • Reduced latency. WebSocket establishes a persistent two-way connection, allowing for instant data exchange without needing to send repeated requests.

  • Reduced overhead. In HTTP, each request contains headers, increasing the amount of data transmitted. WebSocket transmits data in a "light" format after the connection is established, saving bandwidth.

  • Efficient resource usage.
    The server does not waste resources processing thousands of repeated HTTP requests.
    The client does not load the processor due to continuous polling of the server.

  • Scalability. WebSocket simplifies the implementation of real-time features. It is suitable for high-load systems (social networks), where data processing speed is important.

  • Simplified architecture. There is no need to use workarounds (e.g., AJAX requests). The code becomes cleaner and maintenance is easier.

Disadvantages:

  • Resource load of the connection.
    Each WebSocket connection requires a persistent open channel between the client and server. In comparison, HTTP requests are processed and closed, freeing up resources.

  • Scalability complexity.
    WebSocket is harder to scale horizontally since the connection state is "tied" to a specific server.

  • Redundancy for simple tasks.
    If the application does not require instant updates, WebSocket becomes "overkill."
    For example, a static portfolio site or a blog with comments only needs HTTP + AJAX.

Always remember that WebSockets should only be used where constant instant two-way communication is required.


Visualization of real-time bidirectional data exchange between multiple users

Conclusion:

So, we took a look under the hood of a cryptocurrency exchange website and explored how the frontend and backend interact via WebSocket. We discussed security and scalability issues.
I hope this breakdown helped you better understand how everything works! If you have any questions, feel free to ask—I'd be happy to answer them! 😊

In the next part, we will discuss how to test WebSocket connections. We'll look at various approaches and tools that can help ensure WebSocket applications work correctly.

Comments