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.
- The
WebSocketClientreceives a message. - It parses the message and determines its semantic type (e.g.,
new-chat-message,user-typing-status). - It publishes an event to the Event Bus with this type and payload.
- 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.