WebSockets vs long polling (and server-sent events)
Long polling keeps an ordinary HTTP request open until the server has something to send, then the client immediately asks again; WebSockets upgrade one HTTP connection into a persistent two-way channel where either side can send at any time. For real-time features such as chat, live location or collaborative editing, WebSockets are the usual interview answer, server-sent events suit one-way server updates, and long polling remains a solid fallback where persistent connections are blocked.
By Evin JohnPublished 8 min read
1. The problem: the server has news
Plain HTTP is request and response: the client asks, the server answers, and the server cannot speak first. Many products need the opposite direction. A new chat message, a driver moving on a map, a teammate typing in a shared document or a price changing on a trading screen all start on the server. The techniques on this page are different ways to get that news to the client quickly without wasting work.
2. Why interviewers ask
Prompts like WhatsApp, Uber, a collaborative editor or a notification system all have a real-time path, and "we use WebSockets" is where many candidates stop. The interviewer then asks how a message for user B finds the server that holds B's connection, how many connections one server holds, and what happens when a server restarts. Choosing the transport takes one sentence; the follow-ups are where the round is decided.
3. The four techniques
| Technique | How it works | Latency of an update | Main cost |
|---|---|---|---|
| Short polling | The client sends a request every few seconds; the server answers at once, usually with nothing new | Up to one polling interval | Most requests are wasted; load grows with users times poll rate |
| Long polling | The client sends a request; the server holds it open until there is news or a timeout (often tens of seconds), then the client asks again | Near immediate | One held request per client, plus a new request after every message |
| Server-sent events (SSE) | The client opens one HTTP response that never ends; the server writes events into it as text lines | Near immediate | One direction only (server to client); client messages go over normal requests |
| WebSockets | An HTTP request asks to upgrade; after the handshake the TCP connection carries framed messages both ways | Near immediate, both directions | Stateful connections that every layer must support and the servers must manage |
- Long polling
- Request held open
- Message 1 returned; request ends
- New request held open
- Message 2 returned
- WebSocket
- Upgrade request, 101 reply
- Message 1 pushed
- Client sends a message up
- Message 2 pushed
Notes on each
- Long polling works anywhere HTTP works, through any proxy, with no special server support. Messages that arrive while the client is reconnecting must be held, so the client sends the ID of the last message it saw and the server returns everything after it.
- Server-sent events are part of the HTML standard (the EventSource API), with automatic reconnection and a Last-Event-ID header so the server can resume. On HTTP/1.1, browsers cap open connections per site at a small number (six in common browsers), which several SSE streams can exhaust; HTTP/2 multiplexing removes that limit in practice.
- WebSockets (RFC 6455) have low per-message overhead (a header of a few bytes) and suit high-frequency, two-way traffic such as games, editors and chat. Every proxy and load balancer on the path must allow the upgrade and long-lived connections.
4. Choosing
| Feature | Good choice | Why |
|---|---|---|
| Chat, multiplayer, collaborative editing | WebSockets | Frequent messages in both directions |
| Live scores, dashboards, progress of a job, AI text streaming | Server-sent events | One-way updates; plain HTTP, simple reconnection |
| Rare updates, such as a report finishing | Short polling every 10 to 30 seconds, or a push notification | Simplest; a persistent connection would sit idle |
| Restrictive corporate networks or very old clients | Long polling as a fallback | Looks like normal requests to every proxy |
| App in the background on a phone | Mobile push notifications | The operating system closes background sockets; push services wake the app |
Many real-time libraries start with WebSockets and fall back to long polling automatically when the upgrade fails, so "WebSockets with a long-polling fallback" is a reasonable sentence in an interview.
5. Sizing the connection tier
concurrent connected users: 10 million
connections per gateway server: 100,000 (assumed, after load testing)
gateway servers: 10M / 100k = 100, plus headroom for failures and deploys
memory per idle connection: about 20 KB (buffers and session state, assumed)
total connection memory: 10M x 20 KB = about 200 GB across the tier
heartbeat every 30 s: 10M / 30 = about 330,000 small frames a second
same users on long polling, 30 s hold: about 330,000 requests a second when idle
same users on short polling every 5 s: 10M / 5 = 2 million requests a secondThe arithmetic shows why short polling stops scaling: idle users still cost requests. A persistent connection is cheap while idle but must be tracked, and the gateway count is set by concurrent connections rather than by requests a second. Watch file descriptor limits and memory per connection on each gateway, not CPU alone.
6. Routing a message to the right connection
With 100 gateways, user A's message for user B arrives at A's gateway, while B is connected to some other one. Three common ways to bridge the gap:
- Connection registry. When B connects, the gateway records "B is on gateway 37" in a fast store with a time-to-live refreshed by heartbeats. The chat service looks up B and sends the message to gateway 37 directly.
- Pub/sub per user or per room. Each gateway subscribes to channels for the users or rooms it holds. Publishers send to the channel, and only subscribed gateways receive it. Simple, but the broker must handle a channel per active user or room.
- Partitioned gateways. Route each user to a gateway chosen by hashing the user ID, so senders can compute the destination. Rebalancing on scale-out moves connections.
Whichever you choose, store messages durably before delivery, so a user who is offline or between connections gets them later from history instead of losing them. The real-time path is an optimization on top of a store, not the system of record.
- Clients
- Sender app
- Recipient app
- Edge
- Load balancer (upgrade allowed, long idle timeout)
- Gateway servers holding connections
- Services
- Chat service
- Connection registry (user to gateway)
- Pub/sub layer
- Storage and fallback
- Message store
- Mobile push notifications
7. Keeping connections healthy
- Heartbeats. Send a ping (WebSockets have ping and pong frames) every 20 to 60 seconds. It detects dead peers and keeps load balancers and NAT devices from closing a connection they think is idle.
- Reconnection with backoff and jitter. When a gateway dies, all its clients reconnect at once. Spreading retries randomly over a growing window stops them from overwhelming the remaining servers.
- Resume, do not restart. The client sends the last message or event ID it saw; the server replays what it missed from the store.
- Draining on deploys. Stop sending new connections to a gateway, tell clients to reconnect elsewhere in small batches, then restart. Rolling restarts of a stateful tier take longer than for stateless servers.
- Authentication. Check the token on the upgrade request and re-check or expire long-lived sessions, since a connection can outlive the token that opened it.
function reconnectDelay(attempt, baseMs = 500, capMs = 30_000, random = Math.random) {
const ceiling = Math.min(capMs, baseMs * 2 ** attempt);
return Math.floor(random() * ceiling); // anywhere from 0 up to the ceiling
}
const ceilings = [0, 1, 2, 3, 4, 5, 6, 7].map((a) => Math.min(30_000, 500 * 2 ** a));
console.log(ceilings.join(", ")); // 500, 1000, 2000, 4000, 8000, 16000, 30000, 30000
console.log(reconnectDelay(3, 500, 30_000, () => 0.5)); // 20008. Interview questions on real-time delivery
| Question | What a full answer includes |
|---|---|
| WebSockets or long polling for chat? | WebSockets for two-way, frequent traffic, with long polling as a fallback |
| When is SSE better than WebSockets? | One-way server updates over plain HTTP, with built-in reconnect and resume |
| How does a message reach the server holding the recipient's socket? | Registry lookup or pub/sub, after storing the message |
| How many servers for 10 million concurrent users? | Connections per server from a load test, then divide, then add headroom |
| A gateway crashes. What happens? | Clients reconnect with jittered backoff to other gateways and resume from their last ID |
| How do you deploy a new version of the gateway? | Drain gradually and ask clients to reconnect in batches |
| What does the load balancer need? | Upgrade support, long idle timeouts, and balancing that spreads new connections evenly |
| The phone app is in the background. Now what? | Mobile push notifications; the socket will be closed by the operating system |
9. Mistakes to avoid
- Stopping at "WebSockets". Explain routing, registry and reconnection.
- Treating the socket as storage. Write messages to a store first; the connection may be gone a second later.
- Short polling at scale. Idle clients still cost requests every interval.
- Forgetting the load balancer's idle timeout. Without heartbeats, quiet connections get cut.
- Synchronized reconnects. No jitter turns one gateway failure into a wave that knocks over the rest.
10. How to talk about it in the interview
- Pick the transport per feature, with one reason each.
- Size the gateway tier by concurrent connections.
- Draw the path from sender to recipient's gateway, including where the message is stored.
- Cover heartbeats, reconnect with jitter and resume before the interviewer does.
Fictional example
- Interviewer
- Customers watch their courier move on a map. How do updates reach the app?
- Candidate
- Updates only flow from server to customer, about one every few seconds, so I would use server-sent events from a tracking gateway. The customer app opens one stream per active order.
- Interviewer
- Why not WebSockets?
- Candidate
- The customer never sends anything on this screen. SSE is plain HTTP, reconnects on its own and sends the last event ID, so after a dropped connection the gateway replays the latest position. The courier app is different: it sends a location every few seconds, so it posts them over normal HTTPS requests in batches.
- Interviewer
- And when the customer closes the app?
- Candidate
- The stream ends. A push notification tells them when the courier is two minutes away.
Practicing real-time designs with Natively
Real-time questions reward a calm walk from client to gateway to store, and that flow is easier to rehearse aloud than in your head. Run a mock with a friend and let Natively transcribe it on Mac or Windows; mid-session, one shortcut drafts an answer to the question just asked, and another suggests follow-ups you could face, such as the deploy or reconnect questions. Ask for a diagram of the gateway path and it draws one in the answer. The transcript afterwards shows whether you sized the connection tier or skipped it.
Questions people ask
What is the difference between WebSockets and long polling?
Long polling sends an ordinary HTTP request that the server holds open until it has news or times out, after which the client immediately sends another. A WebSocket upgrades one HTTP connection into a persistent channel where both sides can send messages at any time. WebSockets have less overhead per message and suit two-way traffic; long polling works through any proxy and makes a good fallback.
When should I use server-sent events instead of WebSockets?
Use server-sent events when updates only flow from server to client, such as live scores, job progress or streamed text. They run over plain HTTP, reconnect automatically and resume with a Last-Event-ID header. Choose WebSockets when the client also sends frequent messages, as in chat or collaborative editing.
How do WebSockets scale to millions of users?
A tier of gateway servers holds the connections, sized by concurrent connections per server from load tests. A registry or a pub/sub layer routes each message to the gateway holding the recipient's connection, messages are stored before delivery, and clients reconnect with jittered backoff and resume from their last message ID.
Is long polling still used?
Yes, mostly as a fallback when WebSocket upgrades are blocked by proxies or firewalls, and in simple systems with modest traffic. Many real-time libraries try WebSockets first and fall back to long polling automatically.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
