Sub topic 3
Polling, Long Polling, and WebSocket
Prerequisites and scope
This chapter assumes you know basic HTTP request and response behavior and what a TCP connection is. You should also be able to read short JavaScript and Python snippets. It covers how a chat client learns that a new message exists. Later chapters cover what the server does with the message once it arrives.
A chat system has a specific problem. In plain HTTP the client always speaks first, but a chat server often has news the client has not asked for. A friend sends you a message, and your phone must show it within a second or so. You must pick a transport that lets the server push data, or one that imitates pushing.
There are three common options: short polling, long polling, and WebSocket.
Short polling
In short polling, the client asks the server for new data on a fixed timer, for example every 2 seconds. The server answers immediately, even if it has nothing to say.
async function poll(chatId, lastSeq) {
const res = await fetch(`/chats/${chatId}/messages?after=${lastSeq}`);
const messages = await res.json();
for (const m of messages) {
render(m);
lastSeq = Math.max(lastSeq, m.seq);
}
setTimeout(() => poll(chatId, lastSeq), 2000);
}This is easy to build. It uses ordinary stateless HTTP, so any load balancer and any server can answer a request. Failures are simple too: if one request fails, the next one retries.
The costs show up at scale:
- Wasted requests. Most polls return an empty list. If 10 million users poll every 2 seconds, that is 5 million requests per second, and almost all of them carry no data.
- Latency tied to the interval. A message that arrives just after a poll waits almost the full interval. The average delay is half the interval, and the worst case is the whole interval.
- A trade-off you cannot escape. Shortening the interval lowers latency but raises load. Lengthening it lowers load but makes chat feel sluggish.
Short polling is acceptable for low-traffic dashboards. It is a poor fit for chat.
Long polling
Long polling keeps the HTTP model but changes when the server answers. The client sends a request. If no new data exists, the server holds the request open instead of replying. It responds when a message arrives or when a timeout expires, typically 30 to 60 seconds. The client then immediately sends a new request.
import asyncio
from collections import defaultdict
waiters = defaultdict(list) # user_id -> list of futures
async def long_poll(user_id, timeout=30):
fut = asyncio.get_running_loop().create_future()
waiters[user_id].append(fut)
try:
return await asyncio.wait_for(fut, timeout)
except asyncio.TimeoutError:
return [] # client reconnects and asks again
finally:
if fut in waiters[user_id]:
waiters[user_id].remove(fut)
def deliver(user_id, messages):
for fut in waiters[user_id]:
if not fut.done():
fut.set_result(messages)Latency is now close to the network delay, because the server answers the moment a message exists. Empty responses drop to about one per timeout period.
Long polling still has problems in a chat system:
- Re-request overhead. Every delivery ends the request. The client must send a new one, with full HTTP headers and possibly a new TLS handshake if the connection was closed. During the gap between response and the next request, messages queue on the server.
- Server selection. The next request may reach a different server than the previous one. That server does not hold the user's state, so you need a shared store or sticky routing to find it.
- One direction. The client still uses separate HTTP requests to send messages. Each send is a new request.
- Resource use. Each waiting request holds a connection and memory on the server. Intermediaries such as proxies may close idle connections sooner than your timeout.
- Ordering risk. A client that opens a new request before processing the previous response, or that has two requests in flight, can see messages out of order. Using a sequence number such as
after=lastSeqavoids losing or repeating messages.
WebSocket
WebSocket is a protocol that gives the client and server a single, long-lived, full-duplex TCP connection. "Full-duplex" means both sides can send at any time, independently.
A WebSocket connection starts as an HTTP request. The client asks to upgrade the connection, and the server agrees:
GET /ws HTTP/1.1
Host: chat.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=After the 101 response, HTTP is finished on that connection. Both sides exchange small frames with a few bytes of overhead each, instead of full HTTP headers. Because the upgrade starts as HTTP, it works through most firewalls and uses the usual ports 80 and 443 (wss:// is WebSocket over TLS).
What a WebSocket gives a chat system
- Low latency in both directions. The server pushes a message the instant it exists, and the client sends over the same connection.
- Low per-message overhead. There are no repeated headers or handshakes.
- A natural place to attach state. The server knows which user owns which connection, which is what routing and presence need.
What a WebSocket costs
- Stateful servers. A connection pins a user to one chat server for as long as it lasts. You cannot treat these servers like stateless web servers. Deployments must drain connections gracefully, and a server crash drops every connection it holds.
- Connection limits. Each open connection uses a file descriptor and memory. A well-tuned server can hold hundreds of thousands of connections, but you must plan for it.
- Reconnection logic. Connections break on mobile networks, when a laptop sleeps, or when a proxy times out. The client must detect this and reconnect with backoff, then catch up on missed messages.
- Idle timeouts. Load balancers and NATs close connections that carry no traffic. Periodic ping frames or application heartbeats keep them alive.
- Harder infrastructure. Load balancers must support the upgrade and long-lived connections. Some older proxies do not.
A minimal client
This client reconnects with exponential backoff and tells the server the last sequence number it saw, so the server can replay what was missed.
let lastSeq = 0;
let attempt = 0;
function connect() {
const ws = new WebSocket(`wss://chat.example.com/ws?after=${lastSeq}`);
ws.addEventListener("open", () => {
attempt = 0;
});
ws.addEventListener("message", (event) => {
const data = JSON.parse(event.data);
if (data.type === "message") {
lastSeq = Math.max(lastSeq, data.seq);
render(data);
}
});
ws.addEventListener("close", () => {
const delay = Math.min(30000, 1000 * 2 ** attempt++);
const jitter = Math.random() * 500;
setTimeout(connect, delay + jitter);
});
}
connect();The jitter, a small random delay, prevents thousands of clients from reconnecting at the same instant after a server restarts.
Comparing the three
| Property | Short polling | Long polling | WebSocket |
|---|---|---|---|
| Who starts delivery | Client, on a timer | Client, but server delays reply | Either side, any time |
| Typical latency | Up to the interval | Near network delay | Near network delay |
| Empty traffic | Very high | Low | None (except heartbeats) |
| Server state | None | Pending requests | One connection per client |
| Send path | Separate request | Separate request | Same connection |
| Proxy and firewall friendliness | Best | Good | Good, but needs upgrade support |
| Complexity | Low | Medium | Higher |
Choosing for a chat system
For the chat design in this tutorial, use WebSocket as the main transport. Chat needs low latency, traffic in both directions, and frequent small messages. These are the conditions where WebSocket's lower overhead pays off.
Keep HTTP for operations that do not need a live connection. Login, profile edits, loading old history, and uploading media all fit ordinary request and response APIs, and those servers can stay stateless. The next chapter builds on this split: stateless API servers on one side and stateful chat servers on the other.
Keep a fallback in mind. Some corporate networks block WebSocket upgrades. Libraries such as Socket.IO and SignalR fall back to long polling automatically. Whether you need this depends on your user base.
Common mistakes
- Polling without a cursor. Asking for "the latest messages" instead of "messages after sequence N" can lose or repeat messages when two requests overlap.
- No heartbeats. The connection looks open on the client, but an intermediary has already dropped it. Messages stop arriving with no error.
- Reconnecting without backoff. After an outage, every client reconnects at once and overloads the servers that just recovered.
- No catch-up after reconnect. The client reconnects but never asks for messages sent while it was disconnected.
- Treating chat servers as stateless. Deploys that kill all connections at once cause a reconnect storm.
Exercise
A chat app has 2 million active users. Using short polling every 5 seconds, how many requests per second does the server receive? Name two problems this creates, and say why WebSocket avoids them.
Show answer
2,000,000 users / 5 seconds = 400,000 requests per second. Most return empty lists, so the servers spend capacity on useless work. Message latency also averages 2.5 seconds, since a message waits on average half the interval. WebSocket avoids both: the server pushes a message only when one exists, and delivers it immediately over the open connection. The cost is that each chat server must hold many long-lived connections.
Exercise
A client's WebSocket drops for 20 seconds while the user rides through a tunnel. The client reconnects. What must it send, and what must the server do, so no messages are lost or shown twice?
Show answer
The client sends the highest sequence number it has processed, for example after=lastSeq. The server replays every stored message with a higher sequence number, in order. The client ignores any message whose sequence number it has already seen, which prevents duplicates if the server replays some that had already arrived.