WebSockets & Real-Time Apps

Introduction to Real-Time Web

18 min Lesson 1 of 35

What is Real-Time Communication?

Real-time communication on the web refers to the immediate exchange of data between a client and server with minimal latency. Unlike traditional web applications where users must refresh the page to see updates, real-time applications push updates instantly as they occur.

Real-Time Examples: Chat applications, live sports scores, stock tickers, collaborative editing tools (Google Docs), online gaming, and notification systems all rely on real-time communication.

HTTP Limitations

The traditional HTTP protocol follows a request-response model that has inherent limitations for real-time communication:

  • Client-Initiated: The client must always initiate communication; the server cannot push data to the client without a request
  • Stateless: Each request is independent, requiring headers and authentication to be sent repeatedly
  • High Overhead: HTTP headers add significant overhead to each request/response cycle
  • Connection Lifecycle: Connections are typically short-lived and closed after each response
// Traditional HTTP Request GET /api/messages HTTP/1.1 Host: example.com Authorization: Bearer token123 Accept: application/json // Server Response HTTP/1.1 200 OK Content-Type: application/json { "messages": [...] } // Connection closes after response

Polling: The First Attempt at Real-Time

Polling is a technique where the client repeatedly sends HTTP requests at regular intervals to check for updates:

// Simple polling implementation function pollForUpdates() { setInterval(async () => { const response = await fetch('/api/messages'); const data = await response.json(); updateUI(data); }, 3000); // Poll every 3 seconds }
Polling Disadvantages:
  • Wasteful: Most requests return no new data
  • High latency: Updates can be delayed by the polling interval
  • Resource intensive: Creates unnecessary server load and network traffic
  • Battery drain: Constant requests drain mobile device batteries

Long-Polling: An Improvement

Long-polling improves upon regular polling by keeping the HTTP connection open until new data is available:

// Long-polling implementation async function longPoll() { try { const response = await fetch('/api/messages?timeout=30'); const data = await response.json(); updateUI(data); longPoll(); // Immediately reconnect } catch (error) { setTimeout(longPoll, 5000); // Retry after delay } }

How it works: The server holds the request open until new data arrives or a timeout occurs. Once the client receives a response, it immediately sends a new request.

Long-polling reduces unnecessary requests compared to regular polling but still requires the overhead of HTTP headers on each reconnection and is more complex to implement correctly.

Server-Sent Events (SSE)

Server-Sent Events provide a standardized way for servers to push updates to clients over a single HTTP connection:

// Client-side SSE implementation const eventSource = new EventSource('/api/stream'); eventSource.onmessage = (event) => { const data = JSON.parse(event.data); console.log('Received:', data); }; eventSource.onerror = (error) => { console.error('SSE error:', error); };

SSE Characteristics:

  • Unidirectional: Server to client only
  • Text-based: Uses text/event-stream content type
  • Auto-reconnection: Browsers automatically reconnect on failure
  • HTTP-based: Works through most proxies and firewalls

WebSockets: True Bidirectional Communication

WebSockets provide a full-duplex communication channel over a single TCP connection, enabling real-time, bidirectional data exchange:

// Basic WebSocket connection const socket = new WebSocket('ws://example.com/socket'); socket.onopen = () => { console.log('Connected'); socket.send('Hello Server!'); }; socket.onmessage = (event) => { console.log('Received:', event.data); };
WebSocket Advantages:
  • Low Latency: Persistent connection eliminates handshake overhead
  • Bidirectional: Both client and server can send messages anytime
  • Efficient: Minimal framing overhead (2-14 bytes per frame)
  • Binary Support: Can transmit text or binary data

Real-Time Application Use Cases

1. Chat and Messaging

Instant messaging requires immediate delivery of messages, typing indicators, and presence status updates.

2. Collaborative Editing

Multiple users editing the same document simultaneously need to see each other's changes in real-time with operational transformation or CRDT algorithms.

3. Live Data Dashboards

Financial dashboards, analytics platforms, and monitoring systems display continuously updating data streams.

4. Online Gaming

Multiplayer games require ultra-low latency communication for player positions, actions, and game state synchronization.

5. Notifications and Alerts

Push notifications for social media updates, system alerts, or breaking news delivered instantly to connected clients.

6. IoT and Sensor Data

Internet of Things devices streaming sensor data, telemetry, and control commands in real-time.

Comparison Table

Technique | Latency | Overhead | Bidirectional | Complexity ----------------------------------------------------------------- Polling | High | Very High| No | Low Long-Polling | Medium | High | No | Medium SSE | Low | Medium | No | Low WebSockets | Very Low| Very Low | Yes | Medium
Exercise: Think about an application you use daily. Identify whether it uses real-time communication and what technique it might be using. Consider:
  • Does it show instant updates without page refresh?
  • Is communication one-way or two-way?
  • What would happen if it used polling instead of WebSockets?

When to Use WebSockets

Good Use Cases:

  • Frequent bidirectional communication needed
  • Low latency is critical
  • High message frequency
  • Real-time collaboration features

When Not to Use WebSockets:

  • Infrequent updates (SSE or polling may suffice)
  • Unidirectional data flow (SSE is simpler)
  • RESTful API pattern preferred
  • Caching and CDN benefits needed
Best Practice: Start with the simplest solution that meets your requirements. SSE or long-polling might be sufficient for many use cases before introducing the complexity of WebSockets.

Summary

Real-time web communication has evolved from inefficient polling to sophisticated WebSocket implementations. Understanding the limitations of HTTP, the improvements offered by long-polling and SSE, and the capabilities of WebSockets is essential for building modern real-time applications. In the next lesson, we'll dive deep into the WebSocket protocol itself.