Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
Frontend System Design Fundamentals
  1. 1.Introduction to Frontend System Design
  2. 2.Core Frontend Architecture Concepts
  3. 3.Client-Server Interaction Fundamentals
  4. 4.Basic Performance & Accessibility Considerations
  5. 5.State Management Basics & Data Flow
  6. 6.Advanced State Management & Global Stores
  7. 7.Component Libraries & Design Systems
  8. 8.Frontend Build Tools & Development Workflows
  9. 9.Advanced Performance Optimization Techniques
  10. 10.Data Fetching Strategies & Caching
  11. 11.Frontend Security Essentials
  12. 12.Micro-Frontend Architectures
  13. 13.Real-time Communication & WebSockets
  14. 14.Observability, Monitoring, & Logging
  15. 15.Offline-First & Progressive Web Apps (PWAs)
Frontend System Design Fundamentals
13

Frontend System Design · Lesson 13 of 15 · 4 min

Real-time Communication & WebSockets

This topic tests if you can choose the right tool for the job and think about stateful, distributed systems.

When a feature requires instant updates—chat, notifications, collaborative editing—your first thought should be about the communication protocol. The default HTTP request-response model won't cut it. This is where you need a persistent connection.

When to use WebSockets (and when not to)

The core decision is whether you need a persistent, two-way channel. Before WebSockets, we used hacks on top of HTTP.

Polling is the simplest: the client asks the server for updates every few seconds. It's inefficient and introduces latency. Don't propose this unless updates are very infrequent (minutes, not seconds).

Long polling is slightly better. The client makes a request, and the server holds it open until there's an update. This reduces latency but still carries the overhead of establishing a new HTTP connection for every single message.

Server-Sent Events (SSE) are a good choice for one-way data streams from server to client, like a stock ticker or a news feed. It's just a long-lived HTTP connection. If the client never needs to talk back over the same channel, SSE is simpler to implement and scale than WebSockets.

WebSockets provide a true bidirectional, full-duplex connection. After an initial handshake, both client and server can send data at any time with minimal overhead. This is the right tool for chat, multiplayer games, or any feature requiring low-latency, two-way interaction.

The trap: Reaching for WebSockets for everything. If you just need to show a notification from the server, SSE is simpler. If you're just fetching data on user command, standard HTTP is correct. In an interview, justifying your choice is more important than just naming the technology. Show you understand the trade-offs.

How the connection works

A WebSocket connection starts life as a standard HTTP request, which is then "upgraded."

The client sends an HTTP GET request with specific headers (Upgrade: websocket, Connection: Upgrade). If the server agrees, it responds with a 101 Switching Protocols status, and the underlying TCP connection is repurposed for the WebSocket protocol.

From that point on, communication happens via lightweight data frames, not full HTTP requests with headers and cookies. This is why it's so much more efficient for frequent messages.

This handshake is the key detail. It allows WebSockets to work over standard ports 80 and 443, making them firewall-friendly.

Building a resilient client

A WebSocket connection is not permanent. It will drop due to network issues, server restarts, or mobile devices switching from Wi-Fi to cellular. A production-ready client must handle this gracefully.

The trap: Writing client-side code that assumes the connection is always open. Your ws.send() calls will fail, and your users will miss messages.

The solution is to implement automatic reconnection logic. When the onclose event fires, don't just log an error. Start a timer to attempt a reconnect. To avoid overwhelming a struggling server, use an exponential backoff strategy—wait 1s, then 2s, then 4s, and so on, up to a reasonable maximum.

This example shows a basic reconnection strategy.

function setupReliableWebSocket(url: string) {
  let ws: WebSocket;
  let reconnectInterval = 1000; // Start with 1 second
  const maxReconnectInterval = 30000; // Cap at 30 seconds

  const connect = () => {
    ws = new WebSocket(url);

    ws.onopen = () => {
      console.log('WebSocket connection established.');
      reconnectInterval = 1000; // Reset interval on successful connection
    };

    ws.onmessage = (event) => {
      console.log('Message from server:', event.data);
    };

    ws.onclose = (event) => {
      // 1000 means normal, intentional closure.
      if (event.code !== 1000) {
        console.warn(`WebSocket closed. Reconnecting in ${reconnectInterval / 1000}s...`);
        setTimeout(connect, reconnectInterval);
        reconnectInterval = Math.min(reconnectInterval * 2, maxReconnectInterval);
      }
    };

    ws.onerror = (error) => {
      console.error('WebSocket error:', error);
      // The 'onclose' event will usually fire after an error,
      // so we let the onclose handler manage the reconnection.
      ws.close();
    };
  };

  connect();

  return {
    send: (message: string) => {
      if (ws?.readyState === WebSocket.OPEN) {
        ws.send(message);
      } else {
        console.warn('WebSocket not open. Message not sent.');
        // Optional: queue the message to send upon reconnection.
      }
    },
  };
}

// Usage:
// const client = setupReliableWebSocket('ws://localhost:8080');

How to answer the scaling question

A single server handling WebSocket connections is a single point of failure and a performance bottleneck. The interviewer wants to hear how you would scale this to handle thousands or millions of concurrent users.

First, you put multiple WebSocket servers behind a load balancer. This introduces a problem: if a user sends a message to Server A, how do users connected to Server B and C receive it? The servers are isolated.

The solution is a message broker or a publish/subscribe (pub/sub) system acting as a backplane. When Server A receives a message for a chat room, it doesn't try to forward it to other servers directly. Instead, it publishes the message to a shared channel (e.g., a Redis Pub/Sub channel or a Kafka topic named chat_room_123).

All servers (A, B, and C) are subscribed to that channel. They all receive the message from the backplane and can then push it down to their respective connected clients. This decouples the servers and allows you to scale horizontally.

Another consideration for your load balancer is "sticky sessions." Since a WebSocket connection is stateful, it can be beneficial for a reconnecting client to hit the same server it was on before. However, with a pub/sub backplane, this becomes less critical, as any server can handle the user's messages.

Finally, mention security. The WebSocket handshake is an HTTP request, so you can validate the Origin header to prevent cross-site WebSocket hijacking. You can also pass an authentication token (JWT) as a query parameter in the WebSocket URL (ws://.../?token=...) for the server to validate during the initial connection.

Try it

Modify the client-side reconnection code to include a simple message queue. If send() is called while the connection is down, store the message in an array. When the connection is re-established, send all queued messages.

Next: Observability, Monitoring, & Logging

Lock it in — apply this lesson under interview conditions.

Try a free mock interviewPractice system design problems
Previous

Micro-Frontend Architectures

Next

Observability, Monitoring, & Logging