phpjavascriptajax

Will frequent polling overload the server? If so, what's the best way of implementing live updates?


I don't know which is the most efficient way to do. I am seeking a better algorithm.

Let us take some example like Facebook when user posts a post, it will be updated to his friend without any page refresh and we know its by ajax request. But how can we know that some one has posted a new thing? may be like putting a timer for every 2 seconds and sending an ajax request for some table and checking if some user posted something. Right?

But is there a way to do without setting a timer because performing the operation for every 2 seconds may cause severe server issue I think so? Just want to know if there is a better way instead of setting a timer?


Solution

  • Currently what Facebook and Google employ, is a technique called long polling.

    It's a simple system whereby the client makes an AJAX request to the server. The server takes the request and checks to see if it has the data the request needs. If not, the request is left open but deferred by the server. The second the server has the data, the request is handled and returned to the client.

    If you open up facebook, you'll see requests being posted to Facebook which take around 55 seconds to complete. Same goes for Gmail and a few other web applications that seem to have some kind of push system.

    Here's a simple example of how these requests might be handled:

    1. Client:

      • Initial AJAX request which has the timestamp 0
    2. Server:

      • Compare request with timestamp 0 by checking the timestamp of the data on the server. Lets say the data on the server has the timestamp 234.
      • The client stamp is different from the current stamp on the server data so we return with the new data.
    3. Client:

      • Client gets the data and immediately posts a new AJAX request with timestamp 234.
      • Then we process the new data and update the web page appropriately.
    4. Server:

      • Compares request with timestamp 234 with the current stamp of the data on the server.
      • The stamp values are the same so we go to sleep.
      • Server data is update and stamp value is now timestamp 235.
      • Sleeping requests are woken up and returned with update value.

    You can read a more in-depth explanation of more modern mechanisms for live updates.