WebSockets & Server-Sent Events

Basics

Visual Representation

Rendering diagram...

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:

  • Upgrade request β€” Client sends a normal HTTP request with a special header: "Hey, can we upgrade this to a WebSocket?"
  • Server agrees β€” Responds with "101 Switching Protocols" β€” the connection is now "upgraded."
  • Open pipeline β€” Now both sides have a persistent, full-duplex (two-way) connection. Either can send a message at ANY time.
  • Messages flow β€” Client sends: "new message: hey!" Server sends: "user_typing: true." No request-response pattern needed!
  • Connection stays open β€” Until one side explicitly closes it or the network dies.
  • Server-Sent Events (SSE):

  • Client opens connection β€” Sends a GET request with "Accept: text/event-stream."
  • Server keeps it open β€” Instead of sending one response and closing, the server keeps the HTTP connection alive.
  • Server pushes data β€” Whenever something happens, the server writes a new "event" down the same open connection.
  • Client just listens β€” Like having the radio on. Data arrives automatically.
  • Auto-reconnect β€” If the connection drops, the browser automatically reconnects and tells the server "last event I got was #42" β€” so it can catch up.
  • ❓ 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)

  • 🎯 "Design a chat system" is one of the most common interview questions β€” WebSockets are the answer
  • Live dashboards, notifications, collaborative editing β€” all need real-time tech
  • Shows you understand WHEN to use what (not everything needs WebSockets)
  • Understanding the trade-offs helps in "Design Uber" (live driver tracking) or "Design stock ticker"
  • Key Things to Remember

  • WebSocket URL β€” Starts with ws:// or wss:// (secure). Not http://.
  • Full-duplex β€” Both sides send simultaneously. Like a phone call, not walkie-talkie.
  • Stateful connection β€” WebSockets maintain an open connection. This means the load balancer needs "sticky sessions" (always route this user to the same server).
  • SSE is HTTP β€” It's just a long-lived HTTP response that keeps sending data. Works with CDN, proxies, everything HTTP works with.
  • SSE is one-way β€” Server β†’ Client only. Client can't send data through SSE (use a separate POST request for that).
  • Polling vs Long-polling vs SSE vs WebSocket β€” Polling (repeated requests, wasteful). Long-polling (hold request until data available, then respond). SSE (server streams). WebSocket (full two-way).
  • Connection limit β€” Browsers allow max 6 HTTP connections per domain. SSE uses one of these! But WebSockets don't count toward this limit.
  • Heartbeats β€” WebSocket connections send periodic "ping/pong" to detect if the connection died silently (no error, just silence).
  • Scale challenge β€” If a user is connected to Server A via WebSocket, and a message is published on Server B β€” you need a pub/sub system (like Redis Pub/Sub) so Server B can notify Server A.
  • Reconnection β€” SSE handles this automatically (with Last-Event-ID). WebSocket reconnection is manual β€” you need to code it yourself.
  • 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/5

    You're building a live cricket score website. Which technology is most appropriate?