You have a MySQL 8.0 primary in your main region and you want a read replica in a second region — different city, different provider, no shared private network. Your options were “set up a VPN” (operational overhead, another thing to monitor) or “ship the replication channel over the public internet.” The second option is fine, but it has to be done properly: TLS-only, certificate verification on both sides, connection compression so transatlantic bandwidth isn’t your bottleneck, GTID so the replica is resumable, and lag alerting that fires before your readers do. This article installs that across two Ubuntu 22.04 VMs — call them primary (region A) and replica (region B) — with the replication channel encrypted and compressed and a lag exporter that emits a Prometheus metric.
What’s happening
Cross-region replication over the public internet has four failure modes that the configuration must address:
- In-flight tampering or eavesdropping. Without TLS, anyone between you and the cloud provider can read every row change.
REQUIRE SSLon the replication user is the floor; certificate verification (REQUIRE SUBJECTorMASTER_SSL_VERIFY_SERVER_CERT=1) is what stops a man-in-the-middle who has a different certificate. - Bandwidth cost. Cross-region egress is metered. Uncompressed binlog is mostly textual SQL or row images that compress 5-10x. MySQL 8.0 supports zstd compression on the replication channel (
source_connection_compression_algorithm=zstdon the replica), which is far more efficient than the legacy zlib option. - Latency and packet loss. A transatlantic link has 80-150 ms of RTT and occasional packet loss.
slave_net_timeout(nowreplica_net_timeout) controls how long the replica waits before assuming the connection died. Default is too high; we set it to 30 seconds with automatic reconnect. - Silent lag growth. Without an exporter, lag grows undetected until reads start serving stale data.
SECONDS_BEHIND_SOURCE(the rename ofSECONDS_BEHIND_MASTERin 8.0.22+) is the metric — but it can lie under heavy write load, so we cross-check against GTID positions.
How to verify
After the installer, check from the replica side:
mysql -uroot -p -e "SHOW REPLICA STATUS\G" | grep -E \
'Replica_IO_Running|Replica_SQL_Running|Seconds_Behind_Source|Source_SSL_Allowed|Auto_Position|Compression'
You want:
Replica_IO_Running: YesReplica_SQL_Running: YesSeconds_Behind_Source: 0(or a small positive number under steady load)Source_SSL_Allowed: YesAuto_Position: 1(GTID, not file-position)Source_Connection_Compression: zstd
If Replica_IO_Running is No, the IO thread is dead — the most common cause is a TLS failure (the replica trusts a different CA than the certificate the primary presents). The error appears in the replica’s error log (/var/log/mysql/error.log); look for SSL connection error or unable to get local issuer certificate.
Confirm GTID positions are converging:
-- on the primary
SELECT @@server_uuid, @@gtid_executed;
-- on the replica
SELECT @@server_uuid, RECEIVED_TRANSACTION_SET, REPLICATED_TRANSACTION_SET
FROM performance_schema.replication_connection_status;
The primary’s gtid_executed should appear in the replica’s RECEIVED_TRANSACTION_SET within a few seconds.
The fix
Two scripts: setup-mysql-primary.sh runs on the primary; setup-mysql-replica.sh runs on the replica. They share a CA — you generate it once on the primary, then copy ca.crt, server.crt, and server.key for the replica’s server certificate, plus a replica.crt and replica.key for client-side verification on the primary. Here we put both scripts inline; you’d split them in a real runbook.
#!/usr/bin/env bash
set -euo pipefail
### PRIMARY — Ubuntu 22.04 — MySQL 8.0 for TLS + zstd replication
### Run as root.
if [[ "$(id -u)" -ne 0 ]]; then echo "Run as root."; exit 1; fi
# === EDIT ===
PRIMARY_PUBLIC_IP="203.0.113.10"
REPLICA_PUBLIC_IP="198.51.100.20"
REPL_USER="repl"
REPL_PASSWORD="CHANGE_ME_REPL"
SERVER_ID_PRIMARY="1"
# ============
echo "==> Updating base + installing MySQL 8.0"
apt-get update
DEBIAN_FRONTEND=noninteractive apt-get -y install mysql-server-8.0 \
ufw fail2ban openssl curl jq
echo "==> Hardening UFW: allow 3306 only from replica IP, deny otherwise"
ufw --force reset
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
ufw allow from ${REPLICA_PUBLIC_IP} to any port 3306 proto tcp
ufw --force enable
echo "==> fail2ban for ssh"
cat > /etc/fail2ban/jail.d/sshd.local <<'F2B'
[sshd]
enabled = true
port = ssh
maxretry = 4
findtime = 10m
bantime = 1h
F2B
systemctl enable --now fail2ban
echo "==> Generating CA + server cert + replica client cert"
CA_DIR=/etc/mysql/tls
mkdir -p ${CA_DIR}
cd ${CA_DIR}
openssl genrsa -out ca.key 4096
openssl req -x509 -new -nodes -key ca.key -days 3650 \
-subj "/CN=Stack Harbor MySQL CA" -out ca.crt
# Server cert (for the primary)
openssl genrsa -out server.key 2048
openssl req -new -key server.key \
-subj "/CN=mysql-primary" -out server.csr
openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial \
-extfile <(printf "subjectAltName=IP:${PRIMARY_PUBLIC_IP}\nextendedKeyUsage=serverAuth") \
-out server.crt -days 825 -sha256
# Client cert (for the replica)
openssl genrsa -out replica.key 2048
openssl req -new -key replica.key -subj "/CN=mysql-replica" -out replica.csr
openssl x509 -req -in replica.csr -CA ca.crt -CAkey ca.key -CAcreateserial \
-extfile <(printf "extendedKeyUsage=clientAuth") \
-out replica.crt -days 825 -sha256
chown -R mysql:mysql ${CA_DIR}
chmod 600 ${CA_DIR}/*.key
chmod 644 ${CA_DIR}/*.crt
echo "==> mysqld config: server-id, GTID, TLS, binlog"
cat > /etc/mysql/mysql.conf.d/replication.cnf <<EOF
[mysqld]
bind-address = 0.0.0.0
server-id = ${SERVER_ID_PRIMARY}
log_bin = /var/log/mysql/mysql-bin
binlog_format = ROW
binlog_row_image = FULL
gtid_mode = ON
enforce_gtid_consistency = ON
expire_logs_days = 7
max_binlog_size = 256M
sync_binlog = 1
innodb_flush_log_at_trx_commit = 1
binlog_transaction_dependency_tracking = WRITESET
# TLS
ssl_ca = ${CA_DIR}/ca.crt
ssl_cert = ${CA_DIR}/server.crt
ssl_key = ${CA_DIR}/server.key
require_secure_transport = ON
tls_version = TLSv1.2,TLSv1.3
EOF
mkdir -p /var/log/mysql
chown mysql:mysql /var/log/mysql
systemctl restart mysql
echo "==> Replication user (requires TLS + client certificate)"
mysql -uroot <<SQL
CREATE USER IF NOT EXISTS '${REPL_USER}'@'${REPLICA_PUBLIC_IP}'
IDENTIFIED BY '${REPL_PASSWORD}'
REQUIRE X509;
GRANT REPLICATION SLAVE ON *.* TO '${REPL_USER}'@'${REPLICA_PUBLIC_IP}';
FLUSH PRIVILEGES;
SHOW MASTER STATUS;
SQL
echo
echo "========================================"
echo "PRIMARY done. Files to copy to the replica:"
echo " ${CA_DIR}/ca.crt"
echo " ${CA_DIR}/replica.crt"
echo " ${CA_DIR}/replica.key"
echo "Save them in ${CA_DIR}/ on the replica before running the replica script."
echo "========================================"
Now the replica:
#!/usr/bin/env bash
set -euo pipefail
### REPLICA — Ubuntu 22.04 — MySQL 8.0 reading from primary over public internet
### Run as root AFTER copying ca.crt + replica.crt + replica.key from primary to /etc/mysql/tls/
### The primary must already be configured with the matching CA.
if [[ "$(id -u)" -ne 0 ]]; then echo "Run as root."; exit 1; fi
# === EDIT ===
PRIMARY_PUBLIC_IP="203.0.113.10"
PRIMARY_PORT="3306"
REPL_USER="repl"
REPL_PASSWORD="CHANGE_ME_REPL"
SERVER_ID_REPLICA="2"
CA_DIR=/etc/mysql/tls
# ============
if [[ ! -f ${CA_DIR}/ca.crt || ! -f ${CA_DIR}/replica.crt || ! -f ${CA_DIR}/replica.key ]]; then
echo "Missing TLS material in ${CA_DIR}. Copy ca.crt + replica.crt + replica.key from the primary."
exit 1
fi
apt-get update
DEBIAN_FRONTEND=noninteractive apt-get -y install mysql-server-8.0 \
ufw fail2ban openssl curl jq
ufw --force reset
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
ufw --force enable
chown -R mysql:mysql ${CA_DIR}
chmod 600 ${CA_DIR}/*.key
chmod 644 ${CA_DIR}/*.crt
echo "==> mysqld config: server-id, read-only, GTID, no binlog needed (single-tier replica)"
cat > /etc/mysql/mysql.conf.d/replica.cnf <<EOF
[mysqld]
server-id = ${SERVER_ID_REPLICA}
gtid_mode = ON
enforce_gtid_consistency = ON
read_only = ON
super_read_only = ON
replica_net_timeout = 30
replica_compressed_protocol = ON
binlog_transaction_dependency_tracking = WRITESET
relay_log = /var/log/mysql/relay-bin
relay_log_recovery = ON
EOF
mkdir -p /var/log/mysql
chown mysql:mysql /var/log/mysql
systemctl restart mysql
echo "==> Configuring CHANGE REPLICATION SOURCE with TLS + zstd"
mysql -uroot <<SQL
STOP REPLICA;
RESET REPLICA ALL;
CHANGE REPLICATION SOURCE TO
SOURCE_HOST = '${PRIMARY_PUBLIC_IP}',
SOURCE_PORT = ${PRIMARY_PORT},
SOURCE_USER = '${REPL_USER}',
SOURCE_PASSWORD = '${REPL_PASSWORD}',
SOURCE_AUTO_POSITION = 1,
SOURCE_SSL = 1,
SOURCE_SSL_CA = '${CA_DIR}/ca.crt',
SOURCE_SSL_CERT = '${CA_DIR}/replica.crt',
SOURCE_SSL_KEY = '${CA_DIR}/replica.key',
SOURCE_SSL_VERIFY_SERVER_CERT = 1,
SOURCE_HEARTBEAT_PERIOD = 5,
SOURCE_CONNECT_RETRY = 10,
SOURCE_RETRY_COUNT = 86400,
SOURCE_CONNECTION_AUTO_FAILOVER = 0,
SOURCE_CONNECTION_COMPRESSION_ALGORITHM = 'zstd',
SOURCE_CONNECTION_COMPRESSION_LEVEL = 3;
START REPLICA;
SQL
echo "==> Waiting for IO + SQL threads"
for i in {1..30}; do
STATUS=$(mysql -uroot -N -e "SHOW REPLICA STATUS\G")
if echo "$STATUS" | grep -qE 'Replica_IO_Running: Yes' && echo "$STATUS" | grep -qE 'Replica_SQL_Running: Yes'; then
echo "Both threads running."
break
fi
sleep 2
done
echo "==> Lag exporter (textfile)"
mkdir -p /var/lib/node_exporter/textfile
cat > /usr/local/bin/export-mysql-lag.sh <<'M'
#!/bin/bash
set -e
OUT=/var/lib/node_exporter/textfile/mysql_replica_lag.prom
TMP=$(mktemp)
LAG=$(mysql -uroot -N -e "SHOW REPLICA STATUS\G" | awk -F': ' '/Seconds_Behind_Source/{print $2; exit}')
IO=$(mysql -uroot -N -e "SHOW REPLICA STATUS\G" | awk -F': ' '/Replica_IO_Running/{print $2; exit}')
SQLT=$(mysql -uroot -N -e "SHOW REPLICA STATUS\G" | awk -F': ' '/Replica_SQL_Running/{print $2; exit}')
[[ -z "$LAG" || "$LAG" == "NULL" ]] && LAG=-1
IO_NUM=$([ "$IO" = "Yes" ] && echo 1 || echo 0)
SQL_NUM=$([ "$SQLT" = "Yes" ] && echo 1 || echo 0)
cat <<EOM >> "$TMP"
# HELP mysql_replica_seconds_behind_source Seconds behind primary (-1 if NULL)
# TYPE mysql_replica_seconds_behind_source gauge
mysql_replica_seconds_behind_source $LAG
# HELP mysql_replica_io_running 1 if IO thread is running
# TYPE mysql_replica_io_running gauge
mysql_replica_io_running $IO_NUM
# HELP mysql_replica_sql_running 1 if SQL thread is running
# TYPE mysql_replica_sql_running gauge
mysql_replica_sql_running $SQL_NUM
EOM
mv "$TMP" "$OUT"
M
chmod 755 /usr/local/bin/export-mysql-lag.sh
cat > /etc/systemd/system/mysql-replica-lag.service <<'U'
[Unit]
Description=Export MySQL replica lag
[Service]
Type=oneshot
ExecStart=/usr/local/bin/export-mysql-lag.sh
U
cat > /etc/systemd/system/mysql-replica-lag.timer <<'T'
[Unit]
Description=Run every 15s
[Timer]
OnBootSec=15
OnUnitActiveSec=15
[Install]
WantedBy=timers.target
T
systemctl daemon-reload
systemctl enable --now mysql-replica-lag.timer
echo
echo "========================================"
echo "REPLICA done."
echo "========================================"
mysql -uroot -e "SHOW REPLICA STATUS\G" | grep -E 'Replica_IO_Running|Replica_SQL_Running|Seconds_Behind_Source|Source_SSL_Allowed|Auto_Position|Source_Connection_Compression'
Run the primary script first, copy the three TLS files to the replica, edit PRIMARY_PUBLIC_IP / REPLICA_PUBLIC_IP / REPL_PASSWORD in both scripts to match, then run the replica script. The lag exporter writes a Prometheus textfile every fifteen seconds — wire mysql_replica_seconds_behind_source > 60 for 5m to your alerting and you’ll know about lag before your readers do.
Two operational notes. First: Seconds_Behind_Source lies under heavy primary write load — the replica may show zero lag because the IO thread is keeping up, while the SQL thread is twenty minutes behind. The cross-check is to compare the primary’s gtid_executed against the replica’s RECEIVED_TRANSACTION_SET and REPLICATED_TRANSACTION_SET and alert if the set difference is more than a few thousand transactions. Second: bind the replica to its private interface only if at all possible; the public IP is fine for the source-to-replica leg but the replica itself should not be reachable from the internet.
For cross-region replicas under our environment management with TLS rotation, lag SLOs, and Sev-1 escalation, we deploy and operate the channel as part of cloud compute — book a scoping call if you’re standing this up against a managed primary in the cloud.