MySQL Replication and High Availability

Level: Advanced Module: Database Services 9 min read Lesson 42 of 66

Overview

  • What you’ll learn: MySQL replication concepts, asynchronous and semi-synchronous replication setup, GTID-based replication, Group Replication for multi-primary and single-primary clusters, and high-availability strategies using ProxySQL and failover mechanisms.
  • Prerequisites: Lesson 41 (MySQL Installation and Administration), familiarity with MySQL configuration files and user management
  • Estimated reading time: 25 minutes

Introduction

A single database server represents a single point of failure. If that server goes down — whether due to hardware failure, software crash, or maintenance — your application loses access to its data. Replication solves this problem by maintaining copies of data across multiple servers, while high-availability architectures ensure that failover happens automatically with minimal downtime.

MySQL offers several replication topologies, from traditional asynchronous primary-replica setups to the more modern Group Replication that provides built-in consensus and automatic failover. Understanding these options allows you to design database infrastructure that meets your availability and performance requirements.

In this lesson you will configure primary-replica replication from scratch, upgrade to GTID-based replication for easier management, explore semi-synchronous replication for stronger durability guarantees, and deploy Group Replication for automatic failover.

Replication Concepts

MySQL replication works by recording all data-modifying events on the primary server into a binary log (binlog). One or more replica servers read these events and apply them to their own copies of the data.

Binary Log Formats

MySQL supports three binary log formats:

  • STATEMENT: Logs the actual SQL statements. Compact but can produce inconsistent results for non-deterministic functions.
  • ROW: Logs the actual row changes. Larger but guarantees consistency. This is the recommended format.
  • MIXED: Uses STATEMENT by default and switches to ROW when needed.
# Check current binlog format
mysql> SHOW VARIABLES LIKE 'binlog_format';

# Set in configuration
[mysqld]
binlog_format = ROW

Replication Threads

Each replica runs two main threads:

  • I/O thread: Connects to the primary, reads binary log events, and writes them to the local relay log.
  • SQL thread: Reads events from the relay log and applies them to the replica’s database.

Asynchronous Primary-Replica Replication

In asynchronous replication, the primary does not wait for replicas to confirm that they have received or applied changes. This is the default and provides the best write performance, but there is a risk of data loss if the primary crashes before replicas have caught up.

Configuring the Primary Server

# /etc/mysql/mysql.conf.d/mysqld.cnf on the primary
[mysqld]
server-id              = 1
log_bin                = /var/log/mysql/mysql-bin
binlog_format          = ROW
binlog_expire_logs_seconds = 604800    # 7 days
max_binlog_size        = 100M
# Restart MySQL
$ sudo systemctl restart mysql

# Create a replication user
mysql> CREATE USER 'repl_user'@'10.0.1.%' IDENTIFIED BY 'R3pl_P@ssw0rd!';
mysql> GRANT REPLICATION SLAVE ON *.* TO 'repl_user'@'10.0.1.%';
mysql> FLUSH PRIVILEGES;

# Record the binary log position
mysql> SHOW MASTER STATUS;
+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000001 |      657 |              |                  |
+------------------+----------+--------------+------------------+

Configuring the Replica Server

# /etc/mysql/mysql.conf.d/mysqld.cnf on the replica
[mysqld]
server-id              = 2
relay_log              = /var/log/mysql/mysql-relay
read_only              = ON
super_read_only        = ON
# Restart MySQL
$ sudo systemctl restart mysql

# Configure the replication source
mysql> CHANGE REPLICATION SOURCE TO
       SOURCE_HOST='10.0.1.10',
       SOURCE_USER='repl_user',
       SOURCE_PASSWORD='R3pl_P@ssw0rd!',
       SOURCE_LOG_FILE='mysql-bin.000001',
       SOURCE_LOG_POS=657;

# Start replication
mysql> START REPLICA;

# Check replication status
mysql> SHOW REPLICA STATUSG
*************************** 1. row ***************************
           Replica_IO_Running: Yes
          Replica_SQL_Running: Yes
        Seconds_Behind_Source: 0

GTID-Based Replication

Global Transaction Identifiers (GTIDs) assign a unique identifier to every transaction, making it easier to track replication position and perform failover without manually specifying binary log file names and positions.

Enabling GTIDs

