Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 37

Real-time Communication: Choosing the Right Transport

Recommended resources

Welcome to the first lesson of our module on Real-Time & Collaborative Systems. In our previous lesson, we designed the rendering architecture for a high-traffic news platform and identified a "live blog" as a feature requiring a special approach. Standard rendering strategies get content to the browser, but they don't solve the problem of pushing new updates to the user instantly. This is where real-time communication protocols become critical.

Your experience in scaling e-commerce platforms has likely involved solving for data freshness, but mostly through client-pull mechanisms like caching with stale-while-revalidate. This lesson shifts our focus to server-push architectures. We will dissect the primary transport mechanisms—Long Polling, Server-Sent Events (SSE), and WebSockets—to understand their trade-offs, enabling you to make and defend architectural choices for real-time features in a senior-level interview.

1. The Fundamental Problem: HTTP's Request-Response Model

At its core, standard HTTP is a pull protocol. The client requests, the server responds, and the interaction ends. This is efficient for fetching documents but fundamentally unsuited for applications where the server needs to notify the client about an event the moment it happens.

Imagine a chat application. Without a real-time mechanism, your client would have to ask the server every second, "Any new messages? How about now? Now?" This approach, known as Short Polling, is incredibly inefficient. It generates a massive number of requests, most of which return empty, and introduces a delay equal to the polling interval. For any system at scale, it's a non-starter.

To overcome this, engineers developed a series of progressively more sophisticated techniques. Let's explore the three main contenders you'll be expected to compare in an interview.

[Frontend System Design] Design Real-Time Updates

To frame our discussion, this video by Dmitriy Zhiganov effectively breaks down why real-time updates are necessary and challenges the common junior-level assumption that WebSockets are always the default, correct answer.

First, watch the introduction to real-time updates and the distinction between pull and push strategies. Then, pay close attention to the section where the presenter argues against a "WebSocket-first" mentality. This mindset of critically evaluating trade-offs is precisely what interviewers look for in a senior candidate.


2. The Contenders: Polling, SSE, and WebSockets

Let's look at the evolution of these technologies and their core mechanics. This image provides an excellent high-level visual summary of the communication patterns.

This diagram illustrates the client-server interaction patterns for Short Polling, Long Polling, Server-Sent Events (SSE), and WebSockets, highlighting their key characteristics.

2.1 Long Polling: An HTTP "Hack"

Long Polling is a clever improvement over short polling. Instead of the server responding immediately, it holds the client's request open until it has new data to send.

  • Mechanism:
    1. The client sends an HTTP request to the server.
    2. The server doesn't respond immediately. It waits.
    3. When a new event occurs (e.g., a new chat message arrives), the server sends the data in the response and closes the connection.
    4. The client immediately opens a new long-polling request to wait for the next event.

This pattern, sometimes called a "Hanging GET," significantly reduces the number of useless, empty responses. For years, it was the go-to technique for services like Twitter to deliver notifications.

2.2 Server-Sent Events (SSE): Formalized One-Way Push

SSE is a standard that formalizes the idea of a persistent, one-way, server-to-client stream over a single HTTP connection.

  • Mechanism:
    1. The client establishes a connection to a server endpoint, specifying it expects a text/event-stream.
    2. The server keeps this single HTTP connection open indefinitely.
    3. Whenever a new event occurs, the server writes a specially formatted message to the response stream.

The browser's native EventSource API handles this connection automatically, providing a simple event-driven interface. Crucially, it also handles reconnections automatically. If the connection drops, the browser will attempt to reconnect and send the ID of the last event it received (Last-Event-ID), allowing the server to replay any missed messages.

2.3 WebSockets: The Full-Duplex Channel

WebSockets are a different protocol entirely. They provide a persistent, bidirectional, full-duplex communication channel over a single TCP connection.

  • Mechanism:
    1. The connection starts as a standard HTTP request with an Upgrade header.
    2. If the server agrees, it responds with a 101 Switching Protocols status, and the connection is "upgraded" from HTTP to the WebSocket protocol.
    3. From this point on, it's a raw TCP socket. Both the client and server can send messages to each other at any time with very low overhead.

This is the only one of the three that natively supports two-way communication, which is a critical distinction.


3. Deep Dive: Trade-offs and Decision Framework

Now that we understand the "how," let's get to the "why" and "when." Choosing the right technology requires a deep understanding of their trade-offs in terms of performance, complexity, and infrastructure.

The following resource provides one of the best and most comprehensive analyses of these patterns available. We will use it as our primary reference for this deep dive.

Real-Time Communication: WebSockets, SSE, and Long Polling ...

