Skip to content
tezvyn:

WebSockets: A Persistent, Two-Way Connection

Source: developer.mozilla.orgHardHow cards are made

WebSockets: A Persistent, Two-Way Connection

Think of a WebSocket as a dedicated phone line to a server, keeping the connection open for two-way conversation. It's ideal for real-time features like live chat or streaming stock tickers.

Why it exists

Standard HTTP is inefficient for real-time, server-initiated communication. It's a request-response protocol, meaning the client must constantly poll the server to check for new data, which adds latency and overhead. WebSockets were created to provide a single, long-lived, full-duplex connection, allowing the server to push data to the client instantly.

The mental model

Imagine HTTP is like sending postal mail; you send a letter and wait for a reply. Each exchange is a separate transaction. A WebSocket is like opening a phone line; once connected, both parties can talk freely and instantly in either direction until one hangs up. This persistent, two-way channel is the key difference.

How it works

A WebSocket connection begins as a standard HTTP request with a special "Upgrade" header. If the server supports WebSockets, it agrees, and the connection is promoted from HTTP to the WebSocket protocol. From that point on, you interact with it via an event-driven API. You listen for events like open (connection established), message (data received), error, and close. To send data, you call the send() method on the socket object.

When to use it

Use WebSockets for features that require low-latency, real-time updates pushed from the server. Prime examples include live chat apps, collaborative editing tools (like in Google Docs), multiplayer game state synchronization, and live data feeds for stock tickers or sports scores.

When not to use it

Avoid WebSockets for fetching static or infrequently updated data where the client initiates all requests; standard HTTP is more efficient and cache-friendly for this. The most significant footgun is the lack of built-in backpressure. If a server sends messages faster than your client can process them, they will buffer in memory indefinitely, which can lead to your app becoming unresponsive or crashing. You must implement your own throttling logic or use a newer API like WebSocketStream that handles this.

One canonical example

To create a connection, you instantiate the WebSocket object with a ws:// or wss:// URL: const socket = new WebSocket("wss://api.example.com/updates");. You then add event listeners. To send a message upon connection, use the open event: socket.addEventListener("open", () => socket.send("Hello Server!"));. To process incoming data, listen for the message event: socket.addEventListener("message", (event) => { console.log("Data from server:", event.data); });.

Interview question

Which of the following is a critical consideration when designing a system that uses WebSockets for continuous, high-volume data updates?

  • a.The need for the client to frequently re-establish the connection.
  • b.The inability to efficiently transmit diverse data types like JSON or binary.
  • c.The inherent latency introduced by the initial HTTP upgrade process.
  • d.The absence of built-in backpressure, risking client overload if not managed.Correct
Why?

The card explicitly states that a significant 'footgun' of WebSockets is the lack of built-in backpressure, meaning a server can overwhelm a client with data if not properly managed. While the initial HTTP upgrade introduces some latency, it's not the primary concern for continuous, high-volume data streams, which benefit from the long-lived connection.

Just read this? Test yourself on what you have been reading.

Read the original → developer.mozilla.org

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Every open role lists the topics its interview covers, so you can prepare for the real thing rather than guessing.

See open roles