Load Balancing Two MySQL Servers for PHP Applications

My “research” on clustering and replication was just timely. I had to find a fix for an overloaded server. I could’ve just rewritten the code but I wanted to try something new first. I found out that a MySQL cluster needs to have at least three servers to get full redundancy. Replication was my only choice because I only have two servers for this application and the queries that are producing the most load are select queries.

MySQL replication works by having a master server where all the inserts, updates and deletes (basically any writing done) and one or more slave servers that polls the master server to replicate the database. You can only issue select queries to the slave server. You can also have multiple master servers but it won’t be covered here. You can follow this article to setup replication.

I’ll be using Round Robin to balance the load since I’ll be load balancing for a separate portion only where the same queries are used. This will equally split the load to each server (…almost). To do this in PHP, I wrote a very simple script that opens a socket. Once a host connects, it tells which database server to connect to and immediately terminates the connection.

#!/usr/bin/php -q
<?php
// Bind and listen
socket_bind($stream, "127.0.0.1",3307);
socket_listen($stream, 100);

// Define DB login credentials in an array
// host|user|passwd
$hosts = array(
0 => array('db1.dbservers.net','someuser','somepass'),
1 => array('db2.dbservers.net','anotheruser','anotherpass'),
/***** if you add another host (just follow the drift) *****/ 
// 2 => array('db3.dbservers.net','yetanotheruser','yetanotherpass') 
);

// Loop forever
while(true)
{
	// Accept anyone
	$client = socket_accept($stream);
	$key = key($hosts);
	$reply = implode($hosts[$key], "|");

	// Move internal pointer to next host
	if(next($hosts) === FALSE)
		reset($hosts);

	// Push response then kill the connection
	socket_write($client, $reply);
	socket_close($client);
}
?>

This script should be called from the command line and run like a daemon. Then we modify how we connect to the database. We connect to the “daemon” and catch the login information.

<?php
// Connect to load balancer daemon
$fp = fsockopen("localhost", 3307);

// Fallback and use some host in case of failure
if(!$fp)
{
	$host = "localhost";
	$user = "someuser";
	$pass = "somepasswd";
}
else
{
	// Get DB login information
	$packet = fgets($fp);
	$account_details = explode("|", $packet);
	$host = $account_details[0];
	$user = $account_details[1];
	$pass = $account_details[2];
}

// Connect
$link = mysql_connect($host,$user,$pass);
if(!$link)
{
	die("Fatal Error: Can't connnect to database\n");
}
mysql_select_db("somedb",$link);
?>

The code above can be improved further to check if a host is still up, give weights on the server depending on its hardware and other bells and whistles.

The beauty of this is you can safely change to another algorithm like Weighted Round Robin or Job Informed and all of the code that has to be changed is in the daemon. You may learn more on other algorithms from the paper by Dennis Haney and Klaus S. Madsen.

I’m looking into venturing to a Job Informed algorithm once the whole application uses load balancing. Queries will have weights then some form of load estimation can be achieved. Query analysis is also a possibility (based on subqueries, query type, constraints ,etc).

  • sylar

    thanks dude!

  • http://downloadfreemoviewsonlinenow.webs.com/ download movies

    Brilliant site, I hadn’t noticed blog.jploh.com earlier in my searches!
    Keep up the great work!

  • http://www.pspunlocking.com Santiago Bormes

    Am I the only one to disagree?

  • http://analsex.sexbloga.com/ Glorialivex

    Ihr habt eine schoene Webseite hier, und vielciht schaut Ihr euch auchmal meine an, ok Sex im Internet ist nicht jedermans Sache, aber eben meine erste Homepage. Danke und macht weiter so!
    [url=http://sexgirls.blogsexseite.com/[/url]

  • http://knol.google.com/k/anonymous/-/1rt0pk9erjce3/4 Baby Shower Games

    Please, get in touch with me. I’d like to talk about a possible partnership.

  • http://www.hurtowniahit.pl/ odzież używana

    Thanks for good article. Hope to see more soon.

  • http://sprintsolitaire.com play solitaire online

    Thanks for sharing this link, but unfortunately it seems to be offline… Does anybody have a mirror or another source? Please reply to my post if you do!

    I would appreciate if a staff member here at blog.jploh.com could post it.

    Thanks,
    John

  • http://www.pornblocker.biz Irwin Benedum

    I like to visit your blog a couple times a week for new readings. I was wondering if you have any other niches you write about? You’re a very interesting writer!

  • http://www.wiiunlocker.com Wii Unlock

    Hola! Nice site. I like to recommend wii unlock. Have a excellent day keep up the good work!

  • http://www.hurtowniahit.pl/ odzież używana

    Thanx for the effort, keep up the good work Great work, I am going to start a small Blog Engine course work using your site I hope you enjoy blogging with the popular BlogEngine.net.Thethoughts you express are really awesome. Hope you will right some more posts.

  • http://www.earthmagnets.net Earth Magnets

    Another one bites the dust…

  • http://www.kimkardashian.ca Kim Kardashian Sex Tape

    Can find the RSS button. I want to follow you! Please HELP!

  • http://mattresstopperbuy.com/ Ben

    hey there, this might be little offtopic, but i am hosting my site on hostgator and they will suspend my hosting in 4days, so i would like to ask you which hosting do you use or recommend?

  • http://www.pandorapsp.net PSP Pandora Battery

    This sucks. Just my 2 cents.

  • http://www.nacktefrauen.biz/ Lauren Matin

    Warum auch nicht jeder kann das so sehen wie er will. Ist der Gründonnerstag weiß, wird der Sommer sicher heiß.

  • http://www.freshsocial.com Carlene Broida

    What an idiot.

  • http://www-das.uwyo.edu arlindapar

    uncertain suggested program down

  • http://www.buy-adderall-xr.com buy adderall xr

    you told me ‘BUY Hydrocodone – DELIVERY 7 DAYS’ I received in 4 days … but the big surprise was the TOTAL quality of the product. always buy hydrocodone online is difficult because you get very poor quality but you are AMAZING!

  • Pingback: facebook clone script

  • Pingback: odzież używana

  • Pingback: Guaranteed Website Visitors