DBAtlas · Database operations atlas

Read/write split and replica health checks with ProxySQL

MySQLRouter & Proxy

Command

-- On MySQL (source): monitor user
CREATE USER 'proxysql_mon'@'%' IDENTIFIED BY 'M0n#itor2024';
GRANT USAGE, REPLICATION CLIENT ON *.* TO 'proxysql_mon'@'%';

-- ProxySQL admin: mysql -u admin -p -h 127.0.0.1 -P 6032
UPDATE global_variables SET variable_value = 'proxysql_mon' WHERE variable_name = 'mysql-monitor_username';
UPDATE global_variables SET variable_value = 'M0n#itor2024' WHERE variable_name = 'mysql-monitor_password';
LOAD MYSQL VARIABLES TO RUNTIME; SAVE MYSQL VARIABLES TO DISK;
INSERT INTO mysql_replication_hostgroups (writer_hostgroup, reader_hostgroup, check_type, comment) VALUES (10, 20, 'read_only', 'shop');
INSERT INTO mysql_servers (hostgroup_id, hostname, port, max_replication_lag) VALUES (10, 'db1', 3306, 0), (20, 'db2', 3306, 30), (20, 'db3', 3306, 30);
LOAD MYSQL SERVERS TO RUNTIME; SAVE MYSQL SERVERS TO DISK;
INSERT INTO mysql_users (username, password, default_hostgroup, transaction_persistent) VALUES ('app', 'App#Pass2024', 10, 1);
LOAD MYSQL USERS TO RUNTIME; SAVE MYSQL USERS TO DISK;
INSERT INTO mysql_query_rules (rule_id, active, match_digest, destination_hostgroup, apply) VALUES (100, 1, '^SELECT .* FOR (UPDATE|SHARE)', 10, 1), (200, 1, '^SELECT ', 20, 1);
LOAD MYSQL QUERY RULES TO RUNTIME; SAVE MYSQL QUERY RULES TO DISK;

-- Verify
SELECT hostgroup_id, hostname, status FROM runtime_mysql_servers;
SELECT hostgroup, srv_host, status, ConnUsed, Queries, Latency_us FROM stats_mysql_connection_pool;
SELECT hostgroup, substr(digest_text, 1, 60) AS digest, count_star, sum_time / 1000 AS sum_ms FROM stats_mysql_query_digest ORDER BY sum_time DESC LIMIT 10;

What it does

Manages writer (10) and reader (20) hostgroups automatically based on the read_only flag; routes SELECTs to replicas and locking reads and writes to the source; temporarily removes a replica that exceeds max_replication_lag (SHUNNED).

When to use it

To spread read load in an async replication topology without touching the application; for connection pooling and per-query routing / caching / firewalling.

Caution

Configuration has 3 layers (MEMORY → RUNTIME → DISK): without LOAD ... TO RUNTIME nothing changes, without SAVE ... TO DISK it is lost on restart. The read_only check requires super_read_only=ON on replicas; otherwise replicas are moved into the writer hostgroup. Sending every SELECT to replicas causes read-after-write errors due to lag; writing rules only for heavy / reporting queries based on stats_mysql_query_digest is safer. The admin interface is SQLite: MySQL functions such as LEFT() do not exist, use substr(). Change the default admin:admin account (admin-admin_credentials).

Open in DBAtlas →

Related