1

I have an application (php) running with MySQL 5.5 (1 master and 1 slave)

I use to dispatch read/write on master / slave.

When I create a new record (a user or something like that) I write it on the master and when I reload the page, I load it from the slave.

Example:

...
if ($_GET['id'])
{
    #Load user
    $user = $sql->load('user', $_GET['id']);

    if ($user == false)
    {
        throw exception('User not found');
    }
}
else if ($_POST['create]')
{
    #Create a new user

    $user_id = $sql->insert('user', $_POST);
    $mvc->reload('?id=' . $user_id);
    exit();
}
...

But when the master is really performant (quick insert) and the replication is not (lag = 0.3 - 1 sec), the reload will not work...

What are the best practice to handle that

Some solutions:

  • Database optimisation for reducing the lag (very difficult)
  • sleep(1) before reading or after writing ... not very elegant
1
  • 10 questions, no votes, no accepts. Check out the FAQs...
    – gbn
    Feb 3, 2012 at 8:57

1 Answer 1

1

First, you need to define if your application can work with a lag or not.

If not, then you need to ensure that the data you want to fetch are already available on slave. For example fetch the last id from slave and compare it with id you are about to fetch; or try slave first and if row is not there, fallback to master (but that will overload the master with requests for new data).

Usually web application can work with stale data. There is no problem if other visitors will see a new post 10 seconds later. But as you mentioned, it is bad if author of the post doesn't see it immediately. So you can act differently based on the data/reason you are fetching (for example cache the info about recent post in session and in that case fetch from master)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.