Showing posts with label Replication. Show all posts
Showing posts with label Replication. Show all posts

Sunday, February 2, 2014

Max Allowed Packet Error in MySQL Replication

 Last week one of my friend called and Ask for help. He told me he is getting below error in his MySQL setup.


 Last_IO_Error: Got fatal error 1236 from master when reading data from binary log: 'log event entry exceeded max_allowed_packet; Increase max_allowed_packet on master; the first event 'mysql_binary_log.000050' at 658752953, the last event read from '/mysql/logs/binary/mysql_binary_log.000050' at 658752953, the last byte read from '/mysql/logs/binary/mysql_binary_log.000050' at 658752972.'

The first solution of it to increase size of max_allowed_packet to start replication.   To configure this variable you need to execute below command.

Check the current Size.

mysql> show variables like 'max%allowed%';
+--------------------+---------+
| Variable_name      | Value   |
+--------------------+---------+
| max_allowed_packet | 4194304 |
+--------------------+---------+
1 row in set (0.08 sec)

mysql>

To increase size execute below commands.

mysql>
mysql> set global max_allowed_packet=41943040
    -> ;
Query OK, 0 rows affected (0.04 sec)

mysql>

Check size by login in another MySQL session.

mysql> show variables like '%allowed%'
    -> ;
+--------------------------+------------+
| Variable_name            | Value      |
+--------------------------+------------+
| max_allowed_packet       | 41943040   |
| slave_max_allowed_packet | 1073741824 |
+--------------------------+------------+
2 rows in set (0.00 sec)

mysql>

It was a simple solution to start work.  Still I was keen to know details /possible reason of this.  I asked  for some more details from him and found current bin log format is configured to “row”. In case of row based binary log size of binary log is more than from mixed/statement based logging.
In his scenario it was due to a big transection which generated 2GB log and replication stopped. Set your binlog format to mixed to avoid these situations.

Friday, July 27, 2012

Performance of MySQL Semi-Synchronous Replication

This is a blogpost by Aaron http://blog.9minutesnooze.com/performance-mysql-replication-high-latency/

I have seen a few posts on DBA.SE (where I answer a lot of questions) recommending the use of semi-synchronous replication in MySQL 5.5 over a WAN as a way to improve the reliability of replication. My gut reaction was that this is a very bad idea with even a tiny write load, but I wanted to test it out to confirm. Please note that I do not mean to disparage the author of those posts, a user whom I have great respect for.

What is semi-synchronous replication?

The short version is that one slave has to acknowledge receipt of the binary log event before the query returns. The slave doesn’t have to execute it before returning control so it’s still an asynchronous commit. The net effect is that the slave should only miss a maximum of 1 event if the master has a catastrophic failure. It does not improve the reliability of replication itself or prevent data drift.

What about performance, though? Semi-synchronous replication causes the client to block until a slave has acknowledged that it has received the event. On a LAN with sub-millisecond latencies, this should not present much of a problem. But what if there is 85ms of latency between the master and the slave, as is the case between Virginia and California? My hypothesis is that, with 85ms of latency, it is impossible to get better than 11 write queries (INSERT/UPDATE/DELETE) per second – 1000ms / 85ms = 11.7.

Let’s test that out.

I spun up identical m1.small instances in EC2′s us-east-1 and us-west-1 regions using the latest Ubuntu 12.04 LTS AMI from Alestic and installed the latest Percona Server 5.5 from their apt repository.

gpg --keyserver  hkp://keys.gnupg.net --recv-keys 1C4CBDCDCD2EFD2A

gpg -a --export CD2EFD2A | apt-key add -

echo deb http://repo.percona.com/apt precise main > /etc/apt/sources.list.d/percona.list

apt-get update

apt-get install percona-server-server-5.5 libmysqlclient-dev

Although mostly irrelevant to the benchmarks, my.cnf is configured thusly (basically identical to support-files/my-huge.cnf shipped with the distribution):

[mysqld]

port          = 3306

socket          = /var/run/mysql/mysql.sock

skip-external-locking

key_buffer_size = 384M

max_allowed_packet = 1M

table_open_cache = 512

sort_buffer_size = 2M

read_buffer_size = 2M

read_rnd_buffer_size = 8M

myisam_sort_buffer_size = 64M

thread_cache_size = 8

query_cache_size = 32M

thread_concurrency = 8



server-id     = 1

log-bin=mysql-bin

binlog_format=mixed



innodb_data_home_dir = /var/lib/mysql

innodb_data_file_path = ibdata1:2000M;ibdata2:10M:autoextend

innodb_log_group_home_dir = /var/lib/mysql

innodb_buffer_pool_size = 384M

innodb_additional_mem_pool_size = 20M

innodb_log_file_size = 100M

