WebSockets & Server-Sent Events
Basics
Visual Representation
What is it?
π Think of it like different ways to stay updated:
Normal HTTP is like texting someone "Any news?" every 5 minutes. Polling β inefficient if nothing changed.
Server-Sent Events (SSE) is like subscribing to a news channel β they push notifications TO you whenever something happens. One-way: server β client.
WebSockets is like a phone call β once connected, BOTH sides can talk at any time. Two-way: client β server simultaneously.
In regular HTTP, the client asks, server responds, connection closes. But what if you need REAL-TIME updates? (Chat messages, live scores, stock prices, Uber driver location). You need the server to push data without the client constantly asking.
π‘ Simple Summary: HTTP = client asks every time. SSE = server pushes to client. WebSocket = both talk freely, anytime, like a phone call.
How it works β Like you're watching it happen
WebSockets:
Server-Sent Events (SSE):
β But wait β why not just use WebSockets for everything?
WebSockets are MORE complex β they need special server infrastructure, don't work with standard HTTP caching/CDN, and are harder to scale (load balancers need sticky sessions). If you ONLY need serverβclient updates (stock prices, notifications, live scores), SSE is simpler, works over standard HTTP, auto-reconnects, and is supported by all browsers. Use WebSockets only when the client ALSO needs to send frequent data (chat, multiplayer games).
Why should you care? (Interview perspective)
Key Things to Remember
Real Examples You Use Daily
π¬ WhatsApp Web/Slack β Uses WebSockets. When someone sends you a message, the server instantly pushes it to your open WebSocket connection. You also send messages through the same connection. Two-way, real-time.
π Zerodha/Groww (Stock trading) β Live stock prices use WebSockets or SSE. Prices change every millisecond β polling would be too slow and expensive. The server streams price updates to your screen in real-time.
π Uber driver tracking β When you're watching your driver approach on the map, that's live location being pushed to your phone. The driver's app sends position updates (WebSocket up), Uber pushes them to your map (WebSocket down).
π Instagram notifications β When someone likes your post, you get an instant notification. The server pushes this via a persistent connection (SSE or WebSocket) rather than your app constantly asking "any new notifications?"
Common Mistakes in Interviews
β Using WebSockets when SSE is enough β "For live cricket scores, I'd use WebSockets." But cricket scores are ONE-WAY (server β client). SSE is simpler, auto-reconnects, and works over standard HTTP infrastructure. Use WebSocket only when the CLIENT also needs to send frequent messages.
β Forgetting the scaling problem β With 1M WebSocket connections, if user A (on Server 1) sends a message to user B (on Server 3), how does Server 3 know? You need Redis Pub/Sub or a message broker between servers.
β Not mentioning heartbeats β Without ping/pong, a dead connection sits silently. The server thinks the client is still connected, wasting resources. Heartbeats detect dead connections.
β Ignoring reconnection logic β Networks are flaky. Mobile users switch between WiFi and 4G. Your WebSocket WILL disconnect. You need exponential backoff reconnection and message replay (what did I miss while disconnected?).
β Saying "polling is always bad" β For dashboards updating every 5 minutes, simple polling is fine and SIMPLER to build. WebSocket overhead isn't worth it for infrequent updates.
π― Interview One-Liner
"WebSockets provide full-duplex, persistent connections for bidirectional real-time communication like chat, while SSE offers simpler one-way server-to-client streaming over standard HTTP β and the choice depends on whether the client needs to frequently send data back or just receive updates."
Interview Q&A
Q: Design the real-time component of a chat application. What protocol would you choose?
WebSockets β because chat is bidirectional (users send AND receive messages). Each user maintains a persistent WebSocket connection to a chat server. When User A sends a message, their chat server receives it, stores it in the database, then pushes it to User B's WebSocket. For scale, I'd use Redis Pub/Sub between servers so any server can deliver to any user's connection.
Q: How would you handle 1 million concurrent WebSocket connections?
One server can handle ~50K-100K WebSocket connections (with event-driven I/O like Node.js). So I'd need 10-20 servers. Use a load balancer with sticky sessions (or use the user ID to deterministically route to a server). Add Redis Pub/Sub so if user A is on Server 1 and their friend is on Server 5, the message still reaches them. Monitor memory carefully β each connection holds state.
Q: SSE vs WebSocket β when would you pick SSE?
SSE when data flows ONE WAY: server β client. Live sports scores, stock tickers, news feeds, deployment logs, notification streams. SSE advantages: works over standard HTTP (CDN-compatible), auto-reconnects with last-event-ID, simpler to implement. I'd pick WebSocket only when the client needs to send frequent messages too β chat, collaborative editing, multiplayer games.
Q: What happens to WebSocket connections during a server deployment?
All connections to that server DROP. Users experience a brief disconnect. Solutions: (1) Rolling deployments β update servers one by one, only draining connections from the server being updated. (2) Connection draining β stop new connections to the old server, wait for existing ones to close naturally or timeout. (3) Client-side reconnection with exponential backoff. (4) Message queue to buffer messages during the transition.
Q: How does a load balancer work with WebSocket connections?
Tricky! Normal load balancers distribute each REQUEST independently. But WebSocket is a PERSISTENT connection β it must stay on the same server. Solution: use "sticky sessions" (route by user ID or connection ID to the same backend server). Or use a layer 4 load balancer that routes TCP connections, not individual HTTP requests. The initial HTTP upgrade request gets routed, then all subsequent WebSocket frames stay on that connection.
Q: What's long-polling and why is it a poor man's WebSocket?
Long-polling: client sends a request, server HOLDS it open (doesn't respond immediately). When new data arrives, server responds, client immediately sends another request. Repeat. It simulates server push using regular HTTP. Drawbacks: high overhead (new HTTP request for every message), headers resent every time, and servers hold idle connections. But it works EVERYWHERE (even behind strict proxies that block WebSockets). It's the fallback when WebSocket isn't possible.
Quick Quiz
1/5You're building a live cricket score website. Which technology is most appropriate?