MySQL replication copies writes from a primary server to one or more replica servers in real time. On a Hong Kong VPS stack, this enables read scaling (sending SELECT queries to replicas while writes go to the primary), creates a hot standby for failover, and facilitates zero-downtime backups by dumping from a replica without locking the primary. This guide covers primary-replica replication between two Hong Kong VPS instances using GTID-based replication — the modern, reliable approach.
Architecture
<code">
App servers
│
├── Writes → HK VPS Primary (10.0.0.1:3306)
│ │
│ └── Binary log replication →
│
└── Reads → HK VPS Replica (10.0.0.2:3306)
Step 1: Configure the Primary Server
<code">apt update && apt install -y mysql-server-8.0 cat >> /etc/mysql/mysql.conf.d/mysqld.cnf << 'EOF' # Replication settings — Primary server-id = 1 log_bin = /var/log/mysql/mysql-bin.log binlog_format = ROW binlog_row_image = FULL expire_logs_days = 7 # GTID mode (modern, crash-safe replication) gtid_mode = ON enforce_gtid_consistency = ON log_replica_updates = ON # Performance sync_binlog = 1 innodb_flush_log_at_trx_commit = 1 EOF systemctl restart mysql # Create replication user mysql -u root -p << 'SQL' CREATE USER 'replication'@'REPLICA_VPS_IP' IDENTIFIED BY 'StrongReplPass!'; GRANT REPLICATION SLAVE ON *.* TO 'replication'@'REPLICA_VPS_IP'; FLUSH PRIVILEGES; -- Verify GTID is on SHOW VARIABLES LIKE 'gtid_mode'; SQL
Step 2: Configure the Replica Server
<code">apt update && apt install -y mysql-server-8.0 cat >> /etc/mysql/mysql.conf.d/mysqld.cnf << 'EOF' # Replication settings — Replica server-id = 2 relay_log = /var/log/mysql/mysql-relay.log log_bin = /var/log/mysql/mysql-bin.log log_replica_updates = ON # GTID mode gtid_mode = ON enforce_gtid_consistency = ON # Read-only (prevents accidental writes to replica) read_only = ON super_read_only = ON # Performance innodb_buffer_pool_size = 512M EOF systemctl restart mysql
Step 3: Take Initial Snapshot
<code"># On the PRIMARY — export database with GTID info mysqldump -u root -p \ --all-databases \ --single-transaction \ --set-gtid-purged=ON \ --triggers \ --routines \ --events \ --hex-blob \ > /tmp/primary_dump.sql # Transfer to replica scp /tmp/primary_dump.sql root@REPLICA_IP:/tmp/ # On the REPLICA — import mysql -u root -p < /tmp/primary_dump.sql
Step 4: Start Replication
<code"># On the REPLICA mysql -u root -p << 'SQL' -- Set up connection to primary CHANGE REPLICATION SOURCE TO SOURCE_HOST='PRIMARY_VPS_IP', SOURCE_PORT=3306, SOURCE_USER='replication', SOURCE_PASSWORD='StrongReplPass!', SOURCE_AUTO_POSITION=1; -- Use GTID auto-positioning (no binlog file/pos needed) -- Start replication START REPLICA; -- Check status (should show: Replica_IO_Running: Yes, Replica_SQL_Running: Yes) SHOW REPLICA STATUS\G SQL
Verify Replication Is Working
<code"># On PRIMARY: mysql -u root -p -e "CREATE TABLE test.repl_test (id INT); INSERT INTO test.repl_test VALUES (1);" # On REPLICA (should appear within seconds): mysql -u root -p -e "SELECT * FROM test.repl_test;" # Expected output: 1 # Check replication lag mysql -u root -p -e "SHOW REPLICA STATUS\G" | grep Seconds_Behind_Source # Should be 0 (caught up) or a small number
Step 5: Route Reads to Replica
ProxySQL — Read/Write Splitting
<code">apt install -y proxysql
# Configure ProxySQL to split reads and writes
mysql -u admin -padmin -h 127.0.0.1 -P 6032 << 'SQL'
-- Add MySQL servers
INSERT INTO mysql_servers (hostgroup_id, hostname, port, weight) VALUES
(10, 'PRIMARY_IP', 3306, 1), -- Writer group (10)
(20, 'REPLICA_IP', 3306, 1); -- Reader group (20)
-- Add MySQL user
INSERT INTO mysql_users (username, password, default_hostgroup) VALUES
('app_user', 'AppPass!', 10); -- Default to writer
-- Query rules: send SELECTs to readers
INSERT INTO mysql_query_rules (rule_id, active, match_digest, destination_hostgroup, apply)
VALUES
(1, 1, '^SELECT.*FOR UPDATE', 10, 1), -- SELECT FOR UPDATE goes to writer
(2, 1, '^SELECT', 20, 1); -- All other SELECTs go to reader
LOAD MYSQL SERVERS TO RUNTIME; SAVE MYSQL SERVERS TO DISK;
LOAD MYSQL USERS TO RUNTIME; SAVE MYSQL USERS TO DISK;
LOAD MYSQL QUERY RULES TO RUNTIME; SAVE MYSQL QUERY RULES TO DISK;
SQL
Application-Level Read/Write Split
<code"># In your application — maintain two connection pools:
# Node.js (mysql2):
import mysql from 'mysql2/promise'
const writePool = mysql.createPool({ host: 'PRIMARY_IP', ...credentials })
const readPool = mysql.createPool({ host: 'REPLICA_IP', ...credentials })
// Use write pool for DML
await writePool.execute('INSERT INTO orders VALUES (...)')
// Use read pool for queries
const [rows] = await readPool.execute('SELECT * FROM products WHERE active = 1')
# Python (SQLAlchemy):
from sqlalchemy import create_engine
write_engine = create_engine('mysql+pymysql://user:pass@PRIMARY_IP/db')
read_engine = create_engine('mysql+pymysql://user:pass@REPLICA_IP/db')
Step 6: Monitor Replication Health
<code"># Monitor replication lag (run every minute via cron)
cat > /opt/check_replication.sh << 'EOF' #!/bin/bash LAG=$(mysql -h REPLICA_IP -u monitor -pMonitorPass! -e \ "SHOW REPLICA STATUS\G" 2>/dev/null | grep "Seconds_Behind_Source" | awk '{print $2}')
if [ "$LAG" = "NULL" ] || [ -z "$LAG" ]; then
echo "CRITICAL: Replication is not running!"
mail -s "MySQL Replication Down" admin@yourdomain.com <<< "Replication stopped on replica."
elif [ "$LAG" -gt 60 ]; then
echo "WARNING: Replication lag is ${LAG}s"
fi
EOF
chmod +x /opt/check_replication.sh
# Add to crontab: * * * * * /opt/check_replication.sh
Failover Procedure
<code"># If primary fails — promote replica to primary: # 1. On replica — stop replication and enable writes mysql -u root -p -e "STOP REPLICA; RESET REPLICA ALL; SET GLOBAL read_only = OFF; SET GLOBAL super_read_only = OFF;" # 2. Point all applications to the replica's IP (now acting as primary) # Update DNS or load balancer to route to former replica # 3. When original primary recovers, set it up as a replica of the new primary # (reverse the replication direction)
Conclusion
MySQL GTID replication between two Hong Kong VPS instances provides read scaling, hot standby for failover, and backup isolation in a straightforward configuration. ProxySQL transparently routes reads to the replica and writes to the primary without application code changes. Replication lag on two HK VPS nodes connected over private networking is typically under 100ms, making the replica nearly always current for read workloads. The result is a resilient database layer for any Asia-Pacific application requiring more than a single database server can provide.
Scale your database: Browse Server.HK Hong Kong VPS plans — deploy two VPS instances for primary-replica MySQL replication; private networking between HK nodes keeps replication latency minimal.