# Add to mysqld.cnf on BOTH primary and replica
[mysqld]
gtid_mode              = ON
enforce_gtid_consistency = ON
# On the replica, configure with GTID auto-positioning
mysql> STOP REPLICA;
mysql> CHANGE REPLICATION SOURCE TO
       SOURCE_HOST='10.0.1.10',
       SOURCE_USER='repl_user',
       SOURCE_PASSWORD='R3pl_P@ssw0rd!',
       SOURCE_AUTO_POSITION=1;
mysql> START REPLICA;

# Verify GTID replication
mysql> SHOW REPLICA STATUSG
# Look for: Retrieved_Gtid_Set and Executed_Gtid_Set

With GTIDs, promoting a replica to primary during failover is significantly simpler because each server knows exactly which transactions it has executed.

Semi-Synchronous Replication

Semi-synchronous replication provides a middle ground between asynchronous replication and full synchronous replication. The primary waits until at least one replica acknowledges receipt of the binary log events before committing the transaction to the client.

# Install the semi-sync plugins
# On the primary
mysql> INSTALL PLUGIN rpl_semi_sync_source SONAME 'semisync_source.so';
mysql> SET GLOBAL rpl_semi_sync_source_enabled = 1;
mysql> SET GLOBAL rpl_semi_sync_source_timeout = 5000;  -- 5 second timeout

# On the replica
mysql> INSTALL PLUGIN rpl_semi_sync_replica SONAME 'semisync_replica.so';
mysql> SET GLOBAL rpl_semi_sync_replica_enabled = 1;
mysql> STOP REPLICA; START REPLICA;

# Verify semi-sync status
mysql> SHOW STATUS LIKE 'Rpl_semi_sync%';

If no replica acknowledges within the timeout period, the primary falls back to asynchronous replication to avoid blocking writes indefinitely.

Group Replication

MySQL Group Replication provides a fault-tolerant, self-healing replication topology. It uses a distributed consensus protocol (based on Paxos) to ensure that all members agree on the order of transactions.

Single-Primary vs. Multi-Primary

  • Single-Primary mode: Only one member accepts writes; all others are read-only. If the primary fails, the group automatically elects a new primary. This is the recommended mode for most workloads.
  • Multi-Primary mode: All members accept writes. Conflict detection is handled by the group. This requires careful application design to avoid excessive conflicts.

Configuring Group Replication

# /etc/mysql/mysql.conf.d/mysqld.cnf (each member)
[mysqld]
server-id                         = 1    # unique per member
gtid_mode                         = ON
enforce_gtid_consistency          = ON
binlog_checksum                   = NONE
log_bin                           = /var/log/mysql/mysql-bin
binlog_format                     = ROW

# Group Replication settings
plugin_load_add                   = group_replication.so
group_replication_group_name      = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
group_replication_start_on_boot   = OFF
group_replication_local_address   = "10.0.1.10:33061"
group_replication_group_seeds     = "10.0.1.10:33061,10.0.1.11:33061,10.0.1.12:33061"
group_replication_single_primary_mode = ON
# Bootstrap the group on the first member
mysql> SET GLOBAL group_replication_bootstrap_group=ON;
mysql> START GROUP_REPLICATION;
mysql> SET GLOBAL group_replication_bootstrap_group=OFF;

# Join additional members
mysql> START GROUP_REPLICATION;

# Check group membership
mysql> SELECT * FROM performance_schema.replication_group_members;

High-Availability Architectures

ProxySQL for Connection Routing

ProxySQL is a high-performance MySQL proxy that provides connection pooling, read/write splitting, and automatic failover routing:

# Install ProxySQL
$ sudo apt install proxysql -y

# Configure backend servers via the ProxySQL admin interface
$ mysql -u admin -padmin -h 127.0.0.1 -P 6032

-- Add MySQL servers
INSERT INTO mysql_servers (hostgroup_id, hostname, port)
VALUES (10, '10.0.1.10', 3306);   -- writer
INSERT INTO mysql_servers (hostgroup_id, hostname, port)
VALUES (20, '10.0.1.11', 3306);   -- reader
INSERT INTO mysql_servers (hostgroup_id, hostname, port)
VALUES (20, '10.0.1.12', 3306);   -- reader

-- Configure read/write split rules
INSERT INTO mysql_query_rules (rule_id, active, match_pattern, destination_hostgroup)
VALUES (1, 1, '^SELECT', 20);

LOAD MYSQL SERVERS TO RUNTIME;
SAVE MYSQL SERVERS TO DISK;
LOAD MYSQL QUERY RULES TO RUNTIME;
SAVE MYSQL QUERY RULES TO DISK;

Monitoring Replication Health

