Ordinary web requests are pull: the client asks, the server answers, and the connection ends. If the server has news (a new chat message, a price change, a driver's new location), it cannot tell the client unless the client asks again.
Real-time communication techniques solve this: short polling, long polling, Server-Sent Events and WebSockets. Each trades simplicity against efficiency. Picking the right one, and knowing how to scale it to millions of open connections, is a standard part of chat, notification, collaboration and live-tracking designs.
Detailed Notes
What is it?
Recall from the clients-and-servers lesson that HTTP is request/response: the client always starts. Real-time means the user sees new data within about a second, without refreshing. Four techniques, from simplest to most capable:
Short polling: the client asks "anything new?" every few seconds, regardless of the answer.
Long polling: the client asks, and the server holds the request open until there is news (or about 30 seconds pass), then answers; the client immediately asks again.
Server-Sent Events (SSE): the client opens one HTTP connection and the server keeps streaming events down it. One direction only: server to client.
WebSocket: one persistent TCP connection upgraded from HTTP that carries messages in both directions at any time, with very small framing overhead.
Why do we need it?
Short polling looks harmless until you do the arithmetic.
text
1,000,000 users, each polls every 5 seconds
Requests per second = 1,000,000 / 5 = 200,000 requests/s
Fraction with news = say 2%
Useful responses = 4,000/s
Wasted requests = 196,000/s (98%)
Average delay to see an update = 2.5 seconds (half the interval)
Two hundred thousand requests per second, 98% empty, each carrying HTTP headers of around 500 bytes, and users still wait up to 5 seconds. Dropping the interval to 1 second improves the delay but multiplies the load by five. A persistent connection delivers the update in tens of milliseconds and sends nothing when there is nothing to say.
How does it work?
Polling versus Long Polling versus WebSocketComparison
Short polling
ask every N seconds
1
Client: any news?
every 5 s
2
Server answers at once
usually 'no'
3
Client waits and repeats
Stateless and trivial
Works everywhere
Mostly empty requests
Delay up to the interval
Rare updates, tolerant of delay
Long polling
server holds the request
1
Client sends a request
2
Server waits for news
up to about 30 s
3
Server replies, client reconnects
Near-instant delivery
Passes any proxy
Reconnect per message
Holds a slot per client
Fallback when sockets are blocked
WebSocket
one two-way connection
1
HTTP upgrade handshake
status 101
2
Connection stays open
3
Either side sends any time
tiny frames
Lowest latency and overhead
True two-way
Stateful connections
Harder to scale and deploy
Chat, games, collaboration
Key point. Polling pays for every question; WebSocket pays for connections and only talks when there is news.
Same goal, delivering news to the client, with very different request patterns.
Short polling
Simple, works everywhere, stateless: any server can answer any request, so a load balancer needs no special setup. Use it when updates are rare and delay is acceptable (a job status check every 10 seconds).
Long polling
The server parks the request until data arrives, then responds; the client reconnects. Delay is near-instant and it works through every proxy and firewall. Costs: each waiting client holds a connection and a server thread or slot, there is a reconnect after every message, and ordering and missed messages between reconnects need care (give each message an ID and let the client say "send everything after ID 1057"). It was the standard before WebSockets and is still a fine fallback.
Server-Sent Events
A plain HTTP response with Content-Type: text/event-stream that never ends. The browser reconnects automatically and can resume using a last-event ID. It is the simplest correct choice for one-way streams: live scores, stock tickers, notification feeds, progress bars. It cannot send client-to-server messages (use a normal HTTP request for those).
WebSocket
The client sends a normal HTTP request with Upgrade: websocket. If the server agrees (status 101), the same connection stops being HTTP and becomes a full-duplex channel: either side can send a message at any moment.
Best for chat, multiplayer games, collaborative editing and live trading, where both sides talk frequently. Costs: connections are stateful, meaning a specific server holds the specific connection, so scaling needs more thought than for stateless APIs.
Scaling WebSockets
One server can hold roughly 50,000 to 100,000 idle connections (memory per connection is about 10 KB, so 100,000 connections are about 1 GB, plus the kernel limits that must be tuned).
text
10 million concurrent users / 100,000 per server = 100 gateway servers
The challenge: user A is connected to gateway 7 and user B to gateway 42. How does A's message reach B?
A gateway (WebSocket server) only manages connections. It does not contain business logic.
A presence / session store (a fast key-value store such as Redis) records "user B is on gateway 42".
The chat service looks up B's gateway and forwards the message there, or publishes it to a pub/sub channel that gateway 42 subscribes to (see the queues lesson). Gateway 42 writes it to B's socket.
If B is offline, the message is stored and sent as a mobile push notification instead.
Delivering a Message Across WebSocket GatewaysArchitecture
Key point. Keep gateways dumb. The session store answers 'where is user B?' and pub/sub carries the message there.
Gateways hold sockets; the session store and pub/sub find and reach the right one.
Operational details interviewers like to hear:
Heartbeats: the client and server exchange a tiny ping every 20 to 30 seconds. If one is missed the connection is considered dead, which also keeps NAT devices and load balancers from silently dropping idle connections.
Reconnect with backoff and jitter: when a gateway restarts, 100,000 clients reconnect at once. Randomized delays (see the retries lesson) avoid a reconnect storm.
Missed messages: persist messages with sequence numbers; on reconnect the client sends its last sequence number and receives what it missed.
Load balancing: use an L4 or an L7 load balancer that supports WebSocket, and drain connections gradually during deployments.
Fallback: if WebSockets are blocked by a corporate proxy, fall back to long polling.
Interview tip. Do not default to WebSockets for everything. If the data flows one way, SSE is simpler. If updates are rare, polling is cheaper to operate. Naming the cheaper option and why it is not enough is what impresses.
Real-world example
A ride-hailing app shows the driver moving on the map. The driver's phone sends location every 4 seconds over HTTP or a socket; the rider's app only receives position updates, so SSE or a WebSocket pushes them. Chat between rider and driver is two-way, so it uses a WebSocket. The job status "searching for driver" screen can simply poll every 3 seconds.
System design example
Design live comments on a video streamed to 2 million viewers, 1% of whom comment each minute.
text
2,000,000 viewers / 100,000 per gateway = 20 gateways (plan 30 for headroom)
Comments: 2,000,000 x 1% = 20,000 per minute = about 330 per second inbound
Fan-out: each comment goes to all 2,000,000 viewers
330 x 2,000,000 = 660,000,000 deliveries/s
Delivering every comment to everyone is impossible (660 million messages per second). So sample: show each viewer about 5 comments per second, batched into one frame per second. Viewers receive a one-way stream, so SSE is enough. Comments are published to a pub/sub topic, every gateway subscribes, and each gateway pushes the batch to its own viewers. Writing comments to a database is done asynchronously through a queue.
Interview discussion. "For two-way low-latency messaging like chat I'd use WebSockets behind gateways that only hold connections. A session store maps users to gateways, a pub/sub layer routes messages between gateways, and offline users get a push notification. For one-way updates like scores I'd use SSE, since it's simpler and reconnects automatically."
Trade-off thinking. Polling is stateless and trivial but wasteful and slow. WebSockets are efficient and instant but stateful: they complicate deployments, load balancing and failover. SSE sits in the middle for one-way data. Choose the simplest mechanism that meets the latency requirement.
Key interview takeaway
Match the technique to the data flow: polling for rare updates, long polling as a compatible fallback, SSE for one-way streams, WebSocket for two-way. To scale WebSockets, separate connection handling (gateways) from logic, track which user is on which gateway, route with pub/sub, and handle heartbeats, reconnect storms and missed messages.
Real World Example
A ride-hailing app polls the 'searching for driver' status every 3 seconds, streams the driver's map position to the rider over SSE or a WebSocket, and uses a WebSocket for the in-app chat between rider and driver.