Skip to content

Latest commit

 

History

History
116 lines (80 loc) · 6.56 KB

File metadata and controls

116 lines (80 loc) · 6.56 KB

2.0.3 Real-Time Communication: Polling, Long Polling, and WebSockets

Intuitive Explanation

Real-time communication is about getting updates instantly without the user having to refresh the page.

  • Polling (The Annoying Kid): The client repeatedly asks the server, "Are we there yet? Are we there yet?" Every second. Very inefficient and wastes server resources.
  • Long Polling (The Patient Waiter): The client asks the server, "Do you have the food yet?" The server holds the request until the food is ready, then responds. This is much better, but still requires a new request cycle for the next update.
  • WebSockets (The Open Phone Line): A persistent, two-way phone line is established. Data can be sent from client to server, or server to client, instantly at any time. The most efficient way to handle continuous, low-latency updates.

In-Depth Analysis

1. Polling (Short Polling)

The client sends requests to the server at regular, short intervals to check for new data.

  • Pros: Simple to implement; works universally across all browsers and servers.
  • Cons: High Latency (data is delivered only after the poll interval); Massive Overhead (most requests are empty, wasting bandwidth and CPU on both ends).

2. Long Polling

The client sends a request, and the server intentionally delays the response until an update is available or a timeout occurs. Once the client receives a response, it immediately sends a new request.

  • Pros: Lower latency than short polling; reduces the number of empty responses.
  • Cons: Still requires a new connection setup (HTTP handshake) for every update; can tie up a large number of server connections waiting for data.

3. WebSockets

An upgrade to the standard HTTP connection that establishes a full-duplex (two-way) persistent connection over a single TCP socket.

  • Pros: Lowest Latency; minimal overhead after the initial handshake; data can be pushed from the server to the client without the client requesting it first.
  • Cons: Stateful Connection: The server must maintain the state of every open connection, making horizontal scaling more complex (requires Sticky Sessions or a Redis Pub/Sub layer).

4. Server-Sent Events (SSE)

A standard that allows a server to push data to a client over a single, long-lived $HTTP$ connection. It is * unidirectional* (server to client only).

  • Pros: Easier to implement than WebSockets (works over standard HTTP); automatic reconnection is built-in.
  • Cons: Cannot send data from the client back to the server on the same pipe; less suitable for scenarios requiring two-way chat.

Key Concepts / Tradeoffs

Mechanism Connection Type Directionality Use Case
Polling Connection closed per request. Client → Server Non-critical updates, minimal traffic scenarios.
Long Polling Connection held, then closed per update. Client → Server Chat messages, social feed updates (less continuous than WebSockets).
WebSockets Persistent, open TCP socket. Bi-directional Collaborative editing, real-time gaming, VoIP.
SSE Persistent, open HTTP connection. Server → Client Stock tickers, news feeds, server logs streaming.

✏️ Design Challenge

Problem

You are designing a live commentary feed for a major cricket match. The feed only pushes text updates from the server to thousands of concurrent users. Should you use WebSockets or Server-Sent Events (SSE)? Justify your choice based on protocol simplicity and required directionality.

Solution

🧩 Scenario Overview

  • Live cricket commentary feed (text-only updates).
  • Server → thousands of users (broadcast).
  • Clients don’t need to send data back — only receive updates.
  • Need real-time, low-latency push, and protocol simplicity.

✅ Choice: Server-Sent Events (SSE)

Aspect SSE WebSocket
Directionality One-way (Server → Client) Two-way (Full duplex)
Underlying Protocol HTTP/1.1 (text/event-stream) Custom upgrade from HTTP to WebSocket protocol
Complexity Simple (no handshake, no ping/pong) More complex (connection upgrade, heartbeat)
Reconnection Built-in automatic reconnection Must handle manually
Browser Support Native EventSource API Requires manual WebSocket client setup
Use Case Fit Perfect for live text or news feeds Better for interactive apps (chat, gaming)

✅ Why SSE fits here

  • The commentary feed is server-to-client only — no bidirectional data.
  • SSE runs over standard HTTP, making it simple, firewall-friendly, and easy to scale (HTTP load balancers, caching).
  • Auto-reconnect and event IDs handle intermittent network drops gracefully.
  • Lightweight — avoids the overhead of maintaining full duplex WebSocket channels.

⚠️ When WebSockets Would Be Needed

If the system later required:

  • Users to chat or comment back, or
  • Real-time bidirectional interactions (like score prediction games),

then WebSockets would become the better choice.

✅ Final Summary

Aspect Decision Reason
Protocol Server-Sent Events (SSE) One-way push from server to many clients, minimal complexity
Why not WebSocket Overkill for one-way data; adds unnecessary connection and heartbeat logic
Advantages Simpler to implement, native browser support, auto-reconnect, efficient text streaming