WebSockets are a way to keep a live, two‑way connection between a client (usually a browser) and a server. Instead of opening a new HTTP request for each message, the connection stays open, allowing both sides to push data whenever they need.
One‑Sentence Definition
WebSockets provide a persistent, full‑duplex communication channel over a single TCP connection, enabling real‑time data exchange without the overhead of repeated HTTP requests.
How the Mechanism Works
- Upgrade Handshake – The client sends an HTTP
GETrequest withUpgrade: websocketandConnection: Upgradeheaders. The server replies with101 Switching Protocolsif it supports WebSockets. - Frame Protocol – After the handshake, both sides exchange lightweight frames. Each frame has a small header (opcode, mask, payload length) and the payload data. The protocol is binary‑friendly and can carry text or binary messages.
- Ping/Pong – To keep the connection alive and detect dead peers, either side can send a ping frame; the other must respond with a pong.
- Close – Either side can initiate a graceful close with a close frame, optionally providing a status code and reason.
Trade‑offs to Discuss
| Aspect | Benefit | Cost |
|---|---|---|
| Latency | Near‑instantaneous push from server → lower round‑trip time than polling. | Requires a dedicated socket; idle connections still consume resources. |
| Scalability | Simpler client code, no need for long‑polling or SSE fallbacks. | Server must manage many concurrent connections; load balancers need WebSocket support. |
| Complexity | Straightforward API (WebSocket in browsers, libraries in many languages). | Must handle connection lifecycle, reconnection logic, and back‑pressure. |
| Security | Works over TLS (wss://), inherits HTTP security model. | Same security concerns as any persistent socket (e.g., DoS attacks). |
Concrete Example
Imagine a live‑score dashboard for a sports app. When a user opens the page, the browser creates a WebSocket to wss://scores.example.com. The server pushes each scoring event as soon as it happens:
const ws = new WebSocket('wss://scores.example.com');
ws.onmessage = e => displayScore(JSON.parse(e.data));
The server simply writes a JSON payload for each event, and the client updates the UI instantly. No need for the client to poll every few seconds, saving bandwidth and providing a smoother experience.
Typical Interviewer Questions
- Why use WebSockets instead of HTTP polling? – Emphasize reduced latency, lower bandwidth, and a cleaner programming model for real‑time updates.
- How does the upgrade handshake differ from a normal HTTP request? – Mention the special headers (
Upgrade,Connection) and the101 Switching Protocolsresponse. - What are the main scalability concerns? – Talk about maintaining many open sockets, the need for sticky sessions or a message broker, and how load balancers must be WebSocket‑aware.
- How do you handle reconnection? – Explain exponential back‑off, buffering unsent messages, and optionally using a fallback like long‑polling.
- Can you secure a WebSocket? – Discuss using
wss://, authentication tokens in the initial request, and server‑side validation of each frame.
60‑Second Spoken Answer
"WebSockets give you a persistent, full‑duplex channel over a single TCP connection. The client starts with an HTTP request that includes an
Upgrade: websocketheader, and the server replies with a101 Switching Protocolsresponse. After that, both sides exchange lightweight frames that can carry text or binary data, and they can ping each other to keep the connection alive. The main advantage is real‑time push with very low latency compared to polling, but you have to manage many open connections and ensure your load balancer supports WebSockets. A typical use case is a live‑score board: the server pushes score updates instantly, and the client just updates the UI. In an interview you’d explain the handshake, the frame format, trade‑offs, and maybe mention reconnection strategies and security withwss://."
How to Practice This
- Record yourself – Use Call Assistant to capture a short answer, then replay it to check clarity and timing.
- Mock Q&A – Have a friend ask the five common questions above and answer them out loud, focusing on concise, concrete language.
- Live Demo – Build a tiny WebSocket server (Node.js
wslibrary) and a browser client. Explain the code while it runs to reinforce the mechanism.
Frequently asked questions
What is the difference between WebSockets and Server‑Sent Events?
WebSockets provide full‑duplex communication, allowing both client and server to send messages at any time. Server‑Sent Events are uni‑directional; only the server can push text updates to the client.
Can WebSockets work over HTTPS?
Yes. When you use `wss://` the connection is encrypted with TLS, just like regular HTTPS traffic.
Do browsers support WebSockets natively?
All modern browsers expose a `WebSocket` object in JavaScript, so you can open a connection with `new WebSocket(url)` without any extra libraries.
How do you scale a WebSocket service?
Common approaches include using a message broker (e.g., Redis Pub/Sub) to share state across instances, sticky sessions for load balancers, and horizontal scaling with containers that can handle many concurrent sockets.
#concept#WebSockets#real-time#interview#networking