innodb_log_buffer_size = 8M

innodb_flush_log_at_trx_commit = 0

innodb_lock_wait_timeout = 50

Then, I wrote a very simple Ruby script to perform 10k inserts into a table, using the sequel gem, which I love.

apt-get install rubygems

gem install sequel mysql2 --no-rdoc --no-ri



#!/usr/bin/env ruby

# insertperf.rb



require 'logger'

require 'rubygems'

require 'sequel'



logger = Logger.new(STDOUT)

localdb = "inserttest"



db = Sequel.connect( :database => localdb,

                     :adapter  => 'mysql2',

                     :user     => 'root',

                     :logger   => logger )



db["DROP DATABASE IF EXISTS #{localdb}"].all

db["CREATE DATABASE #{localdb}"].all

db["CREATE TABLE IF NOT EXISTS #{localdb}.foo (

  id int unsigned AUTO_INCREMENT PRIMARY KEY,

  text VARCHAR(8)

) ENGINE=InnoDB"].all



n = 10000

t1 = Time.new

n.times do

  value = (0...8).map{65.+(rand(25)).chr}.join

  db["INSERT INTO #{localdb}.foo (text) VALUES (?)", value].insert

end

t2 = Time.new

elapsed = t2-t1

logger.info "Elapsed: #{elapsed} seconds. #{n/elapsed} qps"

With MySQL configured, let’s knock out a few INSERTs into the us-east-1 database, which has no slaves:

# w/ no slaves

...

INFO -- : (0.000179s) INSERT INTO test.foo (text) VALUES ('FKGDLOWD')

...

INFO -- : Elapsed: 9.37364 seconds. 1066.82142689499 qps

My control is roughly 1000 inserts/sec with each query taking less than .2ms.

Then, I set up a traditional, asynchronous MySQL slave on the server in us-west-1 and ran the test again:

# w/ traditional replication

...

INFO -- : (0.000237s) INSERT INTO test.foo (text) VALUES ('CVGAMLXA')

...

INFO -- : Elapsed: 10.601943 seconds. 943.223331798709 qps

Somewhat inexplicably, the performance was slightly worse with the slave attached, but not by much. ~950 inserts/sec

Next is semi-synchronous replication. First, I tested the latency between us-east-1 and us-west-1.

# ping -c 1 184.72.189.235

PING 184.72.189.235 (184.72.189.235) 56(84) bytes of data.

64 bytes from 184.72.189.235: icmp_req=1 ttl=52 time=85.5 ms

Latency between us-east-1 and us-west-1 is 85ms, so I still predict 11 inserts/sec at most, which means my script will take 15 minutes instead of 10 seconds:

I set up semi-synchronous replication like this:

master> INSTALL PLUGIN rpl_semi_sync_master SONAME 'semisync_master.so';

master> SET GLOBAL rpl_semi_sync_master_enabled = 1;

slave> INSTALL PLUGIN rpl_semi_sync_slave SONAME 'semisync_slave.so';

slave> SET GLOBAL rpl_semi_sync_slave_enabled = 1;

slave> STOP SLAVE; START SLAVE;

I started the script and, as predicted, each insert was taking approximately 85ms. There was a screaming 2 month old in the next room so in the interest of brevity, I reduced the count from 10k to 1k. That should take about 90s:

# w/ semi-sync replication

...

INFO -- : (0.086301s) INSERT INTO test.foo (text) VALUES ('JKIJTUDO')

...

INFO -- : Elapsed: 86.889529 seconds. 11.5088666207409 qps

Just as I suspected – 11 inserts/sec.

In conclusion, the speed of light is a bitch, so don’t enable semi-synchronous replication over wide area or high latency networks.

Thursday, July 19, 2012

Replicate a Database with different Name in MySQL

It happened to me   first time, so I was very excited about it until I noticed that this command has been with us from nearly the very beginning (ie MySQL 4). We need to replicate a database with different name. Was thinking it will be a big task J finally got the easy solution and working now. J

The Situation
Master Server contains db1
Slave Server contains db1 and db2
Slave Server needs db1 from the Master to replicate to db2

The Solution
On my.cnf on the slave server:
--replicate-rewrite-db=from_name->to_name

Thus, this situation would dictate the following:
--replicate-rewrite-db=db1->db2
Easy!

In replication there may be scenario like below
Part 1
What if the Master Server contained db1 and db2; and
the Slave needs only db1 from the Master to replicate to db2 on the Slave?

Part 2
We don't want to replicate both db1 and db2 to this slave, although we want to replicate both databases to another slave - this means that the filter for databases should reside on my.cnf on the slave...

Assuming that we are using replicate-rewrite-db=db1->db2:
Using replicate-do-db on the my.cnf file on the slave, which database would you use with that command?

