Contact Menu

How to Configure APC Cache on Virtual Servers with PHP running under FCGId

APC INFO Monitor

APC INFO Monitor

My Virtualmin Amazon Linux Server runs several virtual domains with PHP under FCGId using APC for opcode caching: Joomla, PHPbb, WordPress, etc . APC is somewhat challenging to configure properly with fcgid-enabled virtual domains, but it is quite helpful to optimize system resources and prevent traffic surges on one site from affecting overall server performance. Joomla and PHPbb have code that is pre-optimized with hooks for APC, but WordPress requires a plugin called W3 Total Cache.

First Things First

Please read my posts about APC on commodity virtual hosting servers and Apache and MySQL performance tuning before you begin.

If you are running your virtual servers under FCGId, then you should do so for all virtual servers on your machine. Why? Because then you do not need apache’s mod_php (php module). Less modules loaded, less wasted memory.

  • Comment out:<br /> LoadModule php5_module modules/libphp5.so
    in /etc/httpd/conf.d/php.conf
  • Remove any php_memory_limit lines in httpd.conf’s virtual hosts section.pecl install apc
  • restart apache
    defaults('USE_AUTHENTICATION',0);
  • do some performance testing and raise your server and thread limits to sane levels in httpd.conf

If possible, you may wish to run Apache with Worker MPM instead of Prefork MPM.

Installation Suggestions and Modification of Defaults

Be sure to install the newest version of APC, 3.1.9 as of the last revision of this post (I assume you know how to install and configure all the packages mentioned in this post):

tail -f -n 50 /var/log/httpd/error_log<br /> tail -f -n 50 /home/domainname.com/logs/error_log

Choose “no” for internal debugging,  but choose “yes” for the other installation options, including the Experimental options.

For W3 Total Cache (WordPress plugin):
Page Cache: do not choose APC for the W3TC’s Page Cache, choose Enhanced Disk.
Minify: do not choose APC for Minify, use Disk.
Opcode Cache: choose APC for Opcode Cache
Database Cache: choose APC for Opcode Cache

For APC running on virtual servers for opcode caching:
Remove apc.ini from /etc/php.d. Do not add the APC configuration into /etc/php.ini (main php.ini which is probably a template used for creation of new virtual servers).

Instead, enable APC on a per-domain basis by modifying the respective /home/domainname.com/etc/php5/php.ini — your httpd.conf or virtual.conf should look something like this for each virtual domain.

<VirtualHost 99.88.177.288:80>
ServerName chrisgilligan.com
ServerAlias www.chrisgilligan.com
DocumentRoot /home/chris/public_html
ErrorLog /var/log/serversoftware/chrisgilligan.com_error_log
CustomLog /var/log/serversoftware/chrisgilligan.com_access_log combined
ScriptAlias /cgi-bin/ /home/chris/cgi-bin/
DirectoryIndex index.html index.htm index.php index.php4 index.php5
<Directory /home/chris/public_html>
Options Indexes IncludesNOEXEC FollowSymLinks ExecCGI
allow from all
AllowOverride All
AddHandler fcgid-script .php
AddHandler fcgid-script .php5
FCGIWrapper /home/chris/fcgi-bin/php5.fcgi .php
FCGIWrapper /home/chris/fcgi-bin/php5.fcgi .php5
</Directory>
<Directory /home/chris/cgi-bin>
allow from all
</Directory>
SuexecUserGroup "#987" "#756"
Options ExecCGI FollowSymLinks Includes IncludesNOEXEC -Indexes MultiViews SymLinksIfOwnerMatch
RemoveHandler .php
RemoveHandler .php5
IPCCommTimeout 12
</VirtualHost>

You must “babysit” the configuration: use the APC monitor (apc.php) to see how many files are being cached, and how much memory (apc.shm_size) is needed to avoid fragmentation, which will cause the 500 errors. If fragmentation rises quickly to 100%, memory usage is full, and cache full count rises above 0, you will almost surely see “500” errors.

If WordPress is the only PHP script software package on the domain, the following configuration will likely work for you; if you have more PHP software packages, you will need to raise apc.shm_size and raise the apc.user_entries_hint and apc.user_entries_hint settings, and possibly lower TTL values to allow cached files to expire and be replaced.

In general, you must double apc.shm_size in relation to APC’s highest reported Memory Usage to avoid fragmentation completely.

Configuration Suggestion for php.ini

in the virtual server’s /home/domainname.com/etc/php5/php.ini, add the following configuration:
(you may also install memcached, and should install fileinfo for full use of W3 Total Cache)

[memcached]
;memcached for distributed servers - e.g. mysql server on separate host
;extension=memcache.so

