Configuring PHP-APC for maximum hit ratio

I’m currently running php5 with APC, the latter with default configuration. However after setting up munin to monitor APC, I’m surprised by the results:

apc.shm_size: 30
apc.gc_ttl: 3600
apc.ttl: 7200
Used: 14MB
Request rate: 100 requests/second
Fragmentation: 0
Hit ratio: 80% (dropping to 0 a few times per hour)

So the obvious question: how can I adapt the configuration to achieve a higher hitrate. I find it very strange that the available memory is not fully used which the hitratio is still below what I would expect.

Here’s my munin chart showing the strange hit ratio drops:

It seems that sometimes all pages are removed from the cache, but the amount of purges is zero…

Thank for any hints!

What’s your php/apache setup? If you run suphp or phpsuexec then there are issues with how apc works with these.

Its fastcgi. My phpinfo() says the following:

PHP Version 5.3.19-1~dotdeb.0
System Linux 2.6.32-5-amd64 #1 SMP Mon Jan 16 16:22:28 UTC 2012 x86_64
Build Date Nov 24 2012 06:58:14
Server API CGI/FastCGI
Virtual Directory Support disabled

BTW: I tried setting a bigger shm_size, but that didn’t help.

I managed to reproduce the error by refreshing (F5) the apc.php page a few times.
I also enabled debugging, but I cannot find where and why apc determines to suddenly clear everything when not full yet. :frowning:

APC on fastcgi doesn’t share cache across different php workers, so it might be that if the fastcgi max requests parameter is set, then a worker will be terminated and respawned minus any cache.
You could also be jumping workers which have not yet built cache. Try setting PHP_FCGI_MAX_REQUESTS to 0 (though this means they never get respawned which means you can get memory leaks over time) and also set only one worker for test purposes. Alternatively, try xcache :wink:

I went on to find out about the shared caching problem, and there does indeed seem to be a problem. I have usually 1 to 3 php-cgi processes running, so if APC is not shared, this could explain why sometimes my cache is emptied (interestingly, when that happens, total requests in the apcinfo.php page also starts back from 0).
So, I set up nginx with php-fpm just to test (I want to keep apache, but want to leave it intact at the moment), and there indeed the APC cache hits is close to 97% (instead of about 80%)

I was surprised though that some performance tests showed that apache with mpm-prefork (as is currently the case) did 500 php requests in about 45s. With nginx, the same 500 requests took 61s. I’m unsure why this could be, and I first need to work out why that is before I could consider switching from php in cgi/fastgi to fpm/fastcgi. Do you have any experience with this?