Volume 1

Q020: WebSockets, Server-Sent Events and Polling

Difficulty: SeniorFrequency: HighAnswer time: 7-10 minutes

What Interviewers Want To Evaluate

This question tests whether you can choose the right realtime transport instead of reaching for WebSockets by default. Interviewers want the differences between polling, long polling, Server-Sent Events, and WebSockets, including directionality, connection cost, proxies, retries, ordering, scaling, and product fit.

For senior roles, the strongest answer connects transport choice to reliability, infrastructure, observability, and user expectations.

Short Interview Answer

Polling repeatedly asks the server for updates. Long polling keeps a request open until data is available. Server-Sent Events keep one HTTP connection open for server-to-client events. WebSockets create a bidirectional persistent connection for client and server messages. Use SSE for one-way live feeds, WebSockets for true bidirectional collaboration or low-latency interaction, and polling when simplicity or infrastructure constraints matter more than instant updates.

Detailed Interview Answer

Realtime is not one technology. It is a product requirement with trade-offs. A stock ticker, chat app, collaborative editor, notification badge, build log viewer, and dashboard refresh can all need different transport choices.

Polling is simple and reliable through most networks, but it can waste requests and feel delayed. Long polling reduces empty responses but still uses request lifecycles. SSE is excellent for server-to-client streams because it uses HTTP, reconnects automatically, and has a simple browser API. WebSockets are more flexible because both sides can send messages at any time, but they require more connection lifecycle work and infrastructure support.

Deep Technical Explanation

The decision starts with direction:

client pulls occasionally -> polling
server pushes one-way updates -> SSE
both sides send frequent messages -> WebSocket

Latency, scale, proxies, auth, ordering, backpressure, and reconnect behavior refine the choice.

Polling and Long Polling

Polling sends a request every interval. It is easy to implement, easy to debug, and works with ordinary HTTP infrastructure. The downside is unnecessary traffic and delayed updates.

Long polling sends a request that the server holds until data is ready or a timeout occurs. The client immediately starts the next request after receiving a response. This reduces empty responses but adds server connection management.

Server-Sent Events

SSE uses EventSource to receive a stream of text events from the server. It is one-way: server to client. The browser handles reconnection and can send the last event ID so the server can resume from a known point.

SSE is a good fit for logs, notifications, progress streams, dashboards, build status, and read-only live feeds.

WebSockets

WebSockets start with an HTTP upgrade, then maintain a persistent bidirectional connection. They are useful for chat, multiplayer experiences, collaborative editing, trading terminals, live cursors, and other features where client and server both send frequent messages.

The application must handle connection open, close, reconnect, heartbeat, auth refresh, backpressure, message ordering, and duplicate delivery.

Code Example

const events = new EventSource("/api/events");

events.onmessage = (event) => {
  console.log(JSON.parse(event.data));
};

events.onerror = () => {
  console.log("SSE connection will retry");
};
const socket = new WebSocket("wss://example.com/realtime");

socket.addEventListener("open", () => {
  socket.send(JSON.stringify({ type: "subscribe", roomId: "team-1" }));
});

socket.addEventListener("message", (event) => {
  console.log(JSON.parse(event.data));
});

Architecture Discussion

Realtime systems need a message model. Define event types, payload versions, idempotency, ordering, replay, and permission checks. The browser transport is only one piece.

At scale, persistent connections require infrastructure planning. Load balancers, serverless platforms, connection limits, regional routing, and pub/sub backplanes all matter.

Trade-Offs

Polling is simple but less efficient. SSE is simpler than WebSockets for one-way streams, but it is not bidirectional. WebSockets are powerful but operationally heavier.

The best choice is usually the simplest transport that satisfies the product's latency and directionality requirements.

Common Mistakes

A common mistake is using WebSockets for a notification badge that can refresh every 30 seconds. Another is using polling for collaborative editing where latency and bidirectional updates are central to the experience.

Another mistake is forgetting reconnect logic. Mobile networks drop connections often.

Real Production Story

A build-log page is often better with SSE than WebSockets. The server streams append-only log lines to the browser, the browser reconnects if interrupted, and the client does not need to send frequent messages back.

Enterprise Example

In a customer support console, chat messages may use WebSockets while agent availability metrics use SSE or polling. Different parts of the same product can use different transports.

Performance Discussion

Realtime transports can harm performance if every message triggers expensive React renders. Batch updates, virtualize long lists, debounce derived calculations, and measure CPU cost.

Security Considerations

Authenticate subscriptions, authorize each channel, validate every message, and handle token expiry. Do not assume a connected socket remains authorized forever.

Senior Engineer Perspective

A senior engineer should choose based on directionality, latency, reliability, infrastructure, and failure behavior, not trendiness.

Lead Engineer Perspective

A lead should define connection ownership, retry policy, message schema, auth refresh, observability, and incident playbooks for realtime failures.

Whiteboard Explanation

Draw three lanes: polling requests, an SSE stream, and a WebSocket. Show which direction messages move and where reconnect behavior lives.

Revision Notes

Polling is pull-based. SSE is one-way server push over HTTP. WebSockets are bidirectional persistent connections. Reconnect and message correctness matter as much as the API.

Key Takeaways

Use the simplest transport that satisfies direction, latency, scale, and reliability needs.

Related Topics

  • Fetch lifecycle
  • HTTP caching
  • Event loop
  • Backpressure
  • Pub/sub
  • Observability

Practice Exercise

Choose transports for notifications, build logs, collaborative cursors, stock prices, and analytics dashboard refresh. Explain why each choice fits.

Follow-Up Questions

  1. When is polling enough?
  2. What is long polling?
  3. How is SSE different from WebSockets?
  4. What does EventSource provide?
  5. Why do WebSockets need heartbeat logic?
  6. How do you handle reconnect?
  7. How do you avoid duplicate messages?
  8. What happens when auth expires?
  9. How do proxies affect realtime connections?
  10. How would you scale WebSocket subscriptions?

Things Interviewers Hate Hearing

"Use WebSockets because realtime" is too shallow. Realtime design starts with product directionality, latency, and failure behavior.

How I Would Answer This In A Real Interview

I would compare the options first. Polling is simple pull, SSE is one-way server push, and WebSockets are bidirectional persistent connections. Then I would map examples: logs and notifications often fit SSE, collaborative apps usually need WebSockets, and low-stakes refresh can use polling.

Then I would discuss production details: reconnect, auth refresh, message ordering, duplicate handling, backpressure, and observability.