Replication & High Availability
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Replication copies changes from one MySQL server (the source) to others (replicas). It is the basis of read
scaling, of standby servers for failover and of delayed copies for recovery from mistakes. This page builds a source and
two replicas with GTIDs in Docker, shows what replication status looks like, and goes through semi-synchronous
replication, a delayed replica, a manual failover and a three-member Group Replication group. All of it ran on
mysql:latest (version 26.10.0) with the shop example (see
Getting Started). The one component described but not run is MySQL Router
(it is not in the server image). Backups and point-in-time recovery are in
Backup & Restore.
How asynchronous replication works
-
A transaction commits on the source and is written to the binary log.
-
A receiver (I/O) thread on each replica connects to the source, reads new events and appends them to a local relay log.
-
An applier (SQL) thread, or several coordinated worker threads, executes the relay log events on the replica.
By default the source does not wait for any replica, which is why it is asynchronous: a replica can be behind, and a committed transaction can be lost if the source fails before any replica received it. The rest of the page is about managing that gap.
Binary log formats
binlog_format decides what is recorded for a data change:
-
ROWrecords the changed row images. Deterministic and the safest, larger for statements that touch many rows. It is the default, shown here:SHOW VARIABLES LIKE 'binlog_format'returnedROW, withbinlog_row_imageFULL. -
STATEMENTrecords the SQL text. Compact, but statements with non-deterministic functions can give different results on the replica. -
MIXEDuses statements and switches to row events when a statement is unsafe.
Changing the format in a session and running an update shows the difference. This test on the source set each
format in turn (SET SESSION binlog_format = ...) before an UPDATE customers ...:
SET SESSION binlog_format = STATEMENT; Warning 1287 '@@binlog_format' is deprecated and will be removed in a future release.
SHOW BINLOG EVENTS IN 'binlog.000002' FROM 6623; (Event_type and Info, trimmed) Gtid SET @@SESSION.GTID_NEXT= '22865cd6-...:22' Query use `shop`; UPDATE customers SET tier='pro' WHERE id='c-2' <- STATEMENT Gtid SET @@SESSION.GTID_NEXT= '22865cd6-...:23' Table_map table_id: 85 (shop.customers) Update_rows table_id: 85 flags: STMT_END_F ... <- ROW Gtid SET @@SESSION.GTID_NEXT= '22865cd6-...:24' Table_map table_id: 85 (shop.customers) Update_rows table_id: 85 flags: STMT_END_F ... <- MIXED, logged as rows (unsafe statement)
Setting binlog_format is deprecated on this server, and it printed warning 1287 when changed. Treat ROW as the only
format to design for; the others exist for older topologies. In the MIXED case the UPDATE ... ORDER BY ... LIMIT
is treated as unsafe for statement logging, so the server logged row events. binlog_row_image=MINIMAL records
less for large rows, and binlog_transaction_compression (0, off, here) compresses transaction payloads.
A GTID source and replica
A global transaction identifier names each committed transaction as source_uuid:sequence. With gtid_mode=ON
(the default on this image, together with enforce_gtid_consistency=ON) a replica tells the source which GTIDs it has
already executed, and the source sends the rest. No log file names or positions to track, and promotion is simple.
The three servers share a Docker network and have distinct server_id values; the replica containers are started the
same way as the source and made read-only afterwards (super_read_only has to be switched on after initialisation, as
the image’s start-up script writes to the server):
docker network create my-b-net
docker run -d --name my-b --network my-b-net -p 33062:3306 -e MYSQL_ROOT_PASSWORD=secret mysql:latest --server-id=1
docker run -d --name my-b2 --network my-b-net -p 33063:3306 -e MYSQL_ROOT_PASSWORD=secret mysql:latest --server-id=2
docker run -d --name my-b3 --network my-b-net -p 33064:3306 -e MYSQL_ROOT_PASSWORD=secret mysql:latest --server-id=3
On the source, create the replication account and load the data:
CREATE USER 'repl'@'%' IDENTIFIED BY 'repl-pass';
GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%';
SHOW BINARY LOG STATUS;
+---------------+----------+--------------+------------------+-------------------------------------------+ | File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set | +---------------+----------+--------------+------------------+-------------------------------------------+ | binlog.000002 | 5372 | | | 22865cd6-dd3b-11f1-a41a-b281b0435263:1-17 | +---------------+----------+--------------+------------------+-------------------------------------------+
On the replica, point it at the source and start it. SOURCE_AUTO_POSITION=1 is what selects GTID-based positioning;
GET_SOURCE_PUBLIC_KEY=1 lets the caching_sha2_password account authenticate without TLS in this demo (use TLS with
SOURCE_SSL=1 for real).
SET GLOBAL super_read_only=ON;
CHANGE REPLICATION SOURCE TO
SOURCE_HOST='my-b', SOURCE_USER='repl', SOURCE_PASSWORD='repl-pass',
SOURCE_AUTO_POSITION=1, GET_SOURCE_PUBLIC_KEY=1;
START REPLICA;
SHOW REPLICA STATUS;
SHOW REPLICA STATUS returns about sixty columns. The ones that matter (output of the real replica, selected fields):
Replica_IO_State: Waiting for source to send event
Source_Host: my-b
Source_User: repl
Replica_IO_Running: Yes
Replica_SQL_Running: Yes
Seconds_Behind_Source: 0
Last_IO_Error:
Last_SQL_Error:
Source_UUID: 22865cd6-dd3b-11f1-a41a-b281b0435263
Replica_SQL_Running_State: Replica has read all relay log; waiting for more updates
Retrieved_Gtid_Set: 22865cd6-dd3b-11f1-a41a-b281b0435263:1-17
Executed_Gtid_Set: 22865cd6-dd3b-11f1-a41a-b281b0435263:1-17,
Auto_Position: 1
The replica pulled the whole history from the source’s binary log: the shop database arrived with its 8 orders and
5 products. After inserting order 1009 and a line on the source:
-- on the source
INSERT INTO orders VALUES (1009,'c-4','open','2026-04-01 10:00:00');
INSERT INTO order_items VALUES (1009,'C-3',2,39.00);
-- on the replica
SELECT id, customer_id, status FROM orders WHERE id=1009;
+------+-------------+--------+ | id | customer_id | status | +------+-------------+--------+ | 1009 | c-4 | open | +------+-------------+--------+
Writing on the read-only replica is refused, which protects the replica from diverging:
ERROR 1290 (HY000): The MySQL server is running with the --super-read-only option so it cannot execute this statement
The source lists its replicas with SHOW REPLICAS:
+-----------+------+------+-----------+--------------------------------------+ | Server_Id | Host | Port | Source_Id | Replica_UUID | +-----------+------+------+-----------+--------------------------------------+ | 2 | | 3306 | 1 | 3c0ee582-dd3b-11f1-8b55-5a9ae755ea58 | +-----------+------+------+-----------+--------------------------------------+
Lag and monitoring
Seconds_Behind_Source is the first number to watch, but it is only the timestamp difference of the event being
applied, and it is NULL when the applier is stopped. A more reliable view uses the GTID sets: whatever the replica
has retrieved but not executed is the backlog. To make lag visible, the applier thread was stopped on the replica and two
orders were inserted on the source three seconds apart:
STOP REPLICA SQL_THREAD;
-- source: INSERT order 1010, SLEEP(3), INSERT order 1011
SHOW REPLICA STATUS;
SELECT MAX(id) FROM orders;
SELECT GTID_SUBTRACT('22865cd6-dd3b-11f1-a41a-b281b0435263:1-21', @@global.gtid_executed) AS pending;
Replica_IO_Running: Yes
Replica_SQL_Running: No
Seconds_Behind_Source: NULL
Retrieved_Gtid_Set: 22865cd6-dd3b-11f1-a41a-b281b0435263:1-21
Executed_Gtid_Set: 22865cd6-dd3b-11f1-a41a-b281b0435263:1-19, ...
MAX(id) = 1009
pending = 22865cd6-dd3b-11f1-a41a-b281b0435263:20-21
The receiver had fetched everything (1-21) while the applier had executed 1-19: two transactions of lag, visible even
though Seconds_Behind_Source was NULL. After START REPLICA SQL_THREAD, the lag cleared and MAX(id) became 1011.
performance_schema gives per-stage detail, with one row per applier worker:
SELECT CHANNEL_NAME, SERVICE_STATE, LAST_ERROR_MESSAGE FROM performance_schema.replication_connection_status;
SELECT WORKER_ID, SERVICE_STATE, LAST_APPLIED_TRANSACTION FROM performance_schema.replication_applier_status_by_worker;
+--------------+---------------+--------------------+ | CHANNEL_NAME | SERVICE_STATE | LAST_ERROR_MESSAGE | +--------------+---------------+--------------------+ | | ON | | +--------------+---------------+--------------------+ +-----------+---------------+-----------------------------------------+ | WORKER_ID | SERVICE_STATE | LAST_APPLIED_TRANSACTION | +-----------+---------------+-----------------------------------------+ | 1 | ON | 22865cd6-dd3b-11f1-a41a-b281b0435263:19 | | 2 | ON | | | 3 | ON | | | 4 | ON | | +-----------+---------------+-----------------------------------------+
The usual causes of lag are a slow single-threaded applier, long transactions on the source (a replica applies them
only after commit), large row changes without a primary key, and an undersized replica. Production monitoring should
alert on Replica_IO_Running, Replica_SQL_Running, the GTID backlog and the commit-to-apply delay in
replication_applier_status_by_worker.
Multi-threaded replicas
A single applier thread cannot keep up with a busy source. On this server the replica is already multi-threaded:
replica_parallel_workers is 4 (four rows above) and replica_preserve_commit_order is 1, so transactions that committed
together on the source are applied in parallel while the commit order stays the same as on the source. The source records
the dependency information in its binary log. The settings to review are replica_parallel_workers,
replica_preserve_commit_order and replica_pending_jobs_size_max (134217728 here).
Semi-synchronous replication
Semi-synchronous replication makes the source wait, before acknowledging a commit to the client, for at least one replica to confirm it has received (not applied) the transaction in its relay log. It narrows the window in which an acknowledged transaction can exist only on a failed source. Both sides load a plugin and enable it:
-- source
INSTALL PLUGIN rpl_semi_sync_source SONAME 'semisync_source.so';
SET GLOBAL rpl_semi_sync_source_enabled = 1;
SET GLOBAL rpl_semi_sync_source_timeout = 5000;
SHOW VARIABLES LIKE 'rpl_semi_sync_source%';
-- replica (super_read_only has to be off to install a plugin)
SET GLOBAL super_read_only=OFF;
INSTALL PLUGIN rpl_semi_sync_replica SONAME 'semisync_replica.so';
SET GLOBAL rpl_semi_sync_replica_enabled = 1;
SET GLOBAL super_read_only=ON;
STOP REPLICA IO_THREAD; START REPLICA IO_THREAD;
+---------------------------------------------+------------+ | Variable_name | Value | +---------------------------------------------+------------+ | rpl_semi_sync_source_enabled | ON | | rpl_semi_sync_source_timeout | 5000 | | rpl_semi_sync_source_trace_level | 32 | | rpl_semi_sync_source_wait_for_replica_count | 1 | | rpl_semi_sync_source_wait_no_replica | ON | | rpl_semi_sync_source_wait_point | AFTER_SYNC | +---------------------------------------------+------------+
(wait_point = AFTER_SYNC is the default: the source waits after writing the binary log and before the engine commit, so
no other session can see a transaction that no replica has.) With the semi-sync plugin enabled on the source but no
semi-sync replica connected, a commit waits for the whole timeout and then falls back to asynchronous behaviour.
The source logged Timeout waiting for reply of binlog (file: binlog.000002, pos: 8110) and
Rpl_semi_sync_source_status changed to OFF. Once a replica connected with semi-sync enabled, the status did not return
to ON by itself in this test; toggling rpl_semi_sync_source_enabled off and on restored it and the next
transaction was acknowledged by the replica:
SET @t=NOW(6); INSERT INTO shop.orders VALUES (1017,'c-3','open',NOW()); SELECT TIMESTAMPDIFF(MICROSECOND,@t,NOW(6))/1000 ms; 4.7960 SHOW STATUS LIKE 'Rpl_semi_sync_source_status'; ON SHOW STATUS LIKE 'Rpl_semi_sync_source_yes_tx'; 1
Watch Rpl_semi_sync_source_status, Rpl_semi_sync_source_yes_tx and Rpl_semi_sync_source_no_tx in monitoring: a
rising no_tx means commits are no longer protected by a replica. Semi-sync trades a few milliseconds per commit for
that protection; Group Replication (below) provides stronger guarantees without a timeout fallback.
Delayed replicas
SOURCE_DELAY keeps a replica deliberately behind. If someone drops a table, the delayed copy still has it for the
length of the delay (see the recovery options in Backup & Restore). The
third server was configured with a 30 second delay (hours in practice):
CHANGE REPLICATION SOURCE TO SOURCE_HOST='my-b', SOURCE_USER='repl', SOURCE_PASSWORD='repl-pass',
SOURCE_AUTO_POSITION=1, GET_SOURCE_PUBLIC_KEY=1, SOURCE_DELAY=30;
START REPLICA;
After an INSERT of order 1018 at 19:20:15 on the source, five seconds later SHOW REPLICA STATUS on the delayed replica
reported:
Seconds_Behind_Source: 5
SQL_Delay: 30
SQL_Remaining_Delay: 26
Replica_SQL_Running_State: Waiting until SOURCE_DELAY seconds after source executed event
Retrieved_Gtid_Set: 22865cd6-dd3b-11f1-a41a-b281b0435263:1-31
Executed_Gtid_Set: 22865cd6-dd3b-11f1-a41a-b281b0435263:1-30, ...
MAX(id) was still 1017 on that replica at 19:20:20, and 1018 at 19:20:50. The event had been received and queued but
not applied; the same applier state is what you would stop (STOP REPLICA SQL_THREAD) when a disaster happens inside the
delay window, then replay the relay log up to just before the bad transaction.
Failover
A manual failover with GTIDs is a short, predictable procedure. The primary (my-b) was stopped and the first replica
reported the loss as a connection retry:
Replica_IO_Running: Connecting Last_IO_Error: Error reconnecting to source 'repl@my-b:3306'. This was attempt 1/10, with a delay of 60 seconds between attempts. ...
Promotion of my-b2: stop replication on it, discard the replica configuration, make it writable, and repoint the other
replica. Because both use GTID auto-positioning, nothing needs to be calculated:
-- on my-b2 (new source)
STOP REPLICA;
RESET REPLICA ALL;
SET GLOBAL super_read_only=OFF;
SET GLOBAL read_only=OFF;
INSERT INTO shop.orders VALUES (1019,'c-1','open',NOW());
-- on my-b3
STOP REPLICA;
CHANGE REPLICATION SOURCE TO SOURCE_HOST='my-b2', SOURCE_USER='repl', SOURCE_PASSWORD='repl-pass',
SOURCE_AUTO_POSITION=1, GET_SOURCE_PUBLIC_KEY=1, SOURCE_DELAY=0;
START REPLICA;
my-b3 then showed Source_Host: my-b2, both replication threads running, and MAX(id) 1019. The old primary was
started again, made read-only and attached as a replica of my-b2; it caught up automatically and listed order 1019.
SHOW REPLICAS on my-b2 then showed servers 1 and 3.
This is manual and relies on someone choosing the most up-to-date replica. A transaction that existed only on the failed
source (possible with asynchronous replication) is an errant GTID if the old source later contains transactions the
group lacks: compare gtid_executed before reattaching a failed server, and rebuild it from a backup if they have diverged.
Orchestration tools, and the InnoDB Cluster described below, automate the election and the redirection.
Group Replication
Group Replication makes a set of servers a replicated group with a consensus protocol (Paxos-based). A transaction commits only after a majority of members have certified it, so there is no unacknowledged-transaction window; members that fall out are expelled or recover automatically. In the default single-primary mode one member accepts writes and the others are read-only, with automatic primary election on failure. Multi-primary mode lets every member accept writes, with conflicts detected by certification.
A three-member group was formed from three fresh containers (my-b, my-b2, my-b3) started with the plugin loaded and
the group settings on the command line:
docker run -d --name my-b --network my-b-net -p 33062:3306 -e MYSQL_ROOT_PASSWORD=secret mysql:latest \
--server-id=1 --plugin-load-add=group_replication.so \
--loose-group-replication-group-name=aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee \
--loose-group-replication-local-address=my-b:3306 \
--loose-group-replication-group-seeds=my-b:3306,my-b2:3306,my-b3:3306 \
--loose-group-replication-start-on-boot=OFF
(my-b2 and my-b3 use their own names and --server-id=2/3.) On this release the default communication stack is MYSQL,
which means the group communicates over each server’s normal MySQL port (3306): a first attempt using the old XCom port
33061 in the local address failed with The group communication engine failed to test connectivity to the local group
communication engine. Every member needs a recovery account with the right privileges, created without being
written to the binary log:
SET SQL_LOG_BIN=0;
CREATE USER 'rpl_user'@'%' IDENTIFIED BY 'rpl-pass';
GRANT REPLICATION SLAVE, CONNECTION_ADMIN, BACKUP_ADMIN, GROUP_REPLICATION_STREAM ON *.* TO 'rpl_user'@'%';
SET SQL_LOG_BIN=1;
CHANGE REPLICATION SOURCE TO SOURCE_USER='rpl_user', SOURCE_PASSWORD='rpl-pass'
FOR CHANNEL 'group_replication_recovery';
(The four privileges were granted with separate GRANT statements in the test; one statement is the same.) The first member
bootstraps the group, once, and the others simply join:
-- on my-b only, once
SET GLOBAL group_replication_bootstrap_group=ON;
START GROUP_REPLICATION;
SET GLOBAL group_replication_bootstrap_group=OFF;
-- on my-b2 and my-b3
START GROUP_REPLICATION;
SELECT MEMBER_HOST, MEMBER_PORT, MEMBER_STATE, MEMBER_ROLE
FROM performance_schema.replication_group_members;
+--------------+-------------+--------------+-------------+ | MEMBER_HOST | MEMBER_PORT | MEMBER_STATE | MEMBER_ROLE | +--------------+-------------+--------------+-------------+ | 53ea9c970199 | 3306 | ONLINE | PRIMARY | | 50a2533e4396 | 3306 | ONLINE | SECONDARY | | b6a5cbfffab2 | 3306 | ONLINE | SECONDARY | +--------------+-------------+--------------+-------------+
The host names are the container identifiers. The first joins of my-b2 and my-b3 were rejected with This member has
more executed transactions than those present in the group: a new member must not hold transactions of its own, and the
Docker image’s start-up creates a few. RESET BINARY LOGS AND GTIDS on the empty joiners fixed it before they joined (only do
that on servers that hold nothing to keep).
The group behaves as a single-primary cluster. A write on a secondary is refused by super_read_only, the data
is on every member, and the member statistics show the certification counters:
-- on my-b2 (secondary) INSERT INTO orders VALUES (2000,'c-1','open',NOW()); ERROR 1290 (HY000): The MySQL server is running with the --super-read-only option so it cannot execute this statement -- on the primary INSERT INTO orders VALUES (2001,'c-1','open',NOW()); SELECT member_id, count_transactions_in_queue q, count_conflicts_detected conflicts, transactions_committed_all_members FROM performance_schema.replication_group_member_stats; member_id f7d4ca3a-... q 0 conflicts 0 committed f7d4ca3a-...:1-15 member_id f7e21d9f-... q 0 conflicts 0 committed f7d4ca3a-...:1-15 member_id f7f19c27-... q 0 conflicts 0 committed (empty at that moment) MAX(id) on my-b3: 2001
Failure and recovery: the primary container was stopped. About twenty seconds later the survivors reported a new primary,
accepted a write (order 2002) and kept the group at two members; the failed member was started again and rejoined, after
its group settings were set again (settings made with SET GLOBAL do not survive a restart), and became a secondary with
the missing data replayed through distributed recovery.
-- after stopping my-b my-b2 ONLINE PRIMARY my-b3 ONLINE SECONDARY -- after my-b restarted and rejoined my-b ONLINE SECONDARY (MAX(id) = 2002, super_read_only = 1) my-b2 ONLINE PRIMARY my-b3 ONLINE SECONDARY
A planned switchover is a function call, accepted by any member:
SELECT group_replication_set_as_primary('f7d4ca3a-dd3b-11f1-bfe9-6247c3418efb');
Primary server switched to: f7d4ca3a-dd3b-11f1-bfe9-6247c3418efb
Points to design for: a group needs an odd number of members, a majority (two of three) to keep working, and every table needs a
primary key. Latency between members affects commit time. Consistency of reads from secondaries is governed by
group_replication_consistency (here BEFORE_ON_PRIMARY_FAILOVER); AFTER and BEFORE_AND_AFTER trade latency for
read-your-writes on any member.
InnoDB Cluster and MySQL Router
InnoDB Cluster is Group Replication managed as one product. Three components work together:
-
Group Replication provides the replicated data and the election.
-
MySQL Shell (
mysqlsh, shipped in this image) provides the AdminAPI:dba.createCluster(),cluster.addInstance(),cluster.status(),cluster.setPrimaryInstance(), which configure the members, the recovery accounts and the metadata for you instead of the manual steps above. -
MySQL Router is a lightweight proxy applications connect to, which learns the cluster topology from its metadata and routes connections. Read/write traffic (typically port 6446) goes to the primary, read-only traffic (6447) is balanced across secondaries, so applications do not change when the primary moves.
The cluster commands and the Router bootstrap (mysqlrouter --bootstrap) are described here and not executed: the Router is
not part of the server image. The Group Replication layer underneath is the part demonstrated above. A related option for
disaster recovery is InnoDB ClusterSet, linking clusters in two data centres, and InnoDB ReplicaSet for a simpler
asynchronous topology managed by the same AdminAPI.
Read/write splitting
Replicas make read scaling possible, but the application, or a proxy, has to send the reads there. The basic options:
-
Application-level: two data sources, one for writes, one (or a pool) for reads, chosen per transaction. Simplest, and explicit about which queries tolerate stale data.
-
Router or proxy: MySQL Router with its two ports, or ProxySQL, which can route by rules or user and also pools connections. See Performance Tuning for connection handling.
-
Driver-level: MySQL Connector/J and others support replication-aware URLs (
jdbc:mysql:replication://...) and read-only transactions routed to replicas.
Rules for correctness: reads that must see the writer’s own changes (read-your-writes) go to the source, or wait
for the replica to catch up (WAIT_FOR_EXECUTED_GTID_SET('gtid', timeout) blocks until a replica has applied a GTID);
reports, search and exports go to replicas; and never let the application write to a replica, which is why they run with
super_read_only.
Operational checklist
-
Use GTIDs and
SOURCE_AUTO_POSITION=1; keepserver_idandserver_uuidunique per server. -
Run replicas
super_read_only, with their own backups, and TLS on the replication channel. -
Monitor both threads, the GTID backlog and commit-to-apply delay, and the disk used by binary and relay logs.
-
Keep binary logs for as long as the slowest replica or restore needs (see Administration for purging).
-
Rehearse failover, including bringing the old primary back; check for errant transactions before reattaching it.
-
For automatic failover choose Group Replication / InnoDB Cluster over hand-written scripts.
Next: Performance Tuning. See also the MySQL Reference.