www.ThimbleOpenSource.com

PHP APC expunge script


I just had a hell of a time with APC. The documentation about the TTL of user entries is poor. I am using APC for storing many things, so it grows pretty big. I was expecting that specifying TTL for each entry, let's say 300 seconds (5 minutes) would cause that entry to be deleted from APC cache when: $creation time + $TTL > time().
However that doesn't happen, the user cache entry still sits in the memory and is deleted ONLY when you try to access. This is BIG problem, when it is for example cache entry specific for user session. E.g. some cached query results, search results, etc.. APC cache keeps filling up very quickly.
The worst thing is, that when APC memory fills up, it freezes Apache process and they all just accept connections and keep waiting for free memory. The only solution is to restart Apache !. This is not good at all !

Restarting so often apache is really not good idea. So next better idea (not happy with it, but at least it works) is to keep executing script, which expunges expired user cache entries from memory. If you have same problems, feel free to use it:

<?php
$data = apc_cache_info('user');
foreach ($data['cache_list'] as $item) {
  if ($item['ttl'] + $item['creation_time'] < time()) {
    apc_delete($item['info']);
  }
}
?>