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
42

Frontend System Design · Lesson 42 of 86 · 4 min

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

This is about choosing the right tool for the job and defending that choice. In an interview, you won't just list technologies; you'll justify why one fits a specific use case better than another.

Match the Use Case to the Technology

Your first move in a real-time system design question is to map the user need to a specific technology. The three common use cases have clear best-fit options. Getting this wrong is a red flag.

  • Chat & Collaboration: Requires two-way, low-latency communication. Users send and receive. This is a job for WebSockets. There is no other serious contender.

  • Notifications & Alerts: Primarily one-way, from server to client. A user gets a notification; they don't typically send one back over the same channel. Server-Sent Events (SSE) are designed for this.

  • Live Data Feeds: Stock tickers, sports scores, dashboards. This is also one-way. SSE is a strong choice, but if the app already has a WebSocket connection for another feature, you might reuse it.

Polling is your fallback for environments where WebSockets or SSE are blocked, or for data that updates infrequently (e.g., every 30+ seconds). If you suggest polling for a chat app, you've already lost.

Designing a Chat System

Chat is the classic real-time problem. The core requirement is that multiple clients can send and receive messages from each other instantly.

WebSockets provide a persistent, bi-directional channel. The client can use socket.send() to push a message to the server, and the server can push messages to all clients in a "room" or channel. This is the fundamental flow.

In an interview, after you establish WebSockets as the choice for chat, the conversation will move to features built on top of it. Be ready to discuss:

  • Typing Indicators: The client sends a {type: 'TYPING_START'} event via WebSocket. The server broadcasts this to the room. Use a debounce on the client to avoid flooding the server.
  • Presence: How do you know who is online? The simplest way is to track active WebSocket connections on the server. When a user connects, they're online. When they disconnect, they're offline.
  • Message History: When a user joins a channel, how do they see old messages? This isn't a real-time problem. The client makes a standard REST or GraphQL request to fetch the last N messages. Real-time updates then come over the WebSocket.

Handling Notifications and Live Feeds

These use cases are about pushing data from the server to the client. The client is mostly a passive listener.

The trap: Over-engineering with WebSockets when SSE would do. SSE runs over standard HTTP and has built-in support for reconnection, making it simpler to manage. If all you need is a one-way feed of stock prices or social media alerts, SSE is the cleaner, more direct solution.

The nuanced answer is to consider the whole system. If your application already has a WebSocket connection for a chat feature, it's often better to add a new message type (e.g., {type: 'NOTIFICATION', payload: ...}) and send it over the existing connection. Managing one persistent connection is easier than managing two.

This demonstrates you think about resource management (connections, memory) and not just isolated features.

Building a Resilient Client

No real-time connection is permanent. Networks fail, servers restart. Your client-side code must handle this gracefully. An interviewer wants to hear you talk about resilience, not just the happy path.

Your WebSocket client wrapper should handle three things: authentication, message routing, and reconnection.

const socketUrl = 'wss://api.example.com/v1/ws';
let socket: WebSocket;

function connect(authToken: string) {
  // Pass the auth token as a query parameter for the initial handshake.
  socket = new WebSocket(`${socketUrl}?token=${authToken}`);

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

  socket.onmessage = (event) => {
    try {
      const message = JSON.parse(event.data);
      // Route message based on a conventional 'type' property.
      switch (message.type) {
        case 'NEW_MESSAGE':
          // updateChatStore(message.payload);
          break;
        case 'PRICE_UPDATE':
          // updateTickerStore(message.payload);
          break;
        default:
          console.warn('Unknown message type:', message.type);
      }
    } catch (e) {
      console.error('Failed to parse incoming message:', event.data);
    }
  };

  socket.onclose = (event) => {
    console.log('WebSocket disconnected. Reconnecting in 3s...', event.code);
    // Simple reconnection logic. For production, use exponential backoff.
    setTimeout(() => connect(authToken), 3000);
  };

  socket.onerror = (error) => {
    console.error('WebSocket error:', error);
    // An error will often be followed by a close event.
    // The onclose handler will manage reconnection.
  };
}

Authentication is critical. A common pattern is to pass a JWT as a query parameter during the initial new WebSocket() connection. The server validates it before upgrading the HTTP request to a WebSocket connection.

Reconnection logic is non-negotiable. A simple setTimeout is fine for a whiteboard, but for a real system, you should mention "exponential backoff" to avoid hammering a server that might be down.

What to Mention for Senior-Level Answers

Once you've covered the basics, show you understand the harder problems. You don't need to have a perfect solution, but you need to know the problems exist.

Message Guarantees: TCP (which WebSockets use) guarantees message order but not delivery if a connection drops. What if a user is offline for 30 seconds and misses a critical message? Acknowledge this. A full solution involves the server tracking message delivery with client acknowledgements (acks), but just identifying the problem is a strong signal.

Scaling the Backend: A single server can only handle so many concurrent WebSocket connections (thousands, not millions). Mention that the backend will need a way to broadcast messages across multiple server instances. This is typically done with a message broker like Redis Pub/Sub or Kafka. You're a frontend engineer, but showing you know where the frontend's responsibility ends and the backend's begins is a sign of seniority.

Try it

Connect to a public WebSocket echo server (like wss://socketsbay.com/wss/v2/1/demo/). Build a minimal UI with an input field and a button to send messages, and a list to display messages received from the server. Implement a status indicator that shows "Connected" or "Disconnected" based on the onopen and onclose events.

Next: We'll move from use cases to implementation patterns in "Designing a Real-Time Data Flow".

Lock it in — apply this lesson under interview conditions.

Try a free mock interviewPractice system design problems
Previous

Real-Time: Polling, SSE and WebSockets

Next

Designing a Real-Time Data Flow