Backend
WebSocket
HTTP vs. WebSocket & Patterns

HTTP vs. WebSocket & Real-Time Patterns

When building real-time applications (such as a chat room, multiplayer game, or live stock ticker), you need instant two-way communication between the client and the server.

With traditional HTTP, clients must repeatedly ask "Are there any new messages?" (polling), which wastes bandwidth, CPU cycles, and introduces latency. WebSockets solve this by establishing a permanent, bi-directional channel over a single connection.


1. The Core Limitation of HTTP

HTTP is built around a request-response model: the client sends a request, the server returns a response, and the connection is closed.


2. HTTP Workarounds & Why They Fall Short

Before WebSockets became a standard, developers used various workarounds to simulate real-time updates:

1. Short Polling

The browser executes a setInterval loop to query the server every $N$ seconds:

// ❌ Inefficient short polling
setInterval(async () => {
  const res = await fetch("/api/chat/messages");
  const messages = await res.json();
  renderMessages(messages);
}, 1000); // Polls every 1 second
  • Problems: 95%+ of requests return empty responses, wasting bandwidth and hammering your database. Adding a 1-second interval means users experience up to a 1-second delay for every message.

2. Long Polling

The client sends an HTTP request, and the server holds the request open until new data arrives. Once the server responds, the client immediately sends another request:

async function startLongPolling() {
  try {
    const res = await fetch("/api/chat/messages/wait");
    const data = await res.json();
    renderMessages(data);
  } finally {
    startLongPolling(); // Immediately reconnect
  }
}
  • Problems: High overhead from constantly opening and closing TCP/TLS handshakes; complex server connection management.

3. Server-Sent Events (SSE)

A one-way persistent HTTP connection where the server pushes text streams to the client:

const eventSource = new EventSource("/api/live-stream");
 
eventSource.onmessage = (event) => {
  const data = JSON.parse(event.data);
  updateDashboard(data);
};
  • When to use SSE: Excellent for one-way read-only streams (e.g., streaming ChatGPT responses, live sports scores).
  • Limitations: Unidirectional only. If the client wants to send data back, it must issue separate HTTP POST requests.

3. Enter WebSocket: Full-Duplex Real-Time Communication

WebSocket provides a persistent, full-duplex TCP connection established via an initial HTTP handshake.

Basic Browser Client Example

// Open a persistent WebSocket connection
const socket = new WebSocket("wss://api.myapp.com/ws");
 
// Connection established
socket.addEventListener("open", () => {
  console.log("Connected to WebSocket server!");
  socket.send(JSON.stringify({ action: "join_room", room: "general" }));
});
 
// Receive live message from server
socket.addEventListener("message", (event) => {
  const payload = JSON.parse(event.data);
  console.log("Incoming message:", payload);
});
 
// Send message to server anytime
function sendChatMessage(text) {
  socket.send(JSON.stringify({ action: "chat", text }));
}

4. HTTP vs. WebSocket Comparison

FeatureHTTP / RESTWebSocket
Connection StyleNew TCP connection per request (or keep-alive)Single persistent TCP connection
Data Flow DirectionUnidirectional (Client to Server)Bi-directional Full-Duplex (Client to Server & Server to Client)
Header Overhead~500 to 1500 bytes per request2 to 14 bytes per frame
LatencyHigh (50-300ms with TCP/TLS setup)Very Low (under 10ms)
Server PushNot supported (without SSE or polling)Native first-class support
Best Used ForCRUD operations, authentication, static assetsChat, multiplayer gaming, live collaboration

5. Ideal WebSocket Use Cases


6. When NOT to Use WebSocket

Use standard HTTP REST / GraphQL APIs when:

  1. Data changes infrequently: Blog posts, product catalogs, user profile views.
  2. You need HTTP caching: CDNs (Cloudflare, Fastly) and browser caches only work with HTTP GET requests.
  3. SEO is critical: Search engine web crawlers do not execute WebSocket streams.
  4. Simple form submissions: Login, checkout, file uploads, and standard CRUD.

đź’ˇ Real-World Scale

  • Discord: Handles 10M+ concurrent WebSocket connections across distributed gateway clusters.
  • Slack: Targets sub-100ms message delivery across desktop and mobile clients.
  • WhatsApp: Processes 500B+ real-time messages per day over persistent socket infrastructure.

👉 Next Step: Discover how the initial HTTP 101 upgrade handshake works in Connection Lifecycle & Upgrade Handshake.