tags:

views:

41

answers:

2

Hi all,

I want to load balance queries to 2 mysql servers, in my application.

What would be the best way to do that, so that each query goes to a different db server?

I am thinking of having a global counter which is incremented each time a connection is made, mod the counter with my db servers in order to get the host I should connect. The above process however needs to be atomic, so that no 2 requests see the same counter.

How should I go about it? Use a semaphore lock, mysql's get_lock()?

pseudo code

counter = 0
hosts = array('192.168.1.1:3306', '192.168.1.2:3306')

//the below code needs to be atomic
GET A GLOBAL LOCK
counter = counter+1
RELEASE THE LOCK

host = hosts[counter % len(hosts)]

Thanks

+1  A: 

The best way?

Use MySQL Proxy... It'll automatically compensate for down servers. Plus you can write rules that state where each query goes (either round robin choice, or to a specific server for better cache affinity). Plus, it can automatically direct all writes to the master server...

I wouldn't try implementing it in your application. The reason is that it's a lot harder to deal with global locks across multiple instances, and it's harder to have fault detection that doesn't result in a large performance hit...

ircmaxell
Hi Mysql Proxy is still beta if I am right. Anyway I need it in the application logic
Thomas
It's alpha technically. Why do you need it in the application logic? What will that do for you that using a proxy won't?
ircmaxell
It's for testing purposes. There's also HaProxy that could do the job, but for now I just want to test it in the app logic
Thomas
Well, as I said, it's going to be quite involved handling all of the edge cases. I'd personally use a lock file (using [`flock`](http://us3.php.net/manual/en/function.flock.php)) to control the counter (lock it, read and increment the counter, write the incremented number, release the lock). But beware that this can be dangerous as it is a bottleneck for your application... And why is it so important for this to be atomic? Who cares if two successive processes hit the same db server? So long as the average case is split 50-50, does it really matter?
ircmaxell
Well, I suppose that you have a point there. Thanks
Thomas
A: 

why not just go with a rand approach?

$this->read_host = $this->prod_slaves_array[rand(0,(count($this->prod_slaves_array)-1))];

advantages are that it is lockless, and though it is not completely 50/50, does it really need to be?

Jason