[fileinfo]
;fileinfo is included in PHP 5.3=>... uncomment the following line if using <=5.2
;extension=fileinfo.so

[APC]
extension = apc.so
apc.enabled = 1
apc.shm_segments = 1
apc.shm_size = 12M
apc.optimization = 0
apc.num_files_hint = 512
apc.user_entries_hint = 1024
apc.ttl = 0
apc.user_ttl = 0
apc.gc_ttl = 600
apc.cache_by_default = 0
apc.filters = "-/home/username/public_html/apc/apc\.php$"
apc.slam_defense = 0
apc.use_request_time = 1
apc.mmap_file_mask = /tmp/apc-accountname.XXXXXX
;OR apc.mmap_file_mask = /dev/zero
apc.file_update_protection = 2
apc.enable_cli = 0
apc.max_file_size = 2M
apc.stat = 1
apc.write_lock = 1
apc.report_autofilter = 0
apc.include_once_override = 0
apc.rfc1867 = 0
apc.rfc1867_prefix = "upload_"
apc.rfc1867_name = "APC_UPLOAD_PROGRESS"
apc.rfc1867_freq = 0
apc.localcache = 1
apc.localcache.size = 512
apc.coredump_unmap = 0
apc.stat_ctime = 0

Save php.ini, restart apache and then watch the APC Monitor to ensure fragmentation stays below 50% (it should remain less than 10% most of the time… if fragmentation rises quickly, you should add a few more MB’s of memory to apc.shm_size and restart apache).

Monitoring APC Performance and Detecting Errors

You should run apc.php in a password-protected directory in the domain’s public_html. Edit the apc.php code to allow passwordless access.
mod_fcgid: process /home/username/public_html/scriptname.php(21272) exit(lifetime expired), terminated by calling exit(), return code: 0

You can monitor errors with these commands:
... exit(server exited) ...

In the logs, you should see messages like the following:
... exit(idle timeout) ...
exit(communication error)
apc.filters = "-/home/username/public_html/apc\.php$,-/home/username/public_html/wordpress/wp-content/themes/themename/thumb\.php$,-/usr/share/psa-horde/.*,+/home/username/public_html/phpmyadmin/.*"
if the cache is working well. If you see exit(communication error) then you have issues, probably cache full and fragmented.

Fragmentation Explained

Fragmentation is a measure of the non-available portion of apc.shm_size due to lack of contiguous memory large enough to accept new cache items. 100% fragmentation means the available memory is broken into hundreds of small pieces that are too small to accept new cache items. This occurs when cached items expire and new cached items fill their vacated memory slots; usually the new item is slightly smaller than the old item, and the leftover space may be too small for a new cache item.

Fragmentation can cause even a large amount of free memory to be unavailable for new cache items. That is why I say above you can avoid fragmentation by doubling the apc.shm_size in relation to the largest total memory usage you see. So you may want to start with 100MB, let the site run for a few hours during high traffic conditions, and then reduce shm_size to roughly double the highest amount of cache memory usage during that time.

Further Information and Suggestions

APC can have a very significant effect on minimizing overall server load and overall memory usage. It takes time to configure, and must be re-configured whenever PHP script software is added to a virtual server. The more plugins/mods/components you add to a PHP software package, the more scripts, database queries and objects will be cached.

If you have PHP scripts or plugins that do not need to be cached (low traffic pages such as contact forms, PHP scripts that do not have APC hooks and have their own caching schemes, dynamic image resizers, etc.), you can filter them out with simple RegEx:
apc.filters = "-/home/username/public_html/apc\.php$,-/home/username/public_html/wordpress/wp-content/themes/themename/thumb\.php$,-/usr/share/psa-horde/.*,+/home/username/public_html/phpmyadmin/.*"

TimThumb is a good example of a common WordPress theme plugin that may not need to be cached.

Because the apc.filters RegExp only works with filenames, it is not possible to filter out an entire PHP script package, component or plugin based on the directory where it resides. So if you do not wish to use APC cache on a particular script package, you should run it in a separate website. Some PHP script packages such as Gallery2 have an incredibly large number of .php, .inc and .class files which will be cached, so it is difficult to find them all and filter them all using apc.filters.

If you can’t raise apc.shm_size due to lack of available memory, try lowering the TTL’s (values in seconds, 0 is no limit, 600=10minutes, etc.). This will still have a good effect on high-traffic sites with many concurrent end users; caching is not at all necessary for low-traffic sites. However, be aware that lower TTL’s can cause more fragmentation.

During Testing or Debugging with CMS caching plugins or modules

While you are tweaking your opcode settings, and especially if you are using APC with a CMS like WordPress (w3 total cache) or phpbb or joomla, and you are experimenting with settings, or updating plugins or core, you should set apc.stat=1 (on). Restart the web server to load the new settings.

