Longpolling High CPU

I have set up a real-time chat application using longpolling.

Basically, I receive an ajax request and keep it through a while loop with PHP until I get an update.

The CPU is constantly at 99 which I guess is not what I should aim for.

So now I have two thoughts

1.How can I do longpolling differently to bring down the CPU value?

2.When keeping a connection open with sockets (eg c++), I use a loop to send and receive data, a constant process, just like with longpolling, but it does not affect the CPU value as much as it does with this longpolling method. Why?

Running a while loop that doesn’t do anything is a horrible strain on the CPU. It’s known as a busy wait.
What you want instead is a mechanism that lets PHP know new data has arrived, so you can do idle wait instead.
If that is not an option then throwing some usleep in the loop to back off the CPU might also work to alleviate things.

You don’t see this problem with the c++ program you mentioned because thats actually doing stuff. It’s not a busy wait.

The loop keeps checking a file for updates and as soon as it finds updates it continues with sending the updates back to the browser. So it does something, but that doesn’t count or is enough maybe?

It’s checking it way too much with no results. Like I said, busy wait. Slow it down by adding some usleep.

Can you use web sockets instead of long polling?

Doesn’t fix the problem. You still need the busy loop to read from the file.

To really fix this problem you need a system that notifies you when something new arises without needing to constantly polling for it. Something like Redis pub/sub.

Are you saying web sockets are going to be continuously polling for info? My understanding (limited) is web sockets would only send messages when needed. If the load still remains a problem I think scaling horizontally or isolating the service to dedicated nodes would be a viable option.

The difference between long poll and websocket is only client side, in the browser. Long poll closes the connection, while websocket stays open.

At the server side though the problem is exactly the same. You need to check the file continously to see if anything was added.

Therefore, the only way to solve this is to not use a file, but something else that will do a callback when something changes, so you don’t have to check continously.

Or, and I forgot about this earlier, what you can also do is use inotify (https://www.php.net/manual/en/book.inotify.php) basically telling the operating system you want to be notified when a file changes. So then you don’t have to check continously and also don’t get a busy loop.

1 Like