Card 03/ 10

ConceptDifficulty: Beginner2 min

Long Polling: Holding the Request Until There Is News

The server waits to answer, so an update arrives almost as it happens.

Long polling means the client sends an ordinary HTTP request, and the server does not answer until it has news or a time limit passes. As soon as an answer arrives, the client sends the next request. News reaches the client almost as soon as it exists, using nothing but plain HTTP.

Who starts, and which way. The client starts every exchange, as with short polling. The difference is on the server: instead of answering "nothing yet" at once, it holds the request open and answers when there is something to say.

One held request, the answer, and the next request

Why the time limit. A request held too long is cut by something in between, a proxy or load balancer with its own idle timeout. The server answers empty before that, often after 20 to 30 seconds, and the client asks again.

What it costs the server. Far fewer empty answers than short polling, because a request returns only with news or at the time limit. In exchange, every waiting client holds one open request on the server, so the server must handle many idle connections cheaply. A server that gives each request its own thread runs out of threads long before it runs out of work.

Long polling

Use it when

  • News must arrive within a second or so, and only the server has news to send
  • Something in the path cannot carry WebSockets or a streaming response
  • Updates are irregular, so a fixed timer would mostly come back empty

Avoid it when

  • The client also sends often, which a two-way connection does better
  • The server holds one thread for each open request

One product that uses it. The Telegram Bot API's getUpdates method takes a timeout parameter: set above zero, the server holds the request until a message arrives or the timeout passes.

So use long polling when news must arrive quickly over plain HTTP, and make sure the server can hold many waiting requests without a thread for each.