Using Memcached to Reduce Database Load

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.

This entry was posted in PHP and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>