Roman Holic Roman Holic - 1 year ago 109
PHP Question

NGINX + phpFPM load balancer and sessions

i have one question, i am using nginx and PHPFPM.
I am using loadbalancer for 2 phpfpm servers.

To keep sessions from both phpfpm servers synced i used memcached.
But when i use memcached i see that page is slowing down.

When i use files as sessions save type web is runing faster, but sessions are not synced imediately (i guess files are owerwriting). I am using NFS to share sessions.

Any ideas please how to sync sessions when using nginx loadbalancer for phpfpm servers?

Answer Source

The speed increase you're probably seeing here in PHP using NFS over memcached is a deceptive one by nature. PHP session storage defaults to lock acquisition on a first-come-first-served basis. Which means that two concurrent requests made to PHP for the same session will cause the first request to lock the session until either PHP is done or you explicitly call session_write_close() from your code, to release the lock.

But in a file based session store, PHP relies on flock, which doesn't work in NFS.

The NFS (Versions 2 and 3) protocol does not support file locking

See this answer on unix stackexchange

So for a distributed session store, you rarely want slow file-system based lock. Most in-memory stores work faster anyway. And since NFS can't typically handle flock calls, your sessions will get corrupted if two concurrent requests try to write to the same session file. In other words, what you're seeing as faster is just basically your requests potentially corrupting their sessions faster, because there's no lock on the session for concurrency.

If your requests take a really long time and don't require the session it's best to explicitly call session_write_close as early in the code as possible when you are done with the session so that any other concurrent requests coming in can get at the session. This is typically a problem when you're doing a lot of long-polling requests to PHP (say over AJAX).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download