APC.Stat is the file change polling, which checks for file change every time a cached script or object is called. So, with polling turned off, your settings/configuration files will remain cached, and this will cause you a lot of frustration. W3 Total Cache in particular is difficult to get configured properly with apc.stat=0 because the config settings and files are dependent upon database and php, which will be cached as files or opcode.

After you have sorted out your opcode settings, you may switch apc.stat=0 and restart the web server to turn off polling for better performance.

If you cannot get APC to configured correctly for your WordPress sites, I suggest WP Super Cache and WP Minify… that combination will probably have a better effect, as it will serve pages very quickly and accellerate user experience for a small number of users. Joomla 1.5 and phpBB3 are much easier to work with, as their caching systems are built to use APC and other opcode caches. Apparently, Gallery3 now also supports opcode caching.

More advice:

  • turn on apc.stat (documentation says, “not for production servers”, but W3TC requires stat polling to monitor file status, post revisions, plugin upgrades, etc.)
  • turn off apc.optimization (experimental and unstable, may cache user session info, fubaring items which should not be cached, such as admin pages and logged-in site pages)
  • turn off apc.include_once_override (use carefully; only useful with PHP scripts that do not have cache hooks, such as Joomla 1.0, phpBB2, etc.)
  • turn off apc.slam_defense (may cause objects to be replaced with PHP warnings which are displayed to the user, especially on Joomla 1.5)
  • set apc.user_ttl = 0 (allows your php scripts to set appropriate timeouts for queries and objects)
  • set apc.mmap_file_mask = /tmp/apc-yourusernamehere.XXXXXX for file-backed mmap; make file mask unique by adding your unique string; XXXXXX (exactly 6 X’s) must remain to allow APC to add random string
    OR set to /dev/zero for anonymous mmap if you can spare the memory

APC Manual: http://www.php.net/manual/en/book.apc.php
APC Runtime Configuration http://www.php.net/manual/en/apc.configuration.php

, , , , , , , , , , , , , , , , , , , , , , , ,

