Interview frequency: …
Short answer
WebSockets provide full-duplex communication over one persistent TCP connection. SSE provides a one-way stream from server to client over standard HTTP. Long Polling keeps HTTP requests open until new data is available.
Explanation
For fast two-way communication, such as group chat rooms, multiplayer games, or live stock exchanges, WebSockets are best because they remove repeated HTTP headers. For server-to-client streaming only, such as currency rates, app notifications, or ChatGPT text streaming, SSE is simple, supports automatic reconnection, and easily passes through HTTP firewalls and proxies.
Code example
// SSE: one-way server → client stream over plain HTTP
app.get("/events", (req, res) => {
res.set({ "Content-Type": "text/event-stream", "Cache-Control": "no-cache" });
const timer = setInterval(() => res.write(`data: ${Date.now()}\n\n`), 1000);
req.on("close", () => clearInterval(timer));
});
// WebSocket: full-duplex over a single upgraded TCP connection
const ws = new WebSocket("wss://example.com/chat");
ws.onopen = () => ws.send("hello");
ws.onmessage = (event) => console.log(event.data);
// Long polling: the server holds the request until there is news, then the client asks again
async function poll(since = 0) {
const response = await fetch(`/updates?since=${since}`);
const { items, last } = await response.json();
items.forEach(handle);
return poll(last);
}Common mistakes
- Using WebSockets to stream simple one-way notifications, unnecessarily adding handshake maintenance, server management, and proxy blocking complexity.