Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top