Home›Learn›MySQL 4: high availability with InnoDB Cluster
MySQL · Chapter 4 · High availability

High availability: MySQL replication and InnoDB Cluster

Can three MySQL servers agree on every commit, so losing one loses nothing?

InnoDB Cluster is MySQL's built-in answer to failover: Group Replication to keep three servers in step, MySQL Shell to set them up, and MySQL Router to send the app to whichever one is primary.

Why this chapter matters

Why we need high availability at all

Every server fails eventually: a disk, a kernel panic, a zone outage, or just the patch you have to install on Tuesday. With one database, each of those is an outage for every customer at once. High availability turns them into a few seconds that most users never notice.

What we are protecting

Revenue and trust. Checkout, login, payments: when the database is down, the whole product is down, and nothing in the app can work around it.

What we achieve

Two numbers. RTO: how fast writes work again, seconds instead of the 15 to 30 minutes a manual failover takes. RPO: how much confirmed data a failure can lose, ideally zero.

Maintenance without downtime

The quiet win. With a spare node, patches, upgrades and hardware swaps become rolling switchovers during the day, not maintenance windows at night.

What it is not

A backup. A bad DELETE reaches every replica in milliseconds. You still need backups and point-in-time recovery.

What the targets mean in minutes

Availability targetDowntime allowed per yearPer monthWhat it takes
99.9% ("three nines")8.8 hours43.8 minutesOne server and good backups can almost do it, if nothing big breaks.
99.99% ("four nines")52.6 minutes4.4 minutesAutomatic failover. One manual 3 a.m. failover uses most of the year.
99.999% ("five nines")5.3 minutes26 secondsAutomatic failover in seconds, and maintenance with no downtime at all.

The arithmetic is why teams automate: a single manual failover at 3 a.m. can spend a whole year of a 99.99% budget.

How companies usually set it up

  1. Three nodes across three availability zones in one region, with automatic failover. This is the standard production setup; losing a zone loses one node.
  2. A replica in a second region for disaster recovery, usually asynchronous, promoted by a person or a runbook when a whole region is gone.
  3. A proxy or pooler in front, so the app has one address and never needs to know which server is primary.
  4. Backups and continuous WAL archiving to object storage, with restores tested on a schedule.
  5. Or a managed service (RDS, Aurora, Cloud SQL) that does the same three jobs for you, with less control.

Running it on thousands of servers

Nobody configures a thousand clusters by hand. At that scale, high availability is a product the database team runs, with the same few parts everywhere:

Desired state in code

Each cluster is a file in Git: size, version, replicas, settings. Terraform, Ansible or a Kubernetes operator turns the file into servers, and a pull request is how anything changes.

One failover tool, everywhere

The same Patroni (or orchestrator, or Group Replication) setup on every cluster, so a failover at 3 a.m. behaves exactly like the one you tested.

Service discovery, not hard-coded hosts

Consul, etcd or a proxy layer tells every app where the primary is right now. Failover updates one record, not a thousand config files.

Fleet automation with guardrails

Rolling patches and upgrades one node, then one cluster, at a time. Rate limits so a bad network day cannot trigger a hundred failovers at once.

Proof, not hope

Scheduled switchovers and game days that kill a primary on purpose, restore tests from backup, and dashboards that show every cluster's role, lag and last failover.

Runbooks a machine can follow

The common incidents are scripted and safe to run; the rare ones page a person with the evidence already gathered. That is the idea behind the DBA agent on this site.

Step through it: how a team patches a cluster with no downtime.

What it looks like at real companies

Now let us look at how one MySQL cluster does it, starting with plain replication, then how MySQL got from manual failovers to Group Replication.

Explained clearly

Replication lag: why the replica does not have your row yet

Listen, 2 min 52 s
1

The problem

You write a row and read it back from a replica, and it is not there. Nothing was lost. The replica has not applied the change yet.

2

What it is

At commit, the source writes the change to the binary log. On the replica, the receiver thread copies binlog events into the relay log, and applier threads replay them. Replication is asynchronous by default: the source does not wait. Lag is how far the replica's applied data is behind the source.

3

Follow one request

  1. COMMIT on the source writes the binlog.
  2. The receiver on the replica pulls the event into its relay log.
  3. An applier replays the transaction.
  4. Only now does a read on the replica see the row.

For your app: read your own writes from the source. Send to replicas only the reads that can be a little stale.

4

What to watch in production

  • One huge transaction. A 10-million-row DELETE replays as one piece, and nothing behind it applies until it is done. Delete in batches.
  • Too few appliers. replica_parallel_workers is 4 by default since 8.0.27. Busy sources often need more.
  • Tables without a primary key. With row-based replication, each row change can scan the whole table on the replica.
  • A misleading number. Seconds_Behind_Source only covers what the replica has received. A heartbeat row updated every second shows the real lag.
  • Failover. Whatever the replica had not received when the source died is lost.
