Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
Frontend System Design Roadmap
  1. 1.HTTP/1.1 vs HTTP/2 vs HTTP/3 (QUIC)
  2. 2.TCP and TLS Handshakes: Connection Setup Costs
  3. 3.Browser Network Stack and Connection Pooling
  4. 4.GET vs POST and Idempotency in HTTP
  5. 5.The Critical Rendering Path (CRP)
  6. 6.DOM, CSSOM and the Render Tree
  7. 7.Layout, Paint and Compositing
  8. 8.Reflows and Repaints Explained
  9. 9.Event Loop: Call Stack, Task and Microtask Queues
  10. 10.Async JavaScript: Promises and async/await
  11. 11.Web Workers: Multi-threading in the Browser
  12. 12.Browser Storage: Cookies, Web Storage, IndexedDB
  13. 13.Client-Side Storage: Limits and Security Risks
  14. 14.Choosing the Right Client-Side Storage
  15. 15.HTTP Caching: Cache-Control, ETag, Last-Modified
  16. 16.Browser-Level Caching Mechanisms
  17. 17.Cache Invalidation for Frontend Apps
  18. 18.Structuring a Large Single-Page App
  19. 19.Component-Based Architecture Principles
  20. 20.Props, State and Component Lifecycle
  21. 21.Module Bundling Basics
  22. 22.Core Web Vitals: LCP, INP and CLS
  23. 23.FCP and Time to Interactive (TTI) Explained
  24. 24.Measuring Performance: Lighthouse and WebPageTest
  25. 25.Asset Compression and Minification Basics
  26. 26.What Is a CDN and How Does It Work?
  27. 27.CDN Benefits: Latency, Availability, Offload
  28. 28.CDN Cache Behavior and Invalidation
  29. 29.Global State vs Local Component State
  30. 30.State Patterns: Redux, Zustand and Context
  31. 31.Data Fetching: React Query and SWR
  32. 32.Immutable Data in Frontend State
  33. 33.SSR vs CSR: Rendering Trade-offs
  34. 34.Hydration and Time to First Byte (TTFB)
  35. 35.Static Site Generation (SSG) for Speed and SEO
  36. 36.Incremental Static Regeneration (ISR)
  37. 37.Micro-Frontends: Core Principles
  38. 38.Micro-Frontend Integration Strategies
  39. 39.Communication Between Micro-Frontends
  40. 40.Micro-Frontends: Pros and Cons for Large Teams
  41. 41.Real-Time: Polling, SSE and WebSockets
  42. 42.Real-Time Use Cases: Chat, Alerts, Live Data
  43. 43.Designing a Real-Time Data Flow
  44. 44.Scaling WebSocket Connections
  45. 45.Responsive Images: srcset, sizes and picture
  46. 46.Modern Image Formats: WebP, AVIF, JPEG XL
  47. 47.Lazy Loading Images and Videos
  48. 48.Video Streaming: HLS, DASH, Adaptive Bitrate
  49. 49.REST and GraphQL for Frontend Engineers
  50. 50.Batching, Throttling and Debouncing API Calls
  51. 51.Handling API Errors in the Frontend
  52. 52.Authentication Flows: OAuth and JWT
  53. 53.Global Error Boundaries in React
  54. 54.Error Reporting: Sentry and LogRocket
  55. 55.Graceful Degradation and Fallback UIs
  56. 56.Real User Monitoring (RUM)
  57. 57.CORS: Cross-Origin Resource Sharing
  58. 58.Preventing XSS (Cross-Site Scripting)
  59. 59.CSRF Protection for Frontend Apps
  60. 60.Content Security Policy (CSP)
  61. 61.Storing Auth Tokens: Cookies vs localStorage
  62. 62.PWA Manifest and Installability
  63. 63.Service Workers: Lifecycle and Caching Strategies
  64. 64.Offline Support and Background Sync
  65. 65.Push Notifications for Web Apps
  66. 66.Webpack vs Vite vs Parcel
  67. 67.Code Splitting, Tree Shaking, Asset Optimization
  68. 68.Module Resolution and Hot Module Replacement
  69. 69.Monorepo Tooling: Nx and Lerna
  70. 70.Atomic Design for Component Libraries
  71. 71.Theming and Customization in Design Systems
  72. 72.Accessibility in Component Libraries
  73. 73.Component Library Docs, Testing and Versioning
  74. 74.Publishing and Consuming a Component Library
  75. 75.Full-Text Search: Levenshtein and Fuzzy Matching
  76. 76.Indexing Large Datasets in the Browser
  77. 77.Search Performance: Debouncing and Web Workers
  78. 78.Integrating Backend Search Services
  79. 79.Choosing a Chart Library: D3, Chart.js, Recharts
  80. 80.Rendering Large Datasets: Canvas vs SVG
  81. 81.Interactive, Responsive Data Visualizations
  82. 82.Data Fetching and Aggregation for Dashboards
  83. 83.A/B Test Design and Rollout Strategies
  84. 84.Client-Side vs Server-Side A/B Testing
  85. 85.Feature Flags and Remote Configuration
  86. 86.Experiment Data Collection and Analytics
