What is replication in MySQL

Replication in MySQL is a process that allows data from one MySQL database server (the master) to be copied to one or more servers (the slaves). This technique is crucial for ensuring high availability, enhancing performance, and enabling backup solutions. With replication, any changes made to the master database are reflected in the slave databases, allowing for load balancing and fault tolerance.

There are several types of replication in MySQL, including:

  • Asynchronous Replication: The slave servers do not wait for the master to confirm that a change has been made, which could result in a delay in data consistency.
  • Synchronous Replication: Slaves wait for the master to confirm that the transaction has been committed, ensuring better consistency at the cost of higher latency.
  • Multi-Source Replication: Allows a single slave to replicate from multiple master servers.

Example Setup of MySQL Replication


        -- On the Master server:
        -- Step 1: Edit the MySQL configuration file (my.cnf)
        [mysqld]
        server-id=1
        log_bin=mysql-bin
        
        -- Step 2: Create a replication user
        CREATE USER 'replicator'@'%' IDENTIFIED BY 'password';
        GRANT REPLICATION SLAVE ON *.* TO 'replicator'@'%';

        -- Step 3: Obtain the binary log coordinates for the master
        FLUSH TABLES WITH READ LOCK;
        SHOW MASTER STATUS;
        -- Note down the File and Position

        -- Step 4: Unlock the tables
        UNLOCK TABLES;

        -- On the Slave server:
        -- Step 1: Edit the MySQL configuration file (my.cnf)
        [mysqld]
        server-id=2

        -- Step 2: Start replication
        CHANGE MASTER TO 
            MASTER_HOST='master_ip_address', 
            MASTER_USER='replicator', 
            MASTER_PASSWORD='password', 
            MASTER_LOG_FILE='mysql-bin.000001', 
            MASTER_LOG_POS=12345; -- Use the File and Position noted earlier

        -- Step 3: Start the slave
        START SLAVE;

        -- Step 4: Check the slave status
        SHOW SLAVE STATUS\G
        

MySQL replication database replication MySQL master-slave setup asynchronous replication synchronous replication