SHOW REPLICA STATUS\G      -- 8.0.22+
SELECT worker_id, last_applied_transaction,
       applying_transaction, last_error_message
FROM performance_schema.replication_applier_status_by_worker;

The same idea elsewhere: PostgreSQL shows replay_lag in pg_stat_replication. MongoDB shows it with rs.printSecondaryReplicationInfo().

The idea behind it

How MySQL got here

WhenWhat changedWhat it fixed, and what it did not
Before 5.5MyISAM was the default engine.Fast reads, but no transactions, table-level locks and no crash recovery: a crash could leave tables to repair. Replication copied statements to a replica asynchronously.
5.5 (2010)InnoDB became the default engine. Semi-synchronous replication arrived.Transactions, row locks and crash recovery from the redo log. Semi-sync made the source wait until at least one replica received each commit.
2011 onMHA, then Orchestrator (2015), scripted failover.They found the most up-to-date replica, promoted it and re-pointed the others. Still outside MySQL, still at risk of split brain.
5.6 (2013)GTIDs: every transaction gets a global ID.Re-pointing replicas no longer meant finding binlog file names and positions by hand.
5.7.17 (2016)Group Replication.Servers agree on the order of every transaction before it commits. A majority must agree, so a cut-off server cannot keep writing.
2017 onInnoDB Cluster: Group Replication with MySQL Shell and MySQL Router.Setup, failover and routing as one product, instead of three tools glued with scripts.

Before Group Replication, a failover by hand looked like this: stop writes on the old source if it is reachable, compare Executed_Gtid_Set on each replica, pick the furthest, STOP REPLICA; RESET REPLICA ALL; and SET GLOBAL super_read_only = OFF, read_only = OFF on it, run CHANGE REPLICATION SOURCE TO ... SOURCE_AUTO_POSITION = 1 on the others, then move the app. Any transaction only the old source had was lost, or worse, came back later as a conflict.

Step through it:

Explained clearly

What Group Replication does

Listen, 3 min 20 s
1

The problem

With asynchronous replication, the source commits first and tells the replicas later. If it dies in between, the newest commits exist only on a dead disk, and the replica you promote never had them.

2

What it is

Group Replication joins three to nine servers into a group. When the primary commits, it sends the transaction to the group. The members agree on its order through a Paxos-based protocol, each one checks it for conflicts (certification), and only then does the commit return. A majority has to take part, so the transaction is on more than one server before your app hears OK.

3

Follow one failover

  1. db1, the primary, stops answering the group.
  2. The others suspect it after about 5 s, then wait group_replication_member_expel_timeout (5 s by default in 8.4) and expel it.
  3. The remaining majority elects a new primary: the member on the lowest MySQL version, then the highest group_replication_member_weight, then the lowest server UUID.
  4. With the 8.4 default group_replication_consistency = BEFORE_ON_PRIMARY_FAILOVER, the new primary holds new transactions until it has applied everything it received.
  5. MySQL Router sees the new primary in the cluster metadata and sends writes there.

For your app: about 10 to 20 seconds without writes, and no committed transaction lost.

4

What to watch

  • Majority or nothing. If two of three members are gone, the last one cannot reach a majority and blocks writes. That is on purpose.
  • Every table needs a primary key, and only InnoDB tables replicate. Certification compares rows by key.
  • A slow member slows everyone. Flow control throttles the primary when a member's queue grows.
  • Large transactions hurt. A huge DELETE is sent as one message to every member. Batch it.

Step through it:

Not on Group Replication? Classic source and replicas are failed over by Orchestrator. Running on Kubernetes? See MySQL on Kubernetes with the Percona operators. At fleet scale, see running 1,000 databases.

The setup

Three MySQL servers and MySQL Router

Your appone addressMySQL Router:6446 writes · :6447 readsdb1 · primaryGroup Replication memberdb2 · secondaryapplies in the same orderdb3 · secondaryapplies in the same orderchanges flowto every copy

Run Router next to the app (on each app server, or as a sidecar), not on a single separate box that becomes the new single point of failure. Three members tolerate one failure, five tolerate two.

Step by step

Set it up

  1. Install MySQL 8.4 and MySQL Shell on three hosts. Give each a unique server_id.
  2. Prepare each instance with MySQL Shell. It checks and sets what Group Replication needs (GTIDs, row-based binlog, a cluster admin account) and tells you what to restart:
mysqlsh -- dba configure-instance root@db1:3306 --clusterAdmin=clusteradmin
mysqlsh -- dba configure-instance root@db2:3306 --clusterAdmin=clusteradmin
mysqlsh -- dba configure-instance root@db3:3306 --clusterAdmin=clusteradmin
  1. Create the cluster on db1 and add the others. Clone copies the data to each new member:
mysqlsh clusteradmin@db1:3306 --js
var c = dba.createCluster('orders')
c.addInstance('clusteradmin@db2:3306', {recoveryMethod: 'clone'})
c.addInstance('clusteradmin@db3:3306', {recoveryMethod: 'clone'})
c.status()
  1. Bootstrap MySQL Router on each app host. It reads the cluster metadata and writes its own config:
