Module 8 - Networking and APIs

WebSockets & SSE

Real-time communication patterns-from polling to persistent connections.

1The Waiting Room Analogy

Simple Analogy
Polling: Asking "is my order ready?" every 5 seconds. Annoying.
Long Polling: Receptionist says "wait here, I'll call when ready."
WebSocket: Two-way intercom-you can both talk anytime.
SSE: PA system-announcements broadcast to everyone.

2Short Polling

Client repeatedly asks server for updates at fixed intervals. Simple but inefficient.

// Client polls every 5 seconds
setInterval(async () => {
  const response = await fetch('/api/notifications');
  if (response.data.length > 0) {
    showNotifications(response.data);
  }
}, 5000);
Pros
  • Simple to implement
  • Works everywhere
  • Stateless
Cons
  • Wastes bandwidth (empty responses)
  • High latency (up to interval)
  • Server load from constant requests

3Long Polling

Client requests, server holds connection open until data is available (or timeout). Better latency than short polling.

1Client sends request
2Server holds connection (waits for data)
3Data arrives → server responds immediately
4Client immediately makes new request
Pros
  • Lower latency than polling
  • Works through firewalls/proxies
  • Simple fallback
Cons
  • Connection overhead (new request each time)
  • Server holds many connections
  • Not truly real-time

4WebSocket

WebSocket is a persistent, full-duplex connection. Both client and server can send messages anytime. Ideal for real-time apps.

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

ws.onopen = () => ws.send(JSON.stringify({ type: 'subscribe', channel: 'trades' }));
ws.onmessage = (event) => console.log('Received:', event.data);
ws.send(JSON.stringify({ type: 'ping' }));

// Server can push anytime
// No request/response pattern-true bidirectional
Pros
  • True real-time (sub-millisecond)
  • Bi-directional communication
  • Low overhead (no HTTP headers per message)
  • Perfect for chat, gaming, trading
Cons
  • Stateful (harder to scale)
  • Some proxies/firewalls block
  • Need reconnection logic
  • No HTTP caching

5Server-Sent Events (SSE)

SSE is server-to-client only streaming over HTTP. Simpler than WebSocket for one-way updates.

// Client
const eventSource = new EventSource('/api/events');

eventSource.onmessage = (event) => {
  console.log('New event:', event.data);
};

eventSource.addEventListener('notification', (e) => {
  showNotification(JSON.parse(e.data));
});

// Server sends events
// Content-Type: text/event-stream
// data: {"message": "Hello"}\n\n
Pros
  • Simple (just HTTP)
  • Auto-reconnection built-in
  • Works through most proxies
  • Event types and IDs
Cons
  • Server-to-client only
  • Limited to text (not binary)
  • Max connections per domain
  • No IE support (but who cares)

6Comparison

AspectPollingLong PollingWebSocketSSE
DirectionClient → ServerClient → ServerBi-directionalServer → Client
LatencyHighMediumLowLow
ComplexitySimpleMediumComplexSimple
Best ForInfrequent updatesFallbackChat, gamingNotifications, feeds

7Key Takeaways

1Polling: Simple but wasteful. Only for infrequent updates.
2Long Polling: Better latency, good fallback for WebSocket.
3WebSocket: True real-time, bi-directional. Best for chat, games, trading.
4SSE: Simple server-to-client streaming. Good for feeds, notifications.
5Use WebSocket when client needs to send often. SSE when server pushes only.

?Quiz

1. Live stock ticker with prices every 100ms. Best choice?

2. News feed with occasional updates. Best choice?