Long pulling PHP & AJAX - Server Performance

428

I implemented heartbeat as the following

$.ajax({
    cache:false,
    timeout:8000,  
    type:"POST",
    url:"someurl.php",
    data:allFormValues,
    error:function(){ alert("some error occurred") },
    success:function(response){ //call some functions  }
   });

and in the server side

$time = time();
        while(!proccessServer() && (time() - $time) < 60 )
        {
            sleep(5);
        }

and simply it call a function if it returns false the loop will sleep for more 5 seconds and then check but the problem is this thing is eating my resources CPU and this was only when 5 users testing it

I used before this

window.setInterval(function(){
  //I call a function here 
}, 5000);

but also it was eating the resources because of many requests

and maybe my app have 100K online at the same time also I am not thinking about using websockets because of browsers compatibility What do you suggest to solve this ? any help is appreciated

746

Answer

Solution:

Your web server (Apache?) will use one thread until the request completes, which eats resources. AND you are using a PHP process for each visitor, just waiting. PHP is not very suitable for such solutions. You should look at other technologies if you want to do Comet. For example node.js.

You could also switch to NGiNX as web server, and use NGiNX_HTTP_Push_Module from http://pushmodule.slact.net/ for you application, and then stay with PHP. NGiNX will then accept the connection from your visitor and then wait for your code to push data to NGiNX. It might work for you, depending on what exactly you want to do.

723

Answer

Solution:

The problem here is that you are letting the server sleep and retry. that itself is resource intensive. use it wisely.

what you should do is to poll the server in longer intervals, and have the server reply with a status like "done" or a "fail". after that, let JS determine the reply and do the retry - not PHP.


alternatively, you can use the new HTML5 sockets so that you have a persistent two-way connection from client to server. the server can push new content to the client without the client asking for it everytime.

People are also looking for solutions to the problem: php - Converting large associative arrays into local variables, based on key

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.