# Check replication lag
mysql> SHOW REPLICA STATUSG
# Key fields:
#   Seconds_Behind_Source
#   Replica_IO_Running
#   Replica_SQL_Running

# Monitor Group Replication
mysql> SELECT MEMBER_HOST, MEMBER_STATE, MEMBER_ROLE
       FROM performance_schema.replication_group_members;

# Check for replication errors
$ sudo tail -100 /var/log/mysql/error.log | grep -i 'replication|replica|error'

Key Takeaways

  • Asynchronous replication is the simplest setup — the primary streams binary log events to replicas without waiting for acknowledgment.
  • GTID-based replication eliminates the need to track binary log file names and positions manually, simplifying failover.
  • Semi-synchronous replication provides stronger durability by requiring at least one replica to acknowledge receipt before the primary commits.
  • Group Replication provides automatic failover using distributed consensus; single-primary mode is recommended for most workloads.
  • ProxySQL adds connection pooling, read/write splitting, and automatic failover routing in front of MySQL clusters.
  • Always monitor replication lag (Seconds_Behind_Source) and ensure both I/O and SQL threads are running.

What’s Next

In Lesson 43, you will install and configure PostgreSQL on Ubuntu Server, learning its architecture, authentication system, user roles, database management, and essential administration commands.

繁體中文

概覽

  • 您將學到:MySQL 複寫概念、非同步和半同步複寫設定、基於 GTID 的複寫、群組複寫用於多主和單主叢集,以及使用 ProxySQL 和故障轉移機制的高可用性策略。
  • 先決條件:第 41 課(MySQL 安裝和管理),熟悉 MySQL 設定檔和使用者管理
  • 預估閱讀時間:25 分鐘

簡介

單一資料庫伺服器代表單一故障點。如果該伺服器宕機——無論是硬體故障、軟體崩潰還是維護——您的應用程式就會失去對資料的存取。複寫透過在多台伺服器間維護資料副本來解決此問題,而高可用性架構確保故障轉移自動發生,停機時間最小化。

MySQL 提供多種複寫拓撲,從傳統的非同步主從設定到更現代的群組複寫,後者提供內建共識和自動故障轉移。了解這些選項可以讓您設計出滿足可用性和效能要求的資料庫基礎架構。

複寫概念

MySQL 複寫的工作原理是將主伺服器上所有修改資料的事件記錄到二進位日誌(binlog)中。一台或多台從伺服器讀取這些事件並將其套用到自己的資料副本上。

二進位日誌格式

  • STATEMENT:記錄實際的 SQL 語句。緊湊但對非確定性函數可能產生不一致的結果。
  • ROW:記錄實際的行變更。較大但保證一致性。這是推薦的格式。
  • MIXED:預設使用 STATEMENT,必要時切換到 ROW。

複寫執行緒

每個從伺服器執行兩個主要執行緒:

  • I/O 執行緒:連線到主伺服器,讀取二進位日誌事件,寫入本地的中繼日誌。
  • SQL 執行緒:從中繼日誌讀取事件並將其套用到從伺服器的資料庫。

非同步主從複寫

在非同步複寫中,主伺服器不會等待從伺服器確認已收到或已套用變更。這提供了最佳的寫入效能,但如果主伺服器在從伺服器趕上之前崩潰,存在資料遺失的風險。

設定主伺服器

# 主伺服器上的 /etc/mysql/mysql.conf.d/mysqld.cnf
[mysqld]
server-id              = 1
log_bin                = /var/log/mysql/mysql-bin
binlog_format          = ROW
binlog_expire_logs_seconds = 604800
# 建立複寫使用者
mysql> CREATE USER 'repl_user'@'10.0.1.%' IDENTIFIED BY 'R3pl_P@ssw0rd!';
mysql> GRANT REPLICATION SLAVE ON *.* TO 'repl_user'@'10.0.1.%';

# 記錄二進位日誌位置
mysql> SHOW MASTER STATUS;

設定從伺服器

# 從伺服器上的設定
[mysqld]
server-id              = 2
relay_log              = /var/log/mysql/mysql-relay
read_only              = ON
# 設定複寫來源
mysql> CHANGE REPLICATION SOURCE TO
       SOURCE_HOST='10.0.1.10',
       SOURCE_USER='repl_user',
       SOURCE_PASSWORD='R3pl_P@ssw0rd!',
       SOURCE_LOG_FILE='mysql-bin.000001',
       SOURCE_LOG_POS=657;

# 啟動複寫
mysql> START REPLICA;

