How it works
With long polling, a client sends an HTTP request that the server holds until an update arrives or a timeout expires. After receiving the response, the client immediately opens another request, usually carrying a cursor for the last update it received. Unlike periodic polling, an update can be returned as soon as it becomes available, but every completed response requires another request.
SSE keeps an HTTP response open and streams UTF-8 events using the text/event-stream content type. It is server-to-client only; the client can still send commands through ordinary HTTP requests. For example, an order-tracking page can receive status changes over SSE while submitting a cancellation through POST.
WebSockets establish a persistent, full-duplex connection over which either side can send text or binary messages. They fit frequent two-way traffic such as chat messages, editing operations, and presence updates. Messages are ordered on a live connection, but reconnects, multiple producers, and application retries still require explicit ordering and deduplication rules.
At scale, clients connect through a load balancer to connection gateways. A subscription registry or routing layer directs backend updates to the gateways holding the relevant connections, and each gateway fans them out locally. An established connection stays on its gateway, but reconnecting clients can land elsewhere; durable history and recovery state should not exist only in gateway memory.
Define recovery independently of the transport. Give durable events IDs or sequence numbers, let clients resume from a cursor, and provide a snapshot when retained history no longer covers the gap. Browser EventSource automatically reconnects and can send Last-Event-ID, but the server must implement replay; WebSocket reconnect and resume behavior generally belongs in application code.
All three approaches need timeout and resource policies. Use heartbeats appropriate to proxy idle timeouts, disable response buffering for SSE, and bound each client's outgoing queue. A slow location viewer can receive only the newest position, while a slow chat client may need to disconnect and recover missing messages from durable history.
A worked example
SSE for live delivery tracking
Suppose 100,000 customers are watching active deliveries, and each delivery produces one location update every five seconds. That creates 20,000 outbound updates per second before retries. SSE fits because customers mainly receive updates; cancellation and other commands use HTTP requests. At an assumed 300 bytes per event, payload traffic is about 6 MB/s, excluding protocol overhead. Gateways subscribe only to deliveries their clients may view. Each event carries a delivery ID and increasing location version. After reconnecting, a client receives the latest snapshot and ignores older versions. Slow-client queues retain only the newest location, while important order-state transitions remain recoverable from durable history.
Trade-offs to say out loud
- Traffic direction versus protocol complexity
- SSE plus HTTP requests often suffices for server-driven updates, while WebSockets provide a shared bidirectional channel at the cost of application-level message, reconnect, and acknowledgment protocols.
- Request churn versus persistent connection cost
- Long polling creates a new request after each response, while SSE and WebSockets avoid that churn but still consume connection state, buffers, file descriptors, and heartbeat traffic.
- Infrastructure compatibility
- Long polling uses ordinary HTTP exchanges, SSE needs unbuffered streaming, and WebSockets need compatible proxy support; all require deliberate timeout configuration.
- Convenient browser behavior versus constraints
- Native EventSource offers automatic reconnects but no arbitrary request headers, and SSE over HTTP/1.1 can encounter browser per-origin connection limits that differ under HTTP/2.
- Freshness versus completeness
- Coalescing updates limits bandwidth and lag for latest-value data, but messages or editing operations require replay or another recovery path rather than silent dropping.
- Low delivery latency versus delivery guarantees
- A working connection can deliver updates quickly, but durable acceptance, client processing, and recovery after disconnects require storage, cursors, and application acknowledgments where needed.
When to reach for it
- Choose WebSockets when both client and server send frequent, latency-sensitive messages, as in collaborative editing or interactive chat.
- Choose SSE when updates mostly flow from server to browser, such as live prices, progress events, or order status, and HTTP requests can handle client commands.
- Choose long polling when streaming support is constrained or updates are sparse enough that repeated requests are an acceptable cost.
- Consider these transports when freshness requirements make periodic polling too slow or too wasteful, but first establish the required update rate and latency.
How to bring it up in the interview
- Start with direction, frequency, freshness, and recovery requirements rather than naming WebSockets immediately; explain why SSE plus POST or long polling would or would not meet them.
- Separate the connection layer from the durable data path: show where an update is committed, how it reaches a gateway, and how a client recovers if live delivery fails.
- Estimate concurrent connections, messages per second, payload bandwidth, and per-connection memory; interviewers often probe hot-topic fanout and whether slow clients can exhaust gateway resources.
- Describe gateway failure and rolling deployment behavior: drain connections, reconnect with backoff and jitter, and resume on another gateway without relying on sticky sessions for correctness.
- Explain authentication and subscription authorization, including WebSocket Origin validation for browser clients, credential expiry, and access revocation during an open connection; interviewers may ask whether a formerly authorized client can keep receiving private updates.
Common mistakes
- Saying WebSockets guarantee exactly-once delivery or preserve application ordering across reconnects; neither follows from the transport.
- Calling long polling periodic polling, or assuming its latency must equal a fixed polling interval even while a request is waiting.
- Choosing WebSockets for every real-time feature without considering SSE plus ordinary HTTP requests for one-way streams.
- Using sticky sessions as the recovery strategy instead of maintaining replayable history or a recoverable snapshot outside the connection server.
- Keeping unlimited outgoing queues or replaying every stale location or price update to a slow client instead of defining bounded lag and recovery behavior.
Where it comes up
Interview questions where websockets, sse and long polling is part of a strong answer, and why.
- Design a chat app like WhatsAppBidirectional messaging requires connection routing, reconnect recovery, and a clear distinction between durable message acceptance and live delivery.
- Design Google DocsEditing operations and cursor updates need low-latency bidirectional delivery with different durability and slow-client policies.
- Design a real-time stock price feedPrice streaming centers on subscription fanout, latest-value conflation, and reconnects that do not roll displayed prices backward.
- Design Facebook live commentsDelivering comments to large audiences requires a deliberate streaming transport, bounded fanout queues, and cursor-based reconnect behavior.
- Design an ETA and live location sharing serviceLive tracking requires fresh location delivery despite reconnects and slow networks, with trip-scoped subscription authorization.
- Design Dropbox or Google DriveReliable change discovery needs a notification or long-polling channel backed by durable cursors so disconnected clients can catch up.
- Design a stock trading app like RobinhoodLive quote delivery requires choosing a streaming channel and isolating slow subscribers from the price distribution path.
Questions people ask
What is the difference between WebSockets and long polling?
WebSockets keep a full-duplex connection open for messages in either direction. Long polling holds an HTTP request until an update or timeout, then requires the client to issue another request. Both can deliver low-latency updates, but long polling adds request churn and WebSockets require explicit connection lifecycle handling.
When should I use Server-Sent Events instead of WebSockets?
Use SSE when the main requirement is streaming text updates from the server to a browser and client commands can use ordinary HTTP requests. WebSockets are a better fit for frequent bidirectional messages or binary payloads. SSE's automatic browser reconnect does not remove the need for server-side replay or snapshot recovery.
How do you scale WebSockets or SSE across multiple servers?
Distribute connections across gateways and route each update to gateways with interested clients, using a subscription registry or messaging layer. Budget for connection memory, fanout bandwidth, and bounded outgoing queues. Keep recovery state outside individual gateways so reconnects can land anywhere, and use backoff with jitter to limit reconnect storms.