This article from Abstract Algorithms is a senior-level breakdown of the core real-time patterns. It moves beyond simple definitions into protocol costs, server resource profiles, and real-world examples.

Please read the following sections carefully: Start with How Each Pattern Works for a detailed explanation of Long Polling and SSE. Continue with the section on WebSockets to complete the picture. Next, read through the Real-World Applications section. Note which companies use which technology and why (e.g., ChatGPT -> SSE, Slack -> WebSockets). Finally, and most importantly, study the Trade-offs and Failure Modes. This table and the discussion on failure modes are prime material for interview discussions.

After studying the article, the trade-offs should be much clearer. Let's crystallize them in a direct comparison.

This table provides a side-by-side comparison of Long Polling, WebSockets, and SSE across key features like directionality, connection type, data format, and common use cases.

The most critical question that should guide your decision is: Do you need bidirectional communication?

  • If YES (client and server both need to push data spontaneously): You need WebSockets. This is non-negotiable for applications like chat (sending messages, typing indicators), collaborative editors (cursor positions, edits), or multiplayer games (player state). Emulating this with SSE + HTTP POSTs is inefficient and complex.
  • If NO (only the server pushes data to the client): Server-Sent Events (SSE) should be your default choice. It is simpler to implement, works over standard HTTP (making it friendly to proxies and firewalls), and has built-in reconnection logic. Use cases include news feeds, stock tickers, live sports scores, build log streaming, and AI response streams like ChatGPT.
  • If you are constrained by legacy infrastructure: Long Polling serves as a robust fallback. If corporate firewalls or old proxies block the long-lived connections required by SSE or the protocol upgrade of WebSockets, Long Polling will almost always work since it's just a standard HTTP request with a long timeout.

To further solidify your decision-making process, let's consult one more resource.

Frontend System Design: Communication Protocols & Real-Time Data - DEV Community

This DEV Community article offers a very practical, interview-focused perspective, including a clear decision flowchart.

First, review the Decision Flowchart to see a visual representation of the thought process. Then, read the interview question answer for Q1: SSE vs. WebSocket, which provides a concise summary table.


4. Senior-Level Insight: Beyond the Basics

A mid-level engineer can list the pros and cons. A senior engineer discusses infrastructure complexity and failure modes at scale.

  • Scaling WebSockets is Hard: A WebSocket connection is stateful and pinned to a specific server instance. If you have a million users connected across 100 servers, how does a message arriving at Server 1 reach a user connected to Server 50? You need a message broker/pub-sub layer (like Redis or Kafka) that all servers subscribe to. This adds significant operational complexity and another potential bottleneck.
  • SSE is Simpler to Scale: For user-specific notifications (the most common use case), SSE often doesn't require a complex broker. Since each stream is just an independent HTTP connection, you can route notifications to the correct server holding the user's connection. It scales more like a traditional web service.
  • Connection Health is Your Responsibility: For both SSE and WebSockets, you cannot assume a connection, once established, will stay alive forever. Network middleboxes (proxies, NAT gateways) will silently terminate "idle" TCP connections. You must implement an application-level heartbeat/ping-pong mechanism to keep the connection active and detect silent drops. SSE has automatic reconnection, but for WebSockets, you must implement this logic yourself (often with exponential backoff and jitter to prevent a "thundering herd" problem after a server restart).

Conclusion

In this lesson, we deconstructed the three primary patterns for implementing real-time updates on the web. You can now confidently compare them based on their technical merits and operational costs, a crucial skill for any frontend system design interview.

Key Takeaways:

  • The Bidirectionality Litmus Test: The choice between SSE and WebSockets almost always hinges on whether the client needs to push data to the server spontaneously. If not, SSE is the simpler, more robust choice.
  • SSE as the Modern Default for Server-Push: With built-in reconnection, a simple API, and HTTP-friendliness, SSE is the go-to for one-way data streams like notifications, live feeds, and status updates.
  • WebSockets for True Interactivity: For chat, collaborative editing, and gaming, the full-duplex, low-latency nature of WebSockets is essential. Be prepared to discuss the scaling complexities (sticky sessions, pub/sub brokers).
  • Long Polling as the Universal Fallback: While less efficient, its foundation in basic HTTP makes it the most compatible option for environments with restrictive network policies.

In our next lesson, we will dive deeper into the collaborative editing use case. Now that we understand how to establish a bidirectional channel with WebSockets, we need to explore what we send over that channel to allow multiple users to edit a document simultaneously without corrupting data. This will lead us to a conceptual comparison of two fundamental algorithms: Operational Transformation (OT) and Conflict-free Replicated Data Types (CRDTs).