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.