Aggressive Caching With Memcached
Sunday, August 17th, 2008There’s many different methods to use caching, with memcached. I call this one the Aggressive approach.
The basic logic is this: if you don’t even touch the database, you will be able to serve far more requests, than if you did. The biggest downside is, you can’t really do things too dynamically, and really, this only works well for flat pages (ie., it’s not for anything that displays content, based on the user).
In my case, I added the following code (shown as pseudo code) to the main/controller/dispatch script:
$memcache = new Memcache;
$memcache->connect(...);
$data = $memcache->get($_SERVER['REQUEST_URI'])
if ($data) {
echo $data;
die();
}
$db = new PDO(...);
ob_start();
ob_implicit_flush(false);
...
... do whatever ...
...
$data = ob_get_contents();
$memcache->set($_SERVER['REQUEST_URI'], $data, 0, 3600);
ob_end_flush();
One of the biggest downsides to this approach, is figuring out how to delete cached objects when something’s updated. If you have a single table that holds the pages that you’re caching, however, you can just add a hook that deletes the cached object, by URI, when anything is written that would affect it.
This really doesn’t work well for anything super dynamic, but it’s great for increasing performance in areas that would otherwise waste resources.
