Question

What are best practices for long polling?

Currently what I have set up is javascript making an xmlhttprequest to a server with PHP running server side checking if there is anything new and return new content or no new content variable. Then client side will wait for n seconds after receiving the returned value before making another request.

But I'm seeing a lot online with a different approach, that if the server does not have anything new don't return just yet instead wait for n seconds and check again for new content until a certain number of attempts then return new content or no new content and the client side makes a new request right after receiving the returned value.

So with the above 2 which one would be the best approach to give less strain on a server or maybe conserve more server resources? My current setup or the 2nd setup? Or maybe a different approach?

Thanks!

Was it helpful?

Solution

Your first option isn't long-polling at all, it's just sending a request every n seconds. Long-polling means you send a request that stays open until a timeout is reached, or new data is available.

Long-polling is better than sending a request every n seconds because the data is closer to real-time without needing to send a request every <less than 10> seconds.

Typically on the server-side you would handle a long-polling request by using a sleep loop that repeatedly checks the db for new data with a short delay, say, 1 or two seconds. So, if you did it with a 2second delay and a 30 second timeout, you'll be hitting that database 15 times per user per 30 seconds.

Yes, long-polling can be resource intensive. You as the developer have to decide how much of the server's resources you can allocate to improve the user experience.

websockets is the go-to solution now days for chat systems because it bypasses this problem, allowing the server to contact the client(s) when there is a change rather than having n clients contacting the server every x seconds asking if something changed. It would normally work by having a "Post Message" command that the client calls when a new message is added by a client, that command would then broadcast the new message to all connected clients.

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