February
3rd, 2009
Caching memcached, what are you waiting for?
Caching is often looked to as a first step in making something faster. Let’s face it, complex or frequent data access is expensive. As a result, everyone and their mother manager turns to caching for a magical shot in the arm. However, an often overlooked fact is that accessing a cache isn’t a NOOP.
Memcached: It’s Comcastic!
There’s no doubt that memcached is wicked fast. It’s used heavily here at Yahoo! and Facebook uses it extensively as well. An important feature which makes memcached both scalable yet at the same time more expensive (when compared to local memory) is that it’s on the network. This ads a bit of overhead which can generally be avoided with some simple caching of memcached.
A quick example
Every scenario is different, but let’s assume that you use memcached for your session store (it may have MySql behind it but that’s irrelevant). It’s so easy to get a common piece of information like a username.
$memcachedObj->get("username-{$_COOKIE['userId']}");
Let’s say you do that 5 times on a page. Without realizing it, you’ve made 5 network calls to get the username from your ultra speedy cache. That doesn’t sound like an efficient cache store to me.
YAC (Yet Another Cache)?
I’m not suggesting you get data from memcached and then store it in a persistent local memory store. You could do that but a simple alternative is to just store it for the current process and dispose of it along with all the other data that goes along with it.
function connectToCache(){
static $memcachedObj;
if(!$memcachedObj)
$memcachedObj = memcache_connect('remote_host', 11211);
return $memcachedObj;
}
function getFromCache($key){
static $cache;
if(!$cache[$key]){
$memcachedObj = connectToCache();
$cache[$key] = $memcachedObj->get($key);
}
return $cache[$key];
}
echo getFromCache("username-{$_COOKIE['userId']}");
Wrapping it up
While the above code probably works (I didn’t actually test it), you really want to wrap this up in a nice and tiny caching class. Fortunately, I’ve gone ahead and done that for you. As part of the EpiCode PHP framework I’ve written a generic caching component with plugins for both APC and memcached.
require_once 'EpiCache.php';
$cache = EpiCache::getInstance(EpiCache::MEMCACHED);
echo $cache->get("username-{$_COOKIE['userId']}");
// or a one liner
// EpiCache::getInstance(EpiCache::MEMCACHED)->get("username-{$_COOKIE['userId']}");
Feedback
If you’ve used memcached in clever ways then post in the comments. I would like to continually improve the performance of various caches and this is just one of many methods.
and living in Sunnyvale, CA.
July 29th, 2010 at 9:11 am
[...] Mathai: Caching memcached, what are you waiting for? http://www.jaisenmathai.com/blog/2009/02/03/caching-memcached-what-are-you-waiting-for/ This entry was posted in Computers & Web Development. Bookmark the permalink. ← Olá [...]