57 Responses to How to Configure APC Cache on Virtual Servers with PHP running under FCGId

  1. Tom November 6, 2010 at 10:31 am #

    How can you have apc cache shared over multiple fcgid processes?

  2. Chris Gilligan November 6, 2010 at 1:03 pm #

    Tom, the server I am describing runs Virtualmin, so there are multiple virtual domains, each with a unique php.ini. Each virtual domain runs as a separate user, and each user’s mmap_file_mask is unique (/tmp/apc-yourusernamehere.XXXXXX). It seems to work fine with multiple installations of WordPress, Joomla, phpbb, etc.

    • Luis Delgado December 16, 2011 at 4:51 pm #

      Chris. Great, Excelent superb post… I was looking for something like this for months… Do you think there could be any differences between Virtualmin and cPanel in the way they handle virtual domains? I mean, would there be any differences between what you are managing here if I use cPanel?

      Thanks for sharing your knoledge :)

      • Chris Gilligan December 17, 2011 at 12:47 pm #

        Yes, Cpanel and Virtualmin handle virtual domains differently. I don’t know the specifics, but Virtualmin essentially creates a virtual server for each virtual domain, so it allows discrete Apache and PHP settings for each domain, and keeps memory allocations separate. This is less thrifty than Cpanel, but gives more flexibility.

        On Cpanel, I have had good luck with Memcached and MySQL optimization, but not with APC.

  3. Big City Informer March 8, 2011 at 3:37 pm #

    mod_fcgid (with worker.mpm) spawns more than one php process, and each one seems to use a different apc-cache (same mmap filemask, only last 6 XXXXXX are different).
    So watching the apc.php stats shows a different uptime and other stats every time I hit the “reload” button :(
    Any idea how to have all php processes use the same apc cache?
    It’s a dedicated server with only one WPMU install on it and domain-mapping.

    • Chris Gilligan March 11, 2011 at 12:02 am #

      Big, I do not know how to have all processes use same apc cache… you might be better off with eAccellerator for your setup. In my server, I have multiple virtual domains with each a separate php process. WPMU I do not use so don’t know what to tell you. I would suggest you experiment with W3 Total Cache, as it is the best implementation of WP Cache that supports APC. There are a lot of interdependent settings between apc/php.ini and W3, so there will be some trial/error and babysitting before you come up with an acceptable solution.

      I originally suggested apc_stat=0, but w3 may need apc_stat=1 to monitor file status, so the overhead saved by turning off stat could be lost when w3 polls files and does garbage collection. Try and see on your server.

      Also be sure to apc.filters = "-/home/user/public_html/apc\.php$" so you don’t cache the apc monitor.

  4. Chris Gilligan March 11, 2011 at 11:15 am #

    Here’s a guide that explains how to set up w3tc on shared hosting. The tutorials on minify are particularly helpful, and useful for all deployments of w3tc.
    http://zemalf.com/1443/w3-total-cache/

  5. Big City Informer March 16, 2011 at 10:54 am #

    Thanks,
    found out by the way that it is possible to use apc in that config, it just uses several different apc-caches. But it still seems to cache and work somehow as expected.
    Played around with all the settings in w3 and already using the development version by the way ;)

  6. arnaud mallaisy April 20, 2011 at 6:44 pm #

    Hello,

    I have a ubuntu server with apc and I want to have multiple joomla site hosted. But I have a problem as since the joomla use the same component, the cache mix up the files and basically I get one site with the content of the other or vice versa. Even of course after disabling apc in the joomla backend (I set file system for cache except on the main site).
    I also disabled apc to run on the directory of the others sites using

    php_flag apc.cache_by_default Off

    and after checking phpinfo, it is indeed disabled on that directory. Still the cached files are mixed up..

    How can I setup sites to use their own cache ?

    Regards

    • Chris Gilligan April 20, 2011 at 9:22 pm #

      Run each site as a separate virtual host. Set up an individual php.ini for each virtual host in /home/accountname/etc/php.ini and set up your virtual hosting PHP to use that ini for each individual host.

      Then follow the directions above concerning apc.mmap_file_mask (substitute your info for /tmp/apc-yourusernamehere.XXXXXX, and be sure to use exactly 6 X’s).

  7. Georg June 13, 2011 at 11:40 pm #

    Chris,

    this was an interesting night. So i got APC running, and i immediately started to tweak on my CentOS 64bit, Cpanel 2GB memory server.

    The first thing i see that the cache fills up VERY quick, and i see horrible fragmentation rates.

    I increase shm_size from 32 – 64 – 100 up to 256.

    The result was that my server almost came to an halt. I tried to trouble-shoot what is going on…extreme high CPU load, but did not see anything odd going on using top.

    My guess is that it caused to swap out on temp file or something, rendering the server almost non responsive.

    I had W3TC set on three sites to cache database/object to APC. Anyway, i immediately removed APC again and my server load is green again.

    I dont know what to think:

    If i set shm_size “small”, 64MB-100MB i get the cache purged literally every few seconds, i can literally watch it getting filled/fragmented. If i increase the cache my server goes down.

    If i set apc.ttl 0 i get countless errors “unable to allocate pool memory” on my wordpress sites(which is a known issue apparent with APC for 2 years already, see Google).

    In other words: My experience using APC today was NOT pretty.

  8. Chris Gilligan June 15, 2011 at 4:06 pm #

    Georg, I do not think CPanel servers support APC. Sorry you went through the trouble of trying.

  9. Mat June 17, 2011 at 3:24 pm #

    help a lot, thanks for your post.

    One little correction:

    before: apc.shm_size = 32M (= error!!)
    after: apc.shm_size = 32 (=work)

  10. Chris Gilligan June 19, 2011 at 12:26 pm #

    Mat, yes the size may need to be spec’d without the M on some systems. Can you reveal your OS, Apache and PHP versions?

  11. David G June 24, 2011 at 3:12 pm #

    I’m wondering how can the cache be reset or purged? APC.php reports my installation is chugging along fine, only 0.4% misses and 1 full count after 2 weeks and 55% used as I look at it now. But 64% fragmentation that looks kind of ugly and haven’t figured a way to purge the cache other than a reboot.

    • Chris Gilligan June 30, 2011 at 5:22 am #

      David, you can purge the cache by doing several things which are more gentle than a reboot.

      via APC’s API (WordPress’ W3 Total Cache plugin is a fine example)
      via apc.php (APC Control Panel)
      via Apache restart

  12. Katie @ women magazine July 7, 2011 at 6:25 am #

    Hello Chris,

    I just jumped to APC and found that there is no improvements although i haven’t fine tuned APC.

    I am on Rackspace cloud server 512RAM for the moment. I haven’t put it on domain level. i have 3 sites hosted here and don’t plan to use APC on other 2 sites other than stylishandtrendy.

    Thanks

    • Chris Gilligan July 7, 2011 at 6:58 am #

      I took a look at your site and it appears your CDN is not delivering your minified files.
      As mentioned above, you should raise the shared memory setting if you are getting too much fragmentation.
      Try this and let it run for a bit to see if fragmentation stays low.
      apc.shm_size 48M
      apc.max_file_size 2M

      Also filter out apc.php to prevent it from caching
      apc.filters apc\.php$
      Set a tmp output with file mask and make sure the /tmp is writeable by your apache or account user
      apc.mmap_file_mask = see above
      Change file hint to better match a single wordpress site
      apc.num_files_hint 512
      apc.user_entries_hint 1024

      • Katie @ women magazine July 8, 2011 at 6:44 am #

        Hello Chris,

        Thanks for your input, i have tried what you suggested still i don’t see much improvements. Unfortunately, i am still not able to get php.ini on domain level but rest of the settings are in place.

        Also i have noticed few things:

        1. When i filter apc in configuration then it won’t open apc.php instead ask me to download the phpfile.
        2. i can see that in Per-Directory entires it is caching all plugins and wordpress files which are unnecessary, i think that’s causing the fragmention. What do you think?
        3. I can see that it is caching other sites plugins also, i hope this won’t be the case when i am able to configure it for domain level.

        Will you please look at it again and tell me if i am missing something here. If you need the user and pass to check please let me know.

        Thanks for all your help.

        • Chris Gilligan July 8, 2011 at 9:09 am #

          If it is caching plugins for all of your hosted sites, that is the cause of your fragmentation. Shared memory is too low to handle all of the cached variables, and
          I run Virtualmin, which allows to set a separate php.ini for every virtual domain.
          Some hosting companies allow php.ini on a per-directory basis, recursive. Cpanel offers this function. Add or edit a php.ini file in your wordpress directory, change a setting (upload_max_filesize is an easy temporary change that won’t affect anything), and see if it shows up in phpinfo for that directory after apache restart. If that is the case, you can try disabling apc at the root level, and enabling it only on the sites (or directories) you wish. Try it and let me know…

          • Katie @ women magazine July 11, 2011 at 6:05 am #

            Hey Chris,

            I tried to have custom per-directory level php.ini but that didn’t worked per my setup. So i simply used “php_flag apc.cache_by_default Off” on all other hosted domains. Now, i don’t see their entries in apc.php. Cache hit has gone up but fragmentation is still very high. If you look you will understand what i am talking here.

            BTW: Is APC caching has anything to do with MaxClient setting of httpd.conf? I can see in my error log that it says Max client reached.

          • Chris Gilligan July 12, 2011 at 6:36 am #

            It is normal for /wp-admin/ scripts to be cached. W3 should properly take care of this, and not cache objects. Are you experiencing problems with your admin pages?

            Check the format for your apc.filter and make sure it it correct, read the advice in the article again to make sure you have the regex correct. You cannot specify anything other than the actual script filename.

            Perhaps if you need additional advice you should contact Frederick, he is helpful and may be able to help you properly set up your server if you are convinced that you should continue to use w3tc.

        • Chris Gilligan July 11, 2011 at 8:36 am #

          If you are running multiple virtual domains with multiple installations of wordpress, and you cannot have a php.ini for each virtual domain, this can cause users to receive a page from a different website if the query is the same. Tell us a little about your server setup.

          For APC with FCGId to work properly, you must be able to set APC parameters in a local php.ini for each virtual server. Setting APC parameters in the main php.ini is not effective and is inviting problems due to duplicate queries for like-named scripts. You need unique apc.mmap_file_mask for each virtual server.

          Maxclients is the maximum number of simultaneous apache client connections. If you have reached maxclients and you are not running out of memory, then you can safely raise maxclients value.

          If apc shows 100% fragmentation, you need to raise apc.shm_size.

          You might also check if apache is compiled to run Worker MPM as well as default Prefork MPM — see the top of this post for new info on that subject. Worker MPM is generally more efficient with FCGId.

          If you cannot use APC due to your VirtualHost setup, you might consider scrapping APC & W3, using Super Cache instead to handle page cache, and Minify to handle minification. Then set your sights on optimizing MySQL with table cache and query cache. But that is another subject entirely.

          • Katie @ women magazine July 12, 2011 at 5:53 am #

            Hey Chris,

            I think multiple domain issue is not there on my site now but i still see few things:

            1. I can see /wp-admin/load-scripts.php and lots of other admin scripts in “System Cache Entries” I think Admin is also being cached which shouldn’t be the case.
            2. apc.filter: Whenever i write anything in there mysite.com/apc.php stops working instead it asks me to download apc.php What’s wrong, any idea?

            3. What are the best practises for WordPress i.e.

            exclude wp-includes/ or not?
            exclude wp-admin or not?
            exclude plugins or not?

            I think these will effect overall memory usage too. BTW i have increase aps.shm_size to 64M now

    • Chris Gilligan July 7, 2011 at 7:08 am #

      You also need to set w3 total cache to use APC for database and opcode cache

    • Chris Gilligan July 7, 2011 at 7:10 am #

      turn off gzip compression in W3’s browser cache settings if your minified files are not working.

  13. Aziz August 16, 2011 at 11:28 am #

    Hi Chris. Thanks for the excellent write-up. I must have revisited this tutorial like twenty times in hopes that i missed something. I’d like to get a second opinion on why APC keeps clearing my cache at random intervals. apc.ttl and apc.user_ttl are both set to 7200. Plus I’ve never seen my apc uptime go beyond 2-3 minutes.

    I’m not entirely sure if this is the culprit, but perhaps setting FcgidMaxRequestsPerProcess to 1000 in the fcgid.conf would cause the php process to be terminated and consequently clear the apc cache?

    On another note, have you read about the recent timthumb security vulnerability?.

    Here’s the link:

    http://markmaunder.com/2011/zero-day-vulnerability-in-many-wordpress-themes

    • Chris Gilligan August 16, 2011 at 1:57 pm #

      Aziz, thank you for the reminder about timthumb. Looks like the developer and bug fixer have gotten together for a solution, which I have now implemented on several sites.

      fcgidmaxrequestsperprocess could possibly be the culprit. I do not have that directive in fcgid.conf.

      Try
      apc.ttl = 0
      apc.user_ttl = 0
      apc.gc_ttl = 600

      • Aziz August 16, 2011 at 5:17 pm #

        Thanks Chris. The default value for FcgidMaxRequestsPerProcess is 0. I changed those values with no luck. Setting FcgidMaxRequestsPerProcess to 0 also did not help. The APC cache still clears after a few thousand requests. This is what my error log shows me after the cache gets cleared:

        mod_fcgid: process /var/www/cgi-bin/cgi_wrapper/cgi_wrapper(15585) exit(idle timeout), terminated by calling exit(), return code: 0

        Not really sure how to tackle this issue. Disabling the object cache from W3TC definitely solves the problem, but without it I’d have around 30-35 queries per page, vs 12-18 queries when its enabled.

        • Chris Gilligan August 16, 2011 at 5:58 pm #

          What about apc.num_files_hint & apc.user_entries_hint ? Are those set to realistic values for your site? I have found that a single WordPress site works well with settings:
          apc.num_files_hint = 512
          apc.user_entries_hint = 1024

          Also be sure fileinfo is loaded and apc.stat=1, as w3tc needs these to determine if/when a cached file is stale.

          I’m not sure what else to suggest… settings outlined above work well for me, with changes to apc.shm_size and _hint settings for sites with more plugins or additional script packages: I use 80M size for busy WordPress sites, and up to 120M size for domains running additional script packages.

          Have you tried duplicating the settings above? They are working well for several WordPress sites.

          • Aziz August 16, 2011 at 6:30 pm #

            My sincere apologies Chris. After further research I realized that setting apc.gc_ttl to 600 helped. I checked the timeout value of one of my week-long wp transients and it seemed to have survived. From what i noticed, there seems to be some sort of lag (approx 20-30 secs) in fetching the old “survived” transient value and replacing the new one.

            Under apc.php, the uptime would reset to 0 at first, then go back to its original uptime prior to the cache being cleared.

            Fileinfo is loaded and apc.stat is 1. No problems there. I’ll set apc.num_files_hint and apc.user_entries_hint appropriately.

            How does apc.gc_ttl work? What are the implications of setting it too high or too low? and how is it refreshed and at what interval? Thanks in advance.

            Subscribed to your blog.

          • Chris Gilligan August 16, 2011 at 6:33 pm #

            I see the same behavior re: cache uptime reporting. Refreshing the display a couple of times seems to bring apc.php to a stable uptime report. I am not sure why this happens but it does not seem to be causing any issues.
            http://www.php.net/manual/en/apc.configuration.php#ini.apc.gc-ttl

  14. John Murray October 17, 2011 at 10:20 am #

    Chris, thanks for a great write-up.

    On your comment: “If you are running multiple virtual domains with multiple installations of wordpress, and you cannot have a php.ini for each virtual domain, this can cause users to receive a page from a different website if the query is the same. Tell us a little about your server setup.

    For APC with FCGId to work properly, you must be able to set APC parameters in a local php.ini for each virtual server. Setting APC parameters in the main php.ini is not effective and is inviting problems due to duplicate queries for like-named scripts. You need unique apc.mmap_file_mask for each virtual server.”

    I had a lengthy back-and-forth with my hosting company, and it does not appear that this is true on my VPS. I referred my host to your article, and an admin had this to say:

    “I think he’s making the assumption that the webroot is being used to identify the files. This is not the case. To explain further, when you have two different websites, their webroot’s default page is:

    /index.php

    Their WordPress admin directory will be:

    /wp-admin/

    And so on. However, APC is not storing these based on document root. It is storing them based on filesystem postion. So:

    /home//public_html/index.php

    will not be confused with…

    /home//somedomain.com/index.php”

    A look at cache entries when apc.php runs shows that apc is in fact storing entries based on filesystem position. That eliminates the need for a unique apc.mmap_file_mask for each domain.

    Trying to get domain-specific php.ini files was difficult, and I never pulled it off. But loading APC in the master php.ini with 1 setting for the mask works just fine.

    • Chris Gilligan October 26, 2011 at 12:49 pm #

      Thanks, John. Each setup is different, on my VPS server, running with Virtualmin, APC works best as described. In effect, Virtualmin runs multiple virtual servers, each with it’s own apache and php settings. So it does make sense to mask each virtual domain’s cache independently. This also allows to set each domain’s cache to appropriate size & counts for scripts, etc. Servers running with Plesk, Cpanel, etc. have different requirements from Virtualmin.

  15. Ünsal Korkmaz November 19, 2011 at 10:00 am #

    I see WordPress nonce-check problems with apc cache. (plugin is http://wordpress.org/extend/plugins/wp-fb-autoconnect/ ) So i am using memcached for caching. Be careful with using apc on fcgid. I tried lots of time but apc is not suits fcgid..
    Some discussion about topic:
    https://bugs.php.net/bug.php?id=57825

    • Chris Gilligan December 5, 2011 at 8:28 pm #

      I am currently seeing very good performance with the following:
      – APC for Page Cache and Minify
      – Memcached for database and object cache
      OR
      – MySQL cache optimization with no W3 database or object cache

      • Sarbjit Singh December 19, 2011 at 9:20 am #

        I have been trying to find out other who suggest using “Desk Enhanced” for Page Cache. Everyone seems to favour APC. Now your comments here suggests the same. Which one do you recommend now?

        I am using APC for Page Cache and its working quite well. However, my serve keeps running out of RAM. Will RAM usage decrease if I change to Disk for Page Cache?

        • Chris Gilligan December 20, 2011 at 8:13 pm #

          If you have a lot of RAM to spare, and you are only running a few virtual domains, use APC. If you are short on RAM, use Disk Enhanced. RAM usage should decrease because you will be using Disk to save the temporary cache files instead of RAM.

  16. Dfonts December 20, 2011 at 6:38 am #

    Hello
    I have a server with ngnix, php-fmp and apc, and suddenly the site stop working and got this error .

    2011/12/19 21:46:34 [error] 492#0: *7 FastCGI sent in stderr: “PHP Warning: include_once(/var/xxx/Auth.php): failed to open stream: Too many open files in /var/xxx/Loader.php on line 146

    Any ideea about “Too manu open files” ?
    After a php-fpm restart the site start working again.

    • Chris Gilligan December 20, 2011 at 8:14 pm #

      I am not yet familiar with nginx & php-fpm. I do not know what may be causing “too many open files” with nginx & php-fpm.

    • Fleshgrinder April 7, 2012 at 9:36 am #

      This has nothing to do with nginx, php-fpm or APC. It’s an OS limitation. Google for sysctl or sysctl.conf and increase fs.file-max and kernel.shmmax.

      • Chris Gilligan April 7, 2012 at 9:52 am #

        Thanks for the info! I’ve seen reference to that issue in the past, but have not experienced it on any of my current crop of servers. I imagine on a VPS that could be a limitation that is impossible to rectify without a change on the master node.

  17. Using APC for Page Cache and its working quite well. However, my serve keeps running out of RAM..

    • Chris Gilligan June 26, 2012 at 3:01 pm #

      Is it your server running out of RAM, or your virtual server running up against PHP RAM resource limit, or is it your APC cache size set too low?

      How much total server RAM do you have, what is your PHP RAM resource lint, and what is your APC cache size?

  18. Downloadz Portal August 3, 2012 at 7:46 pm #

    Hi!

    I am so thankful I found this guide. There’s a lot of guides to setup APC with WordPress and W3TC but they all use different settings and nothing really worked for me. Thanks to your guide and your php.ini-settings I finally got it to work.

    Before this I used xCache opcode for a few days, made my VPS completely unstable and caused me to lose a lot of traffic. I switched to Worker MPM and setup APC and WABOOM! My site’s faster than 95% of all sites tested at pingdom and a performance score of 93/100. (Which before was 88% and performance 89/100) So I’m very happy! Thanks again!

    • Chris Gilligan August 3, 2012 at 10:52 pm #

      Nice work! Super fast site. I am not using Worker MPM right now due to some issues I had on a much older server… but I may try it again if it is working for you. I just set up this CentOS 6 VPS and have not yet tested MPM on CentOS 6 with Apache 2.2.15… it didn’t work well with 2.1.15 on CentOS 5.8. There were some issues with session integrity… e.g. commenting, admin and other session dependent functions.

      • Downloadz Portal August 4, 2012 at 1:42 pm #

        My VPs also runs on CentOS 6 with the latest apache and php. No issues here. So yeah, you should definitely give it a shot.

        One issue that I can’t seem to get fixed with ACP is that it doesn’t cache any files. Only user cache is running with a hit/miss ratio that is 50/50. My blog is pretty big (a lot of posts, updated multiple times a day) and it’s pretty busy as well.

        My W3TC settings are: page cache (disk enhanced), minify (disk), object and database cache (APC) and browser cache enabled.

        I’ve added some images of my APC stats and settings. Hope you can help me out.

        http://s14.postimage.org/7oz6u5mfl/cache_information.png

        and

        http://s14.postimage.org/cc58vx9sh/runtime_settings.png

        • Chris Gilligan August 4, 2012 at 3:33 pm #

          You should have hundreds of files cached. Looks like APC is loaded and live, but your Apache host is not caching anything. Check your php.ini, and you may need to enable APC via .htacccess — http://linuxsysadminblog.com/2010/03/enabledisable-apc-on-virtual-host-level/

          The way my VPS is set up, I am running multiple virtual hosts under mod_fcgid, so each vhost has it’s own unique php.ini. If you are only running a single host via mod_php or php_fpm, then you probably need to enable APC with .htaccess or make it default on in php.ini.

          • Downloadz Portal August 5, 2012 at 8:27 am #

            I’m only running one host, and it’s on in php.ini

            I’ll check the .htaccess.

            Thanks!

          • Downloadz Portal August 15, 2012 at 8:05 am #

            Wanted to get back to you about how it went with getting APC to work properly.

            Well, I managed to get it to work by enabling Mod_Ruid2 and setting the PHP handler to DSO!

            Then, by tweaking a few settings and raising the shm_size to 256MB I managed to get it working and my site’s blazing fast now!

            Check the stats: http://ScrnSht.com/tsxbwd

            And my settings: http://ScrnSht.com/bohajh

            FYI: I’m running APC on a VPS where there are now 4 sites installed, they all use the same APC and W3TC settings. One of the sites contains about 10.000 posts, whereas the others contain 100-200. All sites are incredibly fast after I got it to work! :)

            Thanks for your info and sharing this guide! :)

  19. Brian January 5, 2013 at 5:19 pm #

    Thx for the info. I have a few questions.

    I am running a cloud server with Centos. I am using fastcgi as the handler. My server only runs a single site.

    Can I follow ur same guide to config APC?

    I am a newbie and am not 100 certain how to config APC. Would installing it with the default settings do much good?

    • Chris Gilligan January 16, 2013 at 5:21 pm #

      Default settings will probably be OK for a single site, but you should follow the tuning advice above to get best performance. You don’t want to see a ton of fragmentation… APC tends to need a memory overhead due to the fragmentation issues.

  20. Simon August 22, 2015 at 4:47 am #

    This helped me disable it server wide, very helpful!

    I can re-enable it per virtual host now, but if I change a single setting like

    apc.shm_size = 12M

    It 500’s after a restart, I’ve tried a bunch of different ways but my server does not like me over-riding the APC settings.

    Confused..

    • Chris Gilligan August 22, 2015 at 1:29 pm #

      Simon, I do not know why that would happen… check your settings. The setup I describe is somewhat specific to Virtualmin.

  21. Maxczysto December 9, 2015 at 3:35 am #

    APC works only php 5.3.3 ?

    • Chris Gilligan December 9, 2015 at 11:00 am #

      Yes, this post was written over 5 years ago, so APC cache was still current with PHP 5.3. Many web servers still run PHP 5.3; though it is dated, it is stable and is maintained in most OS repositories with back ported security patches. 5.3 is still the default PHP for many “stable” server OS. For newer sites, I’m now using PHP 5.5.x, PHP-FPM & NginX… no real need for APC.

  22. Travis June 24, 2016 at 4:45 am #

    Hello guys,

    I am having a problem with APC and APCIterator class in general. I am using APCIterator to retrieve certain items and hand it over to apc_delete($iterator) without having to flush the whole cache.

    My problem is the following: Once I created these items I can easily retrieve them using APCIterator, but after a certain amount amount of the time certain items can’t be retrieved by APCIterator anymore, they are stuck in cache and APCIterator is empty…I have absolutely no clue why and how this is happening.

    Maybe my APC settings??

    Here is a more detailed explanation of my problem:

    http://stackoverflow.com/questions/37969063/apciterator-cant-retrieve-items-after-certain-amount-of-time

    I am very thankful for any ideas on how to fix this…

    Thanks in advance

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.