PHP Session Garbage Collecting - Not great for shared hosting (Repost)

Posted: 2013-04-02 12:28:47 by Alasdair Keyes

Direct Link | RSS feed


This is a repost of an old article that I transferred across from my previous blog. I've only just noticed that it was incomplete so I've completed it and reposted it

I look after a fair sized Linux shared hosting cluster (20,000+ websites) and to provide PHP session persistence between the servers in the cluster, PHP sessions are stored on an NFS share.

I noticed that a number of processes where running for a long time on the Apache servers. At first I thought this was due to loops or bad coding on behalf of the website owners, but it didn't seem to be restricted to any particular users.

After running strace on one of these processes I saw that the processes where getting permission denied trying to delete large numbers of PHP session files.

It turns out that PHP implements it's own internal garbage collection to get rid of old sessions, however, as we run SuPHP, the PHP processes only have permissions to delete their own session files (due to the use of Linux's sticky bit permissions), but that doesn't stop the process recursing through the sessions folder and trying to delete all old sessions.

With 20,000 websites, most of which run PHP CMS systems, this is quite a drain, compounded by the fact it's on an NFS share, which also adds overhead to each filesystem request.

The solution was to turn off garbage collection in PHP config. Create a config fragment file /etc/php.d/disable_session_gc.ini on the webhead and add the following content

; Disable auto session garbage collector
session.gc_probability = 0

Obviously I didn't want the sessions building up on our NFS filer, so I just set up a cronjob to call tmpwatch and delete old files once per day. I decided 7 days would be adequate.

/etc/cron.daily/clear_php_sessions.sh

/usr/sbin/tmpwatch 168 /exports/php/sessions


If you found this useful, please feel free to donate via bitcoin to 1NT2ErDzLDBPB8CDLk6j1qUdT6FmxkMmNz

© Alasdair Keyes

IT Consultancy Services

I'm now available for IT consultancy and software development services - Cloudee LTD.



Happy user of Digital Ocean (Affiliate link)


Version:master-90480fad99


Validate HTML 5