Using Memcached to Reduce Database Load
Filed under PHP
If you host your site on a shared server environment, then this information will not be useful for you (unless the shared server had memcached installed, which would be awesome.
If you run a large website, you probably should be offsetting your database load. One popular solution is to cache database queries to files on the server’s hardrive. This is not the best way if you are looking for near instant data read times. Memcached stores data into ram, making reading and writing the data very quick.
A simple scenario: You increment the ‘views’ field for a news post. All growing traffic causes a ton of updates which result in locking. Your site becomes slow. Memcached to the rescue!
$memcache = new Memcache;
$memcache->connect('memcache_host', 11211);
if(!$memcache->get('postxyz_123_views'))
{
//sql to grab number of views
//number expires in one hour
$memcache->set('postxyz_123_views',$view_count, 0, 3600);
}
//increment the views
$memcache->increment('postxyz_123_views');
$view_count = $memcache->get('postxyz_123_views');
All you need to do then is run a cron job every hour and have it dump the view counts to the database.
That is basically all there is to using memcached. It is very simple. If you feel adventurous, check out the php documentation for some more advanced features.
June 11th, 2008 at 5:17 pm
I found your link on pixel2life.com.
I was searching for this solution a few months ago for my dedicated server.
Great tip.
;) thanks!!
June 13th, 2008 at 11:41 pm
[...] database load, but I failed to give a sound example. Hopefully this will rectify that. Please read this post to catch up if you haven’t already. otherwise I will assume you have experience with [...]