mysqlrouter --bootstrap clusteradmin@db1:3306 --user=mysqlrouter
systemctl start mysqlrouter

The app connects to Router on port 6446 for writes and 6447 for reads (classic protocol). c.status() should show "status": "OK", meaning the cluster can tolerate one failure.

When it breaks

A failover, second by second

  1. 0 sdb1 loses power. Every transaction it acknowledged was already agreed by db2 and db3.
  2. about 5 sdb2 and db3 stop hearing from db1 and mark it unreachable.
  3. +5 smember_expel_timeout passes. The two remaining members, a majority, expel db1.
  4. +1 sThey elect db2 as primary. db2 applies its backlog before it accepts writes.
  5. +1 to 2 sRouter sees the change and sends new write connections to db2. Old connections to db1 fail and the app reconnects.
  6. laterdb1 restarts. With group_replication_start_on_boot on, it joins again and catches up from the others (distributed recovery). If it cannot, run c.rejoinInstance('db1:3306'). A member that was expelled while mysqld kept running retries on its own up to group_replication_autorejoin_tries (3) times, then goes to OFFLINE_MODE, the 8.4 default exit action.

A planned switchover: c.setPrimaryInstance('db2:3306'). Use it before patching the primary.

What goes wrong

What breaks, and what the cluster does

FailureWhat happensWhat you do
One member diesExpelled; if it was primary, a new one is elected.Nothing at first. c.rejoinInstance('db3:3306') when it is back.
Two of three die (no majority)The last member cannot reach a majority. Writes block.If the others are truly gone: c.forceQuorumUsingPartitionOf('db3:3306'). Only when you are sure they will not come back on their own.
All members stopped (power cut)Nobody is running Group Replication.Connect to the member with the most transactions (compare gtid_executed, or use dryRun: true) and run dba.rebootClusterFromCompleteOutage().
A member falls behindFlow control slows the primary to keep the group together.Find the cause: disk, a long query, a huge transaction.
A table without a primary keyWrites to it fail on the cluster.Add a primary key before moving to InnoDB Cluster.
Monitoring

What to watch

SELECT member_host, member_state, member_role
FROM performance_schema.replication_group_members;
SELECT member_id, count_transactions_in_queue, count_transactions_remote_in_applier_queue
FROM performance_schema.replication_group_member_stats;

Every member should be ONLINE with one PRIMARY. Alert on any member in RECOVERING for long, UNREACHABLE or ERROR, and on growing queues. In MySQL Shell, c.status() gives the same view with advice. Page playbooks: cluster lost its majority, a member in ERROR or OFFLINE.

Next · chapter 5Running it as a DBREWhat I watch, the logs, the settings, the commands← Chapter 3: What happens on every write
Part 1 of 4 · Learn · 56 pagesAll pages

How do databases actually work? From one row on disk to transactions: the words you need, PostgreSQL, MySQL and MongoDB from the files up, then Redis, Cassandra and vector search, side by side, and the query and concurrency traps.

Start 1: the basicsStart 2: ten conceptsStart 3: how a query travelsStart 4: napkin mathThe courseShort videosPostgreSQL 1: why PostgreSQLPostgreSQL 2: how it stores your dataPostgreSQL 3: what happens on every writePostgreSQL 4: high availability with PatroniPostgreSQL 5: running it as a DBREPostgreSQL 6: when it breaksPostgreSQL on Kubernetes: CloudNativePGMySQL 1: why MySQLMySQL 2: how it stores your dataMySQL 3: what happens on every writeMySQL 4: high availability with InnoDB ClusterMySQL 5: running it as a DBREMySQL 6: when it breaksMySQL failover with OrchestratorMySQL on Kubernetes: the Percona operatorsMongoDB 1: why MongoDBMongoDB 2: how it stores your dataMongoDB 3: what happens on every writeMongoDB 4: high availability with replica setsMongoDB 5: running it as a DBREMongoDB 6: when it breaksMongoDB on Kubernetes: the Percona operatorB-tree and LSM treeRedis 1: why RedisRedis 2: how it stores your dataRedis 3: high availabilityRedis 4: running it as a DBRERedis 5: when it breaksCassandra 1: why CassandraCassandra 2: how it stores your dataCassandra 3: high availabilityCassandra 4: running it as a DBRECassandra 5: when it breaksVector databases 1: why vector searchVector databases 2: how it stores your dataVector databases 3: high availabilityVector databases 4: running it as a DBREVector databases 5: when it breaksDatabase familiesEngines side by sideQueries that look fine and are notLost updates and write skewMany servers 1: keep a copy runningMany servers 2: who is the leaderMany servers 3: CAP as settingsMany servers 4: unique IDsMany servers 5: split the dataMany servers 6: across servicesMany servers 7: a thousand databasesStaff path, zero to architect