JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsjavascript
PrevNext

Learn the concept

Event Loop & Runtime

javascript
senior
runtime

How do WebSockets work and when would you use them over HTTP?

websockets
real-time
bidirectional
tcp
http
sse
socket-io
Quick Answer

WebSockets provide full-duplex, persistent communication between client and server over a single TCP connection. They start as an HTTP upgrade handshake, then switch to a lightweight binary-framed protocol. Use them for real-time features like chat, live notifications, collaborative editing, and live order tracking.

Detailed Explanation

The WebSocket Handshake:

A WebSocket connection begins as a standard HTTP request with an Upgrade: websocket header. The server responds with 101 Switching Protocols, and from that point forward, the same TCP connection carries WebSocket frames in both directions.

Client → Server:
GET /chat HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13

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

Persistent Full-Duplex Communication:

After the handshake, both client and server can send messages at any time without waiting for a request/response cycle. This eliminates the overhead of HTTP headers on every message (2-10 bytes per WebSocket frame vs 200-800 bytes per HTTP request) and removes the latency of establishing new connections.

WebSocket Lifecycle — readyState:

  • 0 CONNECTING — Connection is being established
  • 1 OPEN — Connection is active, data can flow
  • 2 CLOSING — Close handshake in progress
  • 3 CLOSED — Connection is terminated

When to Use WebSockets vs Alternatives:

| Feature | HTTP Polling | Server-Sent Events | WebSockets | |---------|-------------|-------------------|------------| | Direction | Client → Server | Server → Client only | Bidirectional | | Connection | New per request | Persistent (one-way) | Persistent (two-way) | | Protocol | HTTP | HTTP | WS (binary frames) | | Overhead per message | High (headers) | Medium | Low (2-10 bytes) | | Browser support | Universal | Universal (except IE) | Universal | | Auto-reconnect | N/A | Built-in | Manual | | Best for | Low-frequency updates | Notifications, feeds | Chat, collaboration, gaming |

Server-Sent Events (SSE) are simpler than WebSockets for server-to-client streaming. They use standard HTTP, support automatic reconnection, and work through most proxies and CDNs. Choose SSE for one-directional real-time data (notifications, live feeds) and WebSockets when the client also needs to send real-time data.

Scaling Challenges:

  • Load balancing — WebSocket connections are stateful. You need sticky sessions or a pub/sub layer (Redis) to route messages to the right server.
  • Connection limits — Each open WebSocket holds a TCP connection. Servers need to handle thousands of concurrent connections (use libraries like uWebSockets or Socket.IO).
  • Heartbeats — Connections can silently die (network changes, NAT timeouts). Implement ping/pong frames to detect dead connections.
  • Security — Use wss:// (WebSocket Secure over TLS). Validate the Origin header to prevent cross-site WebSocket hijacking.

Code Examples

WebSocket client basicsJavaScript
const ws = new WebSocket('wss://api.example.com/live');

// Connection opened
ws.addEventListener('open', () => {
  console.log('Connected');
  ws.send(JSON.stringify({ type: 'subscribe', channel: 'orders' }));
});

// Receive messages
ws.addEventListener('message', (event) => {
  const data = JSON.parse(event.data);
  console.log('Received:', data);
});

// Connection closed
ws.addEventListener('close', (event) => {
  console.log(`Disconnected: code=${event.code} reason=${event.reason}`);
});

// Handle errors
ws.addEventListener('error', (error) => {
  console.error('WebSocket error:', error);
});

// Send data (check readyState first)
function sendMessage(message) {
  if (ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify(message));
  }
}

// Close connection gracefully
ws.close(1000, 'User navigated away');

Real-World Applications

Use Cases

Live Delivery Tracking

Food delivery apps use WebSockets to push real-time driver location updates to the customer's map view.

Collaborative Editing

Tools like Figma and Google Docs use WebSockets to synchronize edits between multiple users in real-time.

Mini Projects

Real-Time Chat App

intermediate

Build a chat application with WebSocket connection, message history, typing indicators, and auto-reconnection.

Live Notification System

advanced

Compare implementing notifications with both WebSockets and Server-Sent Events to understand trade-offs.

Industry Examples

Zomato

Zomato uses WebSockets for real-time order tracking and delivery partner location streaming via GPS → Redis → WebSocket push.

Slack

Slack's real-time messaging uses WebSockets for instant message delivery and presence indicators.

Resources

MDN - WebSocket API

docs

MDN - Server-Sent Events

docs

Related Questions

How do you implement data polling in JavaScript?

mid
async

Explain the JavaScript Event Loop and how it handles asynchronous operations.

mid
runtime
Previous
What is requestIdleCallback and how does it compare to other scheduling APIs?
Next
How would you implement Function.prototype.bind from scratch?
PrevNext