Polling with Node JS and Vue

ref – https://www.technouz.com/4879/long-polling-explained-with-an-example/
https://github.com/zaarheed/long-polling-example

Short Polling

Polling at intervals

  1. The client sends a request
  2. Server returns a response of either data or no data
  3. Client receives the response. If there is data, does something with it
  4. Client sleeps for an interval and repeats

The connection here is not continuous. It is at an interval. i.e 5 seconds.
This means we get a result every 5 seconds. However, our result can be ~5 seconds old.

For example,

seconds:
0, client makes a request,
0.1, server responds with empty response
0.2, client receives empty response, data is updated on the server side

1,
2,
3,
4,

5, client makes a request
5.1, server responds with updated data
5.2, client receives the updated data.

Thus, this data is ~5 seconds old.

Making repeated requests like this wastes resources, as each:

– new incoming connection must be established
– the HTTP headers must be parsed
– a query for new data must be performed
– and a response (usually with no new data to offer) must be generated and delivered.

The connection must then be closed, and any resources cleaned up.
This process gets repeated and it very inefficient.

Long Polling

Long polling is a technique where the server elects to hold a client’s connection open for as long as possible, delivering a response only after data becomes available for a timeout threshold has been reached.

With long polling it is almost immediately.
During long polling, we send a request. The request will take say..100 milliseconds. The server gets the data and sends it back, which say takes 200 milliseconds. So it is 300 milliseconds.

This is almost ‘real time’-ish.

On the client side, only a single request to the server needs to be managed. When the response is received, the client can initiate a new request, repeating this process as many times as necessary.

The only difference to basic polling is that a client performing basic polling may deliberately leave small time window between each request so as to reduce its load on the server. And it may responds to timeouts.

With long polling, the client may be configured to allow for a longer timeout period (via Keep-Alive header) while listening for a response.

Note the timeout seconds is ten seconds. This means, ten seconds is the maximum time the server has to return something.

The server

Client