views:

82

answers:

3

I'm building a component of a web page that needs relatively constant database polling. I can see two different approaches for this, and I'm wondering if one of them is better than the others, or if I'm missing a third option.

1) Send off an AJAX request every 1 or 2 seconds to check for updates. Each request returns immediately whether or not there is new data.
2) Fire off a single AJAX request that will not return until it receives data or a timeout occurs. Upon either of those happening, it fires off the next request. (I think this is called long polling?)

The number of database queries will be the same with either, but with #2 there would be fewer requests firing from the browser which could save bandwidth and client resources. For the server, is it better to have a single PHP request that stays active and sleeps between queries, or that fires up every few seconds, polls the DB, then shuts down? Or is there no difference and I'm stressing about this too much?

EDIT: I suppose I should also state that this is a chat widget of a larger web app. A slight delay in communication is not going to kill a user, as chat is a secondary feature.

A: 

You can also look at websockets, part of the newest browsers (or emulated via a Flash file you drop on your page)

Will
Unfortunately, I need to be able to support current and possibly legacy browsers. Definitely worth some more research though. Thanks!
Derek
That's what the flash adapter does
Will
A: 

instead of AJAX pushing data to the server, look at it the other way around: the server pushing data to the client. http://en.wikipedia.org/wiki/Comet_%28programming%29

stillstanding
that's usually long-polling
Will
Yeah, I understand that's what long polling is (and I also found comet during my research). My question is which route to go...
Derek
+1  A: 

Long polling will scale better (i.e. less server load) than polling, while giving much better response times.

If your recipient polls, the average journey time of a message will be half your poll interval.

With long polling, its instant - the server only waits if there is nothing to say.

If you are doing chat messaging, go long poll; its a usability thing.

The down-side with long polling is it is more complicated to implement; but its not that much more complicated, and it is widely implemented. So if you can't use an off-the-shelf framework for your webserver of choice, you can set about writing one reasonably and you will get it working.

Will
Agreed. But with a dozen clients all hitting the system, that's a dozen php processes that are active 100% of the time. As far as scalability is concerned, I guess that's not much worse than half as many hitting it every second.
Derek
Make sure those processes are sleeping nicely, not in some polling of their own, and it'll all be nice and smooth. Worry when you have a few hundred or perhaps more clients.
Will