Frontend System Design Roadmap
43

Frontend System Design · Lesson 43 of 86 · 4 min

Designing a Real-Time Data Flow

This is about architecting the client-side. Your interviewer wants to see you move beyond just new WebSocket() and design a robust, decoupled system.

When you're asked to design a real-time feature like a chat app or a live dashboard, the conversation quickly moves past the API. The real test is how you structure the frontend to handle a continuous, unpredictable stream of data without turning your state into a mess.

This lesson gives you that structure. You'll learn how to isolate network logic, decouple components, and integrate real-time updates into a state management system predictably.

Isolate the connection logic

A raw WebSocket instance in a component is a code smell. It tangles UI with network concerns and makes state management a nightmare. Your first step is to wrap the WebSocket logic in a dedicated module or class.

This wrapper's job is to manage the connection lifecycle. It should handle connecting, sending messages, and—most importantly—reconnecting automatically. Network connections are fragile; your design must assume they will drop.

The trap: Forgetting about reconnection. A candidate who only implements the happy path (onopen, onmessage) shows a lack of production experience.

Here is a minimal, reusable WebSocketClient class. It forms a stable foundation for any real-time feature.

// src/services/websocketClient.ts
type MessageHandler = (data: any) => void;

export class WebSocketClient {
  private ws: WebSocket | null = null;
  private url: string;
  private messageHandlers: Set<MessageHandler> = new Set();
  private reconnectInterval: number = 3000;
  private reconnectTimeoutId: number | null = null;

  constructor(url: string) {
    this.url = url;
    this.connect();
  }

  private connect() {
    this.ws = new WebSocket(this.url);

    this.ws.onopen = () => {
      console.log('WebSocket connected');
    };

    this.ws.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data as string);
        this.messageHandlers.forEach(handler => handler(data));
      } catch (error) {
        console.error('Failed to parse WebSocket message:', event.data);
      }
    };

    this.ws.onclose = () => {
      console.warn('WebSocket closed. Attempting to reconnect...');
      if (this.reconnectTimeoutId) {
        clearTimeout(this.reconnectTimeoutId);
      }
      this.reconnectTimeoutId = window.setTimeout(() => this.connect(), this.reconnectInterval);
    };

    this.ws.onerror = (error) => {
      console.error('WebSocket error:', error);
      this.ws?.close(); // Triggers the onclose handler for reconnect logic
    };
  }

  public send(message: object) {
    if (this.ws?.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify(message));
    } else {
      console.warn('WebSocket not open. Message not sent:', message);
    }
  }

  public subscribe(handler: MessageHandler): () => void {
    this.messageHandlers.add(handler);
    return () => { // Return an unsubscribe function
      this.messageHandlers.delete(handler);
    };
  }

  public close() {
    if (this.reconnectTimeoutId) {
      clearTimeout(this.reconnectTimeoutId);
    }
    this.ws?.close();
  }
}

This implementation uses a simple fixed-interval reconnect. In a real interview, you should mention that exponential backoff is a better strategy to avoid hammering a server that might be temporarily down.

Decouple components with a Pub/Sub layer

