Memcache+PHP session tuning: How does memcache expire keys?

Solution 1:

We've encountered this as well, but have managed to dig into it and work out exactly what's going on. The symptoms we encountered was that memcache (with a reasonably large memory allocation running across multiple servers) started to evict content. This is undesirable, as it can adversely affect current visitors on the site.

By monitoring network traffic, we saw messages from PHP to Memcache as follows:

set memc.sess.key.abcdabcdabcdabcdabcdabcd 0 0 1823 data...

It's the second zero that causes the problems - this dictates the length of time that memcache caches the item. By setting it to zero, memcache never expires this item. In your case this meant users could return hours later and continue accessing your site. In our case, memcache was filling up and causing desired data to be evicted.

I dug further, and it boils down to the PHP memcached extension. As of 1.0.2 (which we're running), this code reads:

sess_lifetime = zend_ini_long(ZEND_STRL("session.gc_maxlifetime"), 0);
if (sess_lifetime > 0) {
    expiration = time(NULL) + sess_lifetime;
} else {
    expiration = 0;
}

In this excerpt, it's ZEND_STRL("session.gc_maxlifetime") which isn't returning the expected value. This has been reported as a bug to PHP, and a fix to the memcached library is described at https://bugs.php.net/bug.php?id=59641.

I've deployed this patch, reviewed network traffic, and found that it does set the expiry time as expected.