Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
Don't ask.
Be told.
HTTP has one rhythm: the client asks, the server answers, the line goes dead. That's fine for loading a page — and hopeless for anything live. To show a new chat message or a moving cursor, the old trick is to poll: ask "anything new?" over and over, mostly to hear "no." It's laggy and wasteful, and the math says exactly how much. WebSockets flip it: keep one line open, and let the server push the instant something happens. This handbook is the arithmetic of why "be told" beats "keep asking."
HTTP can't push
Ordinary HTTP is request-response: the client initiates, the server replies, and the exchange is over. The server has no way to speak first — it can't tap the client on the shoulder and say "something changed." That's a perfect fit for fetching a document, and a fundamental mismatch for anything that updates on the server's schedule: a message arriving, a price ticking, another user's cursor moving.
So to build "live" on top of a protocol that can't push, developers reach for a workaround — have the client ask, repeatedly, and hope to catch news soon after it happens. That's polling, and it works, sort of. But it's a simulation of real-time built out of not-real-time parts, and it pays for the illusion in latency and wasted work. Quantifying that cost is the cleanest way to see why a different primitive — a connection the server can push over — is the real answer.
Polling makes the client wait on average half the poll interval and waste a request whenever nothing changed; a WebSocket keeps a line open so the server pushes instantly, at one-way network latency and zero waste.
The cost of polling
Polling means the client asks "anything new?" every fixed interval. It has two costs, and both are quantifiable. The first is latency: an event can happen at any moment within the interval, so on average the client doesn't learn about it until half the interval has passed. Poll every 10 seconds and your users feel about 5 seconds of staleness on average — an eternity for a chat.
The second is waste. Most polls return nothing — you asked, there was no news — so you're making a stream of requests just to hear "no," burning bandwidth, server CPU, and battery. And the two costs are in tension: to cut the latency you shorten the interval, but that multiplies the number of empty polls. Poll every second instead of every ten and you've traded 5 seconds of lag for ten times the wasted requests. There's no setting of the dial that gives you both low latency and low waste, because you're fundamentally guessing when to ask. The fix isn't a better interval — it's not guessing at all.
A line left open
A WebSocket changes the primitive. After a quick HTTP handshake that "upgrades" the connection, the client and server hold open a single, persistent, full-duplex TCP connection — either side can send a message at any time, for as long as the connection lives. Now the server doesn't wait to be asked; it pushes the instant an event occurs.
Both costs of polling vanish. Latency drops from "half a poll interval" to "one network hop" — tens of milliseconds, effectively the moment it happens. And there are no wasted requests: nothing crosses the wire until there's actually something to send. That's the whole appeal — a WebSocket turns "check constantly, usually find nothing" into "be notified precisely when it matters." The next section makes the difference exact.
The latency math
Polling with interval T: an event is equally likely anywhere in the window, so the expected wait to learn of it is half the interval, and the requests that return nothing are all the polls minus the ones that caught an event:
T=10s → 5s average staleness; over 100s that's 10 polls for maybe 2 events → 8 empty requests. Shrink T and latency falls but waste climbs.
A WebSocket push arrives at roughly the one-way network latency, independent of any interval, with no empty requests — so it clears a real-time perceptual threshold that polling can't:
50 ms push clears a 500 ms "feels live" bar; a 10 s poll's 5 s average doesn't. The runnable version below computes poll latency, wasted requests, and the push comparison.
Poll vs push, in numbers
The push-vs-poll difference is arithmetic. Polling's average latency is half the interval, because an event lands uniformly in the window — so a 10-second poll means ~5 seconds of staleness. It also wastes a request every time nothing changed: total polls minus real events. A WebSocket push arrives at the one-way network time regardless of interval, and sends nothing when there's no news — so it clears a real-time threshold a slow poll can't. Shorter polls cut latency but multiply the waste, the trade you can't win. Change the interval, event count, or network time and compare.
When to use what
Real-time isn't free, so match the transport to the need:
| Transport | Best for |
|---|---|
| Request-response | One-off fetches; data that only changes when the user acts. Simplest, no persistent state. |
| Polling | Infrequent updates where a few seconds of staleness is fine and simplicity matters. |
| Server-Sent Events | Frequent server→client push, one-directional (live feeds, token streaming) — simpler than WebSockets. |
| WebSocket | Low-latency, bidirectional, frequent messaging: chat, collaboration, live cursors, games. |
| WebRTC | Peer-to-peer, ultra-low-latency media (audio/video) — a different tool for a different job. |
The honest default is: don't reach for WebSockets unless you need them. A persistent connection costs server resources per client, complicates load balancing (a socket is stateful; a stateless request isn't), and needs reconnection and heartbeat machinery. For streaming from the server only — an LLM's tokens, a live log — SSE is lighter and often enough. Save WebSockets for genuinely interactive, bidirectional, low-latency features, where the poll math is unacceptable and the two-way channel earns its keep.
Pitfalls
The operational reality is that a persistent connection is stateful, and state is what makes scaling hard. Each open socket pins a bit of memory and a connection slot, so a million concurrent users is a million live connections to hold; load balancers must keep a client stuck to the server that holds its socket (or you need a shared pub/sub layer to fan out messages across servers). Plan for that from the start, or your real-time feature falls over at scale. And connections drop — networks are flaky, phones sleep — so you need automatic reconnection, heartbeats/pings to detect dead connections, and a way to catch up on messages missed while disconnected.
Two more. Reaching for WebSockets when SSE or polling would do: bidirectional, low-latency is powerful but heavy, and using it for infrequent one-way updates is over-engineering. And treating socket messages as trusted: a WebSocket is an open door into your server, so authenticate the connection, authorize every message, and rate-limit — the same discipline as any endpoint. Used where it fits, a WebSocket is the difference between an app that feels alive and one that feels like it's refreshing behind your back. The rule is simple: when staleness is unacceptable and updates are frequent and two-way, stop asking — open a line and be told.
A WebSocket is stateful, which is the whole scaling challenge: each client pins a connection, so you need sticky routing or a shared pub/sub to fan messages across servers, plus reconnection, heartbeats, and missed-message recovery. Don't adopt it for infrequent one-way updates SSE or polling would handle more simply.
Worked example: 10,000 chat users, four ways
Say a chat app has 10,000 users online, and each receives about one message a minute. Assume each poll or long-poll round trip carries about 800 bytes of HTTP headers (cookies often make it more), and that messages are short, under 125 bytes. These inputs are illustrative. Trace one minute of traffic for each transport.
| Transport | Requests or frames per minute | Wasted | Header bytes per minute | Average delay |
|---|---|---|---|---|
| Poll every 5 s | 60 ÷ 5 × 10,000 = 120,000 requests (2,000/s) | 120,000 − 10,000 = 110,000 empty (91.7%) | 120,000 × 800 B = 96 MB | 5 ÷ 2 = 2.5 s |
| Poll every 1 s | 600,000 requests (10,000/s) | 590,000 empty (98.3%) | 480 MB | 0.5 s |
| Long-poll, 30 s hold | about 2 per user: one ended by the message, one by the timeout = 20,000 | about half end with no news | 20,000 × 800 B = 16 MB | one network hop, plus a re-request gap if two messages arrive close together |
| WebSocket, data | 10,000 pushed frames (about 167/s) | none | 10,000 × 2 B = 20 KB of framing | one network hop, say 50 ms |
| WebSocket, 30 s ping/pong | 20,000 pings and 20,000 pongs | keep-alive, not news | 20,000 × (2 + 6) B = 160 KB | not on the message path |
| WebSocket, memory | 10,000 open sockets held all minute | — | say 20 KB per socket = 200 MB of server RAM | paid even when nobody speaks |
Compare rows 1 and 4. The 5-second poll spends 96 MB a minute on headers, and 11 of every 12 requests return nothing. The WebSocket spends 180 KB on framing and keep-alives combined, about 530 times less, and delivers 50 times faster. Row 2 is the trap from the latency math: going from 5 s to 1 s polls cuts the delay by 2 s and multiplies the request load by five. Row 6 is the bill the poll never sends. A poll costs nothing between requests, but a socket holds memory and a connection slot for as long as the user is online. That is why the pitfalls section talks about scaling state, not bandwidth. Note also that all of these counts ignore the TCP and IP packet headers, which every option pays. They also assume every message is caught by its own poll. A longer message, 126 to 65,535 bytes, takes a 4-byte header instead of 2, which changes none of these conclusions.
Check yourself
Each answer uses the numbers or rules above.
An internal dashboard refreshes figures that change about every 30 seconds, and nobody minds 15 seconds of staleness. Which transport, and why?
Plain polling, say every 30 s. The average delay is 30 ÷ 2 = 15 s, which is inside the tolerance. Most polls will find new data, so little is wasted. A WebSocket would add a stateful connection, sticky routing and reconnect logic to save nothing a user can feel. Polling also passes through every proxy and needs no reconnect code, because each request stands alone. The page’s rule is to reach for push only when staleness is unacceptable and updates are frequent.
You stream an LLM’s answer token by token to a browser. The user sends one prompt, then only reads. WebSocket or Server-Sent Events?
SSE. The traffic is one-way, server to client, which is exactly what SSE is for. It runs over an ordinary HTTP response, so proxies, auth and load balancers treat it like any request. The browser’s EventSource reconnects on its own and sends the last event id it saw, so the server can resume. The prompt itself goes up as a normal POST. A WebSocket’s two-way channel would go unused.
Your chat server works on one machine. You add two more behind a round-robin load balancer. Alice’s socket is on server 1 and Bob’s on server 2. What happens when Alice sends Bob a message?
Server 1 receives it and looks for Bob among its own sockets. He is not there, so the message is lost, with no error. Each socket lives on exactly one server. The fix is a shared pub/sub layer: server 1 publishes to Bob’s channel, and whichever server holds Bob’s socket is subscribed and pushes it. Sticky routing alone does not solve this, because Alice and Bob are still on different machines. Redis pub/sub, NATS or a managed message broker can play that role; the servers themselves stay interchangeable.
A phone goes into a tunnel for 20 seconds and comes back. The socket looks open on the client, but no messages arrive. What went wrong, and what two mechanisms fix it?
The connection died silently. A dropped network sends no close frame, and TCP does not notice a dead peer while nothing is being sent. NAT devices and proxies also drop idle connections without telling either side. Heartbeats (ping/pong on a timer) detect the dead line so the client reconnects. Catch-up is the second half: the client sends the id of the last message it received, and the server replays anything newer from a buffer or the database. Without catch-up, every reconnect silently loses whatever was sent during the gap.
Quick answers
What is a WebSocket?
A persistent, full-duplex connection where either side can send at any time, so the server can push updates instantly — the basis of real-time features.
Why is polling inefficient?
You wait on average half the poll interval to learn of an event, and most polls return nothing — so it's both laggy and wasteful.
How do WebSockets cut latency?
The line is already open and the server pushes, so latency is one network hop (tens of ms) instead of half a poll interval, with no empty requests.
When not to use them?
When updates are infrequent or one-way — request-response, polling, or SSE are simpler and cheaper than a stateful persistent connection.
WebSockets: keep the line open
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Handbooks
- The Kafka HandbookApache Kafka as a distributed append-only log, not a queue — topics, partitions and offsets, producers, consumers and consumer groups, per-key ordering, replication and ISR, delivery semantics (at-least-once and exactly-once), retention vs log compaction, and when Kafka beats a message queue.Read →
- Kafka vs RabbitMQThey both "move messages", which is exactly why teams pick the wrong one. Kafka is a durable, replayable log where consumers track their own offset; RabbitMQ is a smart broker that routes each message and deletes it on ack. The remember-vs-forget core difference, throughput and ordering trade-offs, and how to choose.Read →
- Kafka vs KinesisSame partitioned-log model underneath, different operational surface: Kafka is self-run and portable with a huge ecosystem; Kinesis is fully AWS-managed with a hard per-shard throughput ceiling. Retention, cost model, and the lock-in trade-off.Read →
- REST vs Webhooks vs SSEThree ways client and server move data, split by who exposes an endpoint and whether the connection stays open: REST pulls, webhooks flip who runs the server, SSE keeps one connection open for a live push. How real systems run all three at once.Read →
- Streaming vs BatchBatch processes on a schedule; streaming reacts per-event. The real engineering cost of streaming isn’t speed, it’s correctness under disorder — event time vs processing time, watermarks, exactly-once semantics. The Lambda and Kappa architectures that combine both.Read →
- The FDE Take-Home PlaybookTake-homes are the centre of gravity in modern FDE loops and they are graded on judgement, not volume. The five-phase method with time budgets, what graders actually weight, a deliberately ambiguous five-hour practice spec, a 30-point self-scoring rubric, and how to prepare the video defence.Read →