Even with a WebSocketClient wrapper, you don't want UI components subscribing to it directly. That would still create a tight coupling between your view layer and the raw data stream.

A client-side publish-subscribe (Pub/Sub) system, often called an Event Bus, acts as a middleman.

  1. The WebSocketClient receives a message.
  2. It parses the message and determines its semantic type (e.g., new-chat-message, user-typing-status).
  3. It publishes an event to the Event Bus with this type and payload.
  4. UI components subscribe to the specific event types they care about, ignoring all others.

This decouples the data source from the data consumers. A ChatWindow component doesn't need to know that messages come from a WebSocket. It only needs to know about the new-chat-message event.

This pattern is a key signal of senior-level thinking. It demonstrates you can design systems that are modular and easy to refactor. You could swap WebSockets for Server-Sent Events later without rewriting any of your UI components.

Make state updates predictable

Real-time data is a side effect. In modern frontend architecture, side effects should not mutate state directly. All state changes must be predictable and traceable.

This means real-time updates must flow through your state management library (Redux, Zustand, etc.) just like any other data.

The trap: Updating component state directly from a WebSocket onmessage handler. This creates an unpredictable, untraceable flow of data that is impossible to debug.

The correct flow is simple: the message handler's only job is to dispatch an action.

// In your WebSocket setup file
import store from './store';
import { webSocketClient } from './services/websocketClient';

webSocketClient.subscribe((message) => {
  // Map incoming message types to Redux action types
  switch (message.type) {
    case 'NEW_MESSAGE':
      store.dispatch({ type: 'chat/messageAdded', payload: message.data });
      break;
    case 'PRICE_UPDATE':
      store.dispatch({ type: 'stocks/priceUpdated', payload: message.data });
      break;
    // ... other message types
  }
});

The data then flows through the standard Redux cycle: an action is dispatched, a reducer calculates the new state, and components subscribed to that state re-render. This preserves the single source of truth and enables tools like time-travel debugging.

This diagram shows the full lifecycle of a message on the client.

Handle high-frequency updates without freezing the UI

What if you're building a collaborative editor that sends cursor positions 30 times per second? Dispatching 30 actions and re-rendering 30 times a second will cripple the browser.

Your interviewer wants to know how you'd handle this backpressure.

The solution is to batch and throttle updates. Instead of processing every message immediately, you collect them in a queue and process the queue once per frame using requestAnimationFrame.

This ensures you never try to update the UI more often than the browser can paint, typically 60 times per second (about every 16.7ms).

const updateQueue = [];
let isProcessing = false;

// The WebSocket message handler just pushes to the queue
webSocketClient.subscribe((update) => {
  updateQueue.push(update);
  if (!isProcessing) {
    processQueue();
  }
});

function processQueue() {
  isProcessing = true;
  requestAnimationFrame(() => {
    // In a real app, you'd dispatch a single action with all batched updates
    const batch = [...updateQueue];
    updateQueue.length = 0; // Clear the queue

    if (batch.length > 0) {
      console.log(`Processing a batch of ${batch.length} updates.`);
      // store.dispatch({ type: 'updates/batchReceived', payload: batch });
    }
    
    isProcessing = false;
    // If new items arrived while processing, schedule another run
    if (updateQueue.length > 0) {
      processQueue();
    }
  });
}

This pattern is crucial for any real-time feature that involves high-frequency events, like live location tracking, collaborative drawing, or real-time analytics. Mentioning it shows you think about performance under load.

Try it

Implement the WebSocketClient class. For the reconnect logic, upgrade the simple setTimeout to use exponential backoff (e.g., wait 1s, then 2s, 4s, up to a max of 30s). Connect it to a public test WebSocket echo server (like wss://socketsbay.com/wss/v2/1/demo/) and verify that it reconnects automatically if you temporarily disconnect your network.

Next: We'll look at how the server handles thousands of these connections in Scaling WebSocket Connections.

Lock it in — apply this lesson under interview conditions.

Try a free mock interviewPractice system design problems
Previous

Real-Time Use Cases: Chat, Alerts, Live Data

Next

Scaling WebSocket Connections