# Short Polling and Long Polling — WebSockets & Server-Sent Events

Source: https://www.skillbyai.com/en/realtime-web/rt-polling

> Implement long polling, and compare its cost and latency with short polling.

## How the two polling styles work

**Short polling** sends a request on a fixed timer, say every 5 seconds, and the server answers immediately, usually with "nothing new". The average delay is half the interval, and most requests are wasted work: TLS, headers, auth checks and a database query just to return an empty list. **Long polling** fixes the waste. The client sends a request and the server *holds it open* until it has news or a timeout (often 20-30 seconds) passes. When news arrives, the server responds at once and the client immediately sends the next request. Latency drops to roughly one network round trip, and empty responses only happen on timeouts. The cost moves to the server, which must park many open requests cheaply, so it suits event-loop servers (Node.js, asyncio, Go) better than one-thread-per-request designs. Long polling works through almost every proxy, which is why older chat systems and fallback transports used it.

## A long-polling client loop

A `cursor` tells the server which events the client already has, so nothing is lost or repeated between requests. A `204` means the hold timed out with no news.

```js
async function longPoll(url, onEvents) {
  let cursor = 0;
  while (true) {
    try {
      // The server holds this request open until it has news or ~25 s pass.
      const res = await fetch(`${url}?after=${cursor}`);
      if (res.status === 204) continue; // timed out with no news: ask again
      const { events, next } = await res.json();
      cursor = next;
      onEvents(events);
    } catch {
      await new Promise((r) => setTimeout(r, 2000)); // network error: back off
    }
  }
}
```

## Messages can slip between requests

Between one long-poll response and the next request, the server may produce new events. Without a cursor (an event id or sequence number), those events are lost. Always send "give me everything after X", never just "give me what is new".

**Quiz:** Compared with short polling every 5 seconds, what does long polling mainly improve?

- [ ] It encrypts the messages
- [ ] It removes the need for a server
- [ ] It lets the browser send binary frames
- [x] It reduces latency and the number of empty responses

*Answer:* It reduces latency and the number of empty responses. The server holds the request until there is news, so updates arrive almost immediately and empty responses only happen on timeouts.
