Nginx – php5-fpm optimization for long polling

nginxphp-fpmphp5

I'm designing a chat application in PHP. I use nginx with php-fpm environment. The problem is, that after several clients connected, PHP scripts are getting very slow.

I have just several (5-10) clients connected and the long poll is set to 30 seconds. Nginx serves static content like images or styles instantly, but for PHP scripts it takes almost 5 seconds to load. I used XDebug to profile the code, but it tells me, that script which loaded 5 seconds took only 100ms, which is confusing.

I think that php5-fpm queues incoming requests, which causes such delays. Is there something I should know about php5-fpm configuration when using long poll? I'd like to emphasize, that it gets very, very slow when ~5 clients are using the chat.

Similiar issue: http://forum.nginx.org/read.php?3,198958 (one long-running PHP script blocks all other PHP requests)

This also might be connected: http://www.matt-knight.co.uk/2011/concurrent-php-sessions/

Best Answer

Building realtime application with bare php is not a very good option, specially when you need to long polling. You could make some tunings, but sooner or later (eg at 150 connected clients), you will have to change your architecture.

Also long polling requires continuous access to the database, in order to find out when a new message for a user has been sent. This could be an overkill, when you have more than 5 - 10 users, and this is probably the reason why after 5 - 10 clients your server starts to become slower.

I suggest that you use a seperate nodejs server with socket.io for the realtime application, its works great and it can hadle thousands on simultaneous connections without a problem. It contains excellent configuration options and it also support websockets or long polling based on the capabilities of the connected client

You can have a look at socket.io

Plus in order to send messages (push content) from php to the node.js server to the node.js server you could use the elephant.io library