What are Short and Long Polling?
The dictionary meaning of "poll" as a verb is as follows - check the status of (a device), especially as part of a repeated cycle.
In #computers and #networking, #polling is an activity where the status of something (a device/resource) is checked periodically. In a client-server architecture, polling is a way in which the client requests for the status of a resource from the server at regular intervals.
In older #architecture, this was a common pattern where the client pulls data from the server periodically and updates its view accordingly. Based on how frequently is this done, we have two types of polling -
1. Short Polling (or Polling)
2. Long Polling
Before looking at each of these, let's understand what happens when a client makes a request to the server. Many things happen, but the below are most notable ones -
1. make a connection to the server
2. prepare data as packets to send
3. write the packets onto the connection channel
4. server side - read the packets from the connection
5. server side - read the request headers
6. server side - process the information, write result to the same channel
7. close the connection
Whenever a client makes a (web) request to the server, all these things happen.
Short Polling (or Polling) is a pattern, in which the client makes asynchronous requests to the server at very short intervals, in the hope of receiving latest information. For example, the current trajectory of a satellite to be plotted over a time-graph.
In Short Polling -
1. Client makes a connection for a request
2. Server may or maynot have a message to send - so if nothing then times out
3. Client then closes connection
4. Delay (say 10s)
5. Repeat from step 1
But to get as live data as possible, the client makes too many requests and all the above mentioned steps need to be repeated every time. This takes up a lot of resources and may end up in clogging the network.
In Long Polling, the client makes a connection to the server with a request and keeps the channel open, until the server returns with some new data to the client. Here, the connection is kept open for a "long" time, and the server uses the same to write to the client. Once the data is written, the server closes the connection.
In Long Polling -
1. Client makes a connection, and hangs on
2. Server - when has something to write after sometime, puts the message and closes the connection
This way many of the steps above are not repeated and thus makes too less requests. But it doesn't make any sense, if there are many messages to be written.
In modern day real-time communications, we have more sophisticated techniques - Web Sockets , Server Sent Events and frameworks making these easy to use.
That's all about Polling. Share it with your friends if you find it interesting! 💯
Will you be interested in learning more about real-time communications with some real examples?
Let me know in the comments below! 😀