Search code examples
phpajaxapachecometpolling

Which is better Comet or AJAX in term of 10->15 second polling?


My site almost done but i have a problem. Every 10->15 seconds my site will search the database to check whether there are updates or not. If there are updates then send a notification to user who online. I search google and found two solutions: Comet and AJAX. Which is better in my case. or is there a better solution?


Solution

  • In my opinion the best solution for a website that is on shared hosting and uses Apache and PHP is to use a realtime hosted service to push updates to connected clients.

    Here's why:

    Apache wasn't built to handle long-running persistent connections so it's not a great choice for Comet or WebSocket solutions. The PHP Comet and WebSocket solutions that you'll find will likely run standalone as a daemon process and not on Apache. On shared hosting it's highly unlikely you'll be able to run a daemon process and your hosting provider is also unlikely to be happy with you keeping many persistent connections open and hogging resource on the shared machine.

    If you got with an AJAX polling solution and poll your site every 10 to 15 seconds, and include a database query within that poll, then if you have a reasonable number of clients on your site resource usage can spike really quickly:

    100 clients, 10 second polling, 60 second period = 100 * 10 * 6 = 6000 requests and database queries per minute. A lot of the time these requests may also be a waste if no update has occurred. You can find a larger example here.

    By offloading the ability to push updates instantly to your website clients you remove these 6000 requests and database queries and replace them with one call to the realtime hosted service. The service maintains the persistent connections to the clients so that when your application pushes the update to it, it can deliver them to the connected clients.

    Finally, you should be aware that WebSockets supersede Comet as the preferred solution for realtime communication. The protocol was created to solve the problem that Comet solutions tried to solve with various hacks. For more on the history of these technologies and WebSockets see here.