db1 or db2?  It only takes a moment in time to find out... :)
 

Tuesday, July 3, 2012

Replication in MySQL


Replication allows databases on one MySQL server to be duplicated on another. Starting in Version 3.23.15, MySQL supports for one-way replication. One server acts as the master, while one or more other servers act as slaves. The master server keeps a binary log of updates. It also maintains the index file of binary logs to keep track of log rotation. Each slave upon connecting informs the master where it left off since the last successfully propagated update, catches up any updates that have occurred since then, and then blocks and waits for the master to notify it of new updates. When using replication, all updates to the tables that are replicated should be performed on master server.



Benefits of Replication:



q  Robustness: is increased with a master/slave setup. In the event of problems you can switch to the Slave as a backup.

q  Speed: The extra speed is achieved by splitting the load for processing client queries between master and slave servers. SELECT queries may be sent to the slave and the queries that modify data should still be sent to the master, so that master and slave to not get out of synchronization.

q  System Administration: You can get non disturbing backups of system by doing backup of slave instead of doing it on master.



Replication Implementation Overview:



MySQL replication is based on the master server keeping track of all changes to your database (updates, deletes, etc.) in the binary logs. Therefore, to use replication, you must enable binary logging on the master server. Each slave server receives from the master the saved updates that the master has recorded in its binary log, so that the slave can execute the same updates on its copy of the data. Binary log is simply a record starting from the fixed point in time at which you enable binary logging. Any slaves that you set up will need copies of the databases on your master as they existed at the moment you enabled binary logging on the master. If you start your slaves with data that is not the same as what was on the master when the binary log was started, your slaves may fail.



After the slave has been set up with a copy of the master's data, it will simply connect to the master and wait for updates to process. If the master goes away or the slave loses connectivity with your master, it will keep trying to connect periodically until it is able to reconnect and resume listening for updates. Each slave keeps track of where it left off. The master server has no knowledge of how many slaves there are or which ones are up to date at any given time.



Replication Setup:



1.    Make sure you have a recent version of MySQL installed on the master and slaves, and that these versions are compatible according to the table shown below.



Master/ Slave replication compatibility between different versions of MySQL





Master
Master
Master


3.23.33 and up
4.0.3 and up or any 4.1.x
5.0.0
Slave
3.23.33 and up
yes
no
no
Slave
4.0.3 and up
yes
yes
no
Slave
5.0.0
yes
yes
yes



But it is recommended using same version for both the master and the slave.

2.    Make sure the [mysqld] section of the `my.cnf' file on the master host includes a log-bin option. The section should also have a server-id=master_id option, where master_id must be a positive integer value from 1 to 2^32 - 1.



[mysqld]
log-bin
server-id=1



If those options are not present, add them and restart the server.



3.    Take the full database backup from Master server using option –master-data=2. Below is the command for same.



mysqldump –u –p –all-database –-master-data=2>fulldump.sql



4.    Set up an account on the master server that the slave server can use to connect. This account must be given the REPLICATION SLAVE privilege.



Suppose that your domain is mydomain.com and you want to create an account with a username of repl such that slave servers can use the account to access the master server from any host in your domain using a password of slavepass. To create the account, use GRANT statement:



mysql> GRANT REPLICATION SLAVE,REPLICATION CLIENT ON *.*
à TO repl@'%.mydomain.com' IDENTIFIED BY 'slavepass;







5.    Stop the server that is to be used as a slave server and add the following to its `my.cnf' file:



[mysqld]
server-id=2



The slave_id value, like the master_id value, must be a positive integer value from 1 to 2^32 - 1. In addition, it is very important that the ID of the slave be different than the ID of the master. If you are setting up multiple slaves, each one must have a unique server-id value that differs from that of the master and from each of the other slaves.



6.    Start the slave server.



#   mysql –u root –p





7.    Restore the database to slave using commands

mysql –u –p <

8.    Execute the following statement on the slave, replacing the values within <> with the actual values relevant to your system:



mysql> CHANGE MASTER TO
    ->    MASTER_HOST='',
    ->     MASTER_USER='',
    ->     MASTER_PASSWORD='',
    ->     MASTER_LOG_FILE='',
    ->     MASTER_LOG_POS=;



This statement creates master account on slave.





9.    Start the slave threads.



mysql> START SLAVE;





If you have forgotten to set server-id for the master, slaves will not be able to connect to it.

If you have forgotten to set server-id for the slave, you will get the following error in its error log:



Warning: one should set server_id to a non-0 value if

master_host is set.  The server will not act as a slave.



You will also find error messages in the slave's error log if it is not able to replicate for any other reason. Once a slave is replicating, you will find in its data directory one file called `master.info' and another called `relay-log.info'. The slave uses these two files to keep track of how much of the master's binary log it has processed.