Home > mysql, PHP, scripts > Increase your website performance in under 5 seconds!

Increase your website performance in under 5 seconds!

December 16th, 2009 Leave a comment Go to comments

All websites seem to have some sort of dynamic feature which means it probably makes a backend call to a database like mysql to retrieve and display data. In my case, I have a website that displays top 20 most voted names or some other random data on front page of my website.

So every time a user hits index.php, my code makes a db call to get this statistical data. When traffic increased, my server performance took a nose dive and I had to raise mysql max connections to support the number of hits it was getting for each user visit but I was only prolonging and avoiding the issue.

So i figured, why not convert the front door to static html instead?  I renamed index.php (dyanmic version) to index2.php and wrote the following shell script:

cd /home/httpd/vhosts/<www.mywebsite.com>/httpdocs
wget -O temp.index.php --timeout=60 http://www.mywebsite.com/index2.php
if [ "`stat -c%s temp.index.php`" -gt 500 ]
    cp temp.index.php index.php
echo "Cached size too small"
exit 0

The value of ‘500’ above means if file size for temp.index.php is greater, then it’s legitimate otherwise something happened and wget failed. I saved the above script to a file named /bin/cache_main.sh.

And created a crontab entry that would republish index.php every 5 minutes:

*/5 * * * *      /bin/clear_main.sh > /dev/null 2>&1

So with the above setup, the cron runs every 5 minutes hitting index2.php (dynamic version of the site) and generates index.php, static version. Users coming in to the site always gets the index.php served which is 100% static. The data of course will be 5 minutes old but I don’t mind this trade-off at all.

It definitely beats changing code to support caching or buying new hardware to support traffic spike. You use this same method for other db intensive pages on your site just as easily.

Categories: mysql, PHP, scripts Tags:
  1. December 16th, 2009 at 13:25 | #1

    Another fab post, thanks, I love coming again to browse your blog via your twitter updates. If you are looking to give your blog more exposure and improve your ranking in the search engines you should take a look through my Web 2 Mayhem Review.

  1. No trackbacks yet.