Real-Time Systems
WebSockets vs SSE. Scaling stateful connections. When HTTP isn't enough.
When HTTP Isn't Enough
HTTP is pull-based: the client asks, the server responds. But some features require push:
• Live chat — new messages must appear instantly
• Collaborative editing — see others' cursors in real time
• Live notifications — order status updates, likes
• Live dashboards — real-time metrics
• Multiplayer games — game state sync
• Live sports scores — instant score updates
HTTP polling (client asks every second) is wasteful and laggy. Real-time protocols solve this properly.
WebSockets
WebSocket: a persistent, bidirectional, full-duplex TCP connection between client and server.
- Client sends HTTP Upgrade request
- Server agrees → connection upgrades to WebSocket
- Now both sides can send messages anytime
- Connection stays open until explicitly closed
// Server (Node.js with 'ws' library)
const wss = new WebSocketServer({ port: 8080 });
wss.on("connection", (ws) => {
ws.on("message", (data) => {
console.log("received:", data);
ws.send("pong"); // send back
});
ws.send("Welcome!"); // push to client without being asked
});
Use cases: chat, collaborative tools, games, live dashboards.
Scaling challenge: WebSockets are stateful. A user connected to Server A can't receive messages from Server B. Solution: Pub/Sub with Redis — all servers subscribe to a channel, publish to all servers.
Server-Sent Events (SSE)
SSE: server pushes events to client over a regular HTTP connection. One-way (server → client only). Simpler than WebSockets.
// Server
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
setInterval(() => {
res.write(`data: {"price": ${getStockPrice()}}\n\n`);
}, 1000);
// Client
const es = new EventSource("/stream");
es.onmessage = (e) => console.log(JSON.parse(e.data));
Benefits: automatic reconnection built in, works over HTTP/1.1, passes through proxies easily.
Use when: live notifications, activity feeds, live search results, stock tickers.
Use WebSockets when you need bidirectional communication. Use SSE when server → client only.
The Backend from First Principles series is based on what I learnt from Sriniously's YouTube playlist — a thoughtful, framework-agnostic walk through backend engineering. If this material helped you, please go check the original out: youtube.com/@Sriniously. The notes here are my own restatement for revisiting later.