# 檢查複寫狀態
mysql> SHOW REPLICA STATUSG

基於 GTID 的複寫

全域交易識別碼(GTID)為每個交易分配一個唯一識別碼,使追蹤複寫位置和執行故障轉移更加容易。

# 在主伺服器和從伺服器的 mysqld.cnf 中新增
[mysqld]
gtid_mode              = ON
enforce_gtid_consistency = ON

半同步複寫

半同步複寫在非同步和完全同步之間提供了一個中間方案。主伺服器等待至少一個從伺服器確認收到二進位日誌事件後才向客戶端提交交易。

# 在主伺服器上安裝外掛
mysql> INSTALL PLUGIN rpl_semi_sync_source SONAME 'semisync_source.so';
mysql> SET GLOBAL rpl_semi_sync_source_enabled = 1;

# 在從伺服器上安裝外掛
mysql> INSTALL PLUGIN rpl_semi_sync_replica SONAME 'semisync_replica.so';
mysql> SET GLOBAL rpl_semi_sync_replica_enabled = 1;

群組複寫

MySQL 群組複寫提供容錯、自我修復的複寫拓撲。它使用分散式共識協定(基於 Paxos)確保所有成員對交易順序達成一致。

  • 單主模式:只有一個成員接受寫入;其他都是唯讀。主伺服器故障時,群組自動選舉新的主伺服器。
  • 多主模式:所有成員都接受寫入。衝突檢測由群組處理。

高可用性架構

ProxySQL 連線路由

ProxySQL 是一個高效能 MySQL 代理,提供連線池、讀寫分離和自動故障轉移路由。

重點回顧

  • 非同步複寫是最簡單的設定——主伺服器將二進位日誌事件串流到從伺服器而不等待確認。
  • 基於 GTID 的複寫消除了手動追蹤二進位日誌檔名和位置的需要,簡化了故障轉移。
  • 半同步複寫要求至少一個從伺服器確認收到後主伺服器才提交,提供更強的持久性。
  • 群組複寫使用分散式共識提供自動故障轉移;大多數工作負載推薦單主模式。
  • ProxySQL 在 MySQL 叢集前方增加連線池、讀寫分離和自動故障轉移路由。
  • 始終監控複寫延遲(Seconds_Behind_Source)並確保 I/O 和 SQL 執行緒都在執行。

下一步

在第 43 課中,您將在 Ubuntu Server 上安裝和設定 PostgreSQL,學習其架構、認證系統、使用者角色、資料庫管理和基本管理命令。

日本語

概要

  • 学習内容:MySQL レプリケーションの概念、非同期および半同期レプリケーションの設定、GTID ベースのレプリケーション、マルチプライマリおよびシングルプライマリクラスタのためのグループレプリケーション、ProxySQL とフェイルオーバーメカニズムを使用した高可用性戦略。
  • 前提条件:レッスン 41(MySQL インストールと管理)、MySQL 設定ファイルとユーザー管理の知識
  • 推定読了時間:25 分

はじめに

単一のデータベースサーバーは単一障害点です。そのサーバーがダウンすると——ハードウェア障害、ソフトウェアクラッシュ、メンテナンスのいずれであれ——アプリケーションはデータへのアクセスを失います。レプリケーションは複数のサーバー間でデータのコピーを維持することでこの問題を解決し、高可用性アーキテクチャはフェイルオーバーが最小限のダウンタイムで自動的に行われることを保証します。

MySQL は従来の非同期プライマリ・レプリカ構成から、組み込みのコンセンサスと自動フェイルオーバーを提供するより現代的なグループレプリケーションまで、複数のレプリケーショントポロジを提供しています。

レプリケーションの概念

MySQL レプリケーションは、プライマリサーバー上のすべてのデータ変更イベントをバイナリログ(binlog)に記録することで動作します。1つ以上のレプリカサーバーがこれらのイベントを読み取り、自身のデータコピーに適用します。

バイナリログ形式

  • STATEMENT:実際の SQL 文をログに記録。コンパクトだが非決定的関数で不整合が生じる可能性あり。
  • ROW:実際の行変更をログに記録。大きいが一貫性を保証。推奨形式。
  • MIXED:デフォルトは STATEMENT、必要に応じて ROW に切り替え。

レプリケーションスレッド

  • I/O スレッド:プライマリに接続し、バイナリログイベントを読み取り、ローカルのリレーログに書き込む。
  • SQL スレッド:リレーログからイベントを読み取り、レプリカのデータベースに適用する。

非同期プライマリ・レプリカレプリケーション

非同期レプリケーションでは、プライマリはレプリカが変更を受信または適用したことの確認を待ちません。最高の書き込みパフォーマンスを提供しますが、レプリカが追いつく前にプライマリがクラッシュするとデータ損失のリスクがあります。

プライマリサーバーの設定

# プライマリの /etc/mysql/mysql.conf.d/mysqld.cnf
[mysqld]
server-id              = 1
log_bin                = /var/log/mysql/mysql-bin
binlog_format          = ROW
# レプリケーションユーザーの作成
mysql> CREATE USER 'repl_user'@'10.0.1.%' IDENTIFIED BY 'R3pl_P@ssw0rd!';
mysql> GRANT REPLICATION SLAVE ON *.* TO 'repl_user'@'10.0.1.%';

# バイナリログ位置の記録
mysql> SHOW MASTER STATUS;

レプリカサーバーの設定

# レプリカの設定
[mysqld]
server-id              = 2
relay_log              = /var/log/mysql/mysql-relay
read_only              = ON
# レプリケーションソースの設定
mysql> CHANGE REPLICATION SOURCE TO
       SOURCE_HOST='10.0.1.10',
       SOURCE_USER='repl_user',
       SOURCE_PASSWORD='R3pl_P@ssw0rd!',
       SOURCE_LOG_FILE='mysql-bin.000001',
       SOURCE_LOG_POS=657;

# レプリケーションの開始
mysql> START REPLICA;

# レプリケーションステータスの確認
mysql> SHOW REPLICA STATUSG

GTID ベースのレプリケーション

グローバルトランザクション識別子(GTID)はすべてのトランザクションに一意の識別子を割り当て、レプリケーション位置の追跡とフェイルオーバーの実行を容易にします。

# プライマリとレプリカの両方の mysqld.cnf に追加
[mysqld]
gtid_mode              = ON
enforce_gtid_consistency = ON

半同期レプリケーション

半同期レプリケーションは非同期と完全同期の中間を提供します。プライマリは少なくとも1つのレプリカがバイナリログイベントの受信を確認するまで待ってからクライアントにコミットします。

# プライマリでプラグインをインストール
mysql> INSTALL PLUGIN rpl_semi_sync_source SONAME 'semisync_source.so';
mysql> SET GLOBAL rpl_semi_sync_source_enabled = 1;

# レプリカでプラグインをインストール
mysql> INSTALL PLUGIN rpl_semi_sync_replica SONAME 'semisync_replica.so';
mysql> SET GLOBAL rpl_semi_sync_replica_enabled = 1;

グループレプリケーション

MySQL グループレプリケーションはフォールトトレラントで自己修復するレプリケーショントポロジを提供します。分散コンセンサスプロトコル(Paxos ベース)を使用して、すべてのメンバーがトランザクションの順序に同意することを保証します。

  • シングルプライマリモード:1つのメンバーのみが書き込みを受け付け、他はすべて読み取り専用。プライマリが障害を起こすと、グループが自動的に新しいプライマリを選出。ほとんどのワークロードに推奨。
  • マルチプライマリモード:すべてのメンバーが書き込みを受け付け。競合検出はグループが処理。

高可用性アーキテクチャ

ProxySQL による接続ルーティング

ProxySQL は高性能な MySQL プロキシで、コネクションプーリング、読み取り/書き込み分離、自動フェイルオーバールーティングを提供します。

重要ポイント

  • 非同期レプリケーションは最もシンプルな構成——プライマリが確認を待たずにバイナリログイベントをレプリカにストリーミング。
  • GTID ベースのレプリケーションはバイナリログファイル名と位置の手動追跡を不要にし、フェイルオーバーを簡素化。
  • 半同期レプリケーションは少なくとも1つのレプリカの受信確認を要求し、より強い永続性を提供。
  • グループレプリケーションは分散コンセンサスを使用した自動フェイルオーバーを提供。ほとんどのワークロードにはシングルプライマリモードを推奨。
  • ProxySQL は MySQL クラスタの前段にコネクションプーリング、読み取り/書き込み分離、自動フェイルオーバールーティングを追加。
  • 常にレプリケーション遅延(Seconds_Behind_Source)を監視し、I/O と SQL スレッドの両方が動作していることを確認する。

次のステップ

レッスン 43 では、Ubuntu Server に PostgreSQL をインストールして設定し、そのアーキテクチャ、認証システム、ユーザーロール、データベース管理、基本的な管理コマンドを学びます。

You Missed