🔥 0
0
Lesson 1 of 5 15 min +150 XP

HTTP vs WebSocket & Use Cases

You're building a chat application. User A sends a message. How does User B see it instantly?

With traditional HTTP, they don't. User B's browser would have to keep asking "any new messages?" over and over. That's polling - and it's inefficient.

WebSockets solve this problem.

The HTTP Limitation

HTTP follows a simple pattern: request → response. The client asks, the server answers. Then the connection closes.

HTTP: REQUEST-RESPONSE

Client → "Give me data"
Server → "Here's the data"
Connection closes
Client → "Any updates?"
Server → "No"
Connection closes
Client → "How about now?"
Server → "Still no"
Connection closes...

WEBSOCKET: FULL-DUPLEX

Client → "Let's connect"
Server → "Connected!"
Connection stays open
Server → "New message!"
Client → "Got it, here's mine"
Server → "Another update!"
Client → "Thanks!"
Still connected...

HTTP Workarounds (And Why They're Not Great)

Before WebSockets, developers used these techniques:

1. Short Polling

Client repeatedly asks for updates:

// Short polling - inefficient!
setInterval(async () => {
  const response = await fetch('/api/messages');
  const messages = await response.json();
  updateUI(messages);
}, 1000); // Every second
Problems

Wastes bandwidth (most requests return "no updates"), adds latency (up to 1 second delay), hammers your server with requests.

2. Long Polling

Server holds the request until there's data:

// Long polling - better but still problematic
async function longPoll() {
  const response = await fetch('/api/messages/wait'); // Server holds this
  const messages = await response.json();
  updateUI(messages);
  longPoll(); // Immediately reconnect
}
Better, But...

Still creates new connections constantly, server needs to manage hanging requests, not truly bi-directional.

3. Server-Sent Events (SSE)

Server can push to client (one-way):

// SSE - one-way server push
const events = new EventSource('/api/stream');
events.onmessage = (event) => {
  updateUI(JSON.parse(event.data));
};
Good for...

One-way updates (news feeds, stock tickers). But if you need to SEND data back frequently, you still need separate HTTP requests.

Enter WebSocket

WebSocket provides a persistent, full-duplex connection over a single TCP socket.

🔌
Persistent

One connection, keep it open

↔️
Full-Duplex

Both sides send anytime

Low Latency

No connection overhead

📦
Low Overhead

Tiny frame headers

// WebSocket - the right tool for real-time
const ws = new WebSocket('wss://example.com/chat');

ws.onopen = () => {
  console.log('Connected!');
  ws.send(JSON.stringify({ type: 'join', room: 'general' }));
};

ws.onmessage = (event) => {
  const message = JSON.parse(event.data);
  updateUI(message);
};

// Send a message anytime
function sendMessage(text) {
  ws.send(JSON.stringify({ type: 'message', text }));
}

Comparison Table

Feature HTTP WebSocket
Connection New per request Persistent
Direction Client → Server Bi-directional
Latency Higher (handshake) Very low
Overhead per message ~800 bytes headers 2-14 bytes
Server push No Yes
Browser support Universal All modern browsers

Ideal WebSocket Use Cases

💬 Chat Applications

Slack, Discord, WhatsApp Web - instant message delivery in both directions.

🎮 Multiplayer Games

Real-time player positions, actions, game state synchronization.

📊 Live Dashboards

Stock tickers, sports scores, analytics - continuous data streams.

📝 Collaborative Editing

Google Docs, Figma - see others' changes as they happen.

📍 Location Tracking

Uber/Lyft driver tracking, delivery updates in real-time.

🔔 Notifications

Push notifications, alerts, real-time activity feeds.

When NOT to Use WebSocket

Use HTTP Instead When:
  • Data doesn't change often (blogs, product pages)
  • You need HTTP caching (CDN, browser cache)
  • Simple request-response patterns (form submissions, API calls)
  • SEO matters (search engines don't execute WebSocket)

Real-World Scale

10M+
Concurrent connections
Discord handles daily
<100ms
Message latency
Slack's target
500B+
Messages per day
WhatsApp processes

Key Takeaways

  • HTTP limitation - Request-response only, server can't push
  • Polling wastes resources - Most requests return "no updates"
  • WebSocket = persistent + bi-directional - Both sides send anytime
  • Low overhead - 2-14 byte headers vs ~800 bytes for HTTP
  • Use for real-time - Chat, games, live data, collaboration

Next up: Connection Lifecycle - Learn how WebSocket connections are established and maintained.

🧠 Quick Quiz

Test your understanding of this lesson.

1

What is the main limitation of HTTP for real-time applications?

2

What makes WebSocket different from HTTP?

3

Which scenario is BEST suited for WebSockets?