Polling and Long Polling

We live in an era of real time applications, where we use convenient and fast socket connection for the actual data transfer, which allows to send an event straight to the client's device.

But it's not always easy to set the socket. Sometimes the host doesn't allow it, and sometimes there just no resources to support the infrastructure, test fault tolerance and security. In this case polling can be used.

Polling. The very name of it tells us that some poll will be happening regularly. Here it will be the poll of server.

Избирательный участок, где происходит настоящий polling:)

Of course we won't vote. But still we will question the server. The idea is quite plain - regularly ask the server about the new events and updates.

Ordinary polling

For example, we write a messenger and want to deliver new messages to users. With ordinary polling the client's application (browser/phone) will throw a request GET /messagesevery N seconds (e.g. 2 sec).

Polling communication between client and server

Direct decision leads to a needed result - a user gets his messages not later than 2 seconds after they appeared. At the same time cons are pretty obvious:

  1. It's still necessary to wait 2 seconds to get some messages
  2. The server load is unreasonably high. It's necessary to create a connection every 2 seconds, initialize an application etc. All this leads to extra waste of resources

And in this moment we welcome the long polling

What is long polling?

It's the same polling, but with slightly other idea. Within long polling the client sends a request to server with created beforehand timeout (usually 30 sec). The server processes this request in an infinite cycle mode with specified timeout and within the cycle awaits the updates needed by a client. When the update appears, the server at once gives the answer and closes the connection.

Long polling communication between client and server

So we shake off two cons of polling and provide updates to the user with the minimum delay. Long polling also has its disadvantages, but there is web socket for resolving them.