You have a MySQL primary and two read replicas. Your application is connecting directly to the primary for everything — every dashboard, every report query, every SELECT * FROM events ORDER BY created_at DESC LIMIT 10 that backs a feed. The primary is doing fine on writes but its buffer pool is being thrashed by reads that have nothing to do with the OLTP workload. You’d like to send reads to the replicas, but the application code is across three services in two languages and you don’t want to touch any of it. ProxySQL in front of the cluster is the answer: the application keeps connecting to one endpoint, ProxySQL inspects each query, and routes by regex to a writer host group or a reader host group — with automatic eviction of a replica that falls too far behind.
What’s happening
ProxySQL is a layer-7 MySQL proxy. It speaks the MySQL protocol on the client side and the same protocol upstream to MySQL backends. It groups backends into host groups: by convention, host group 10 is “writers”, host group 20 is “readers”. Every query the application sends gets matched against a list of query rules (regex on the SQL text); the first matching rule decides the destination host group. A rule that matches ^SELECT routes to readers, a rule that matches everything else (or that matches ^(INSERT|UPDATE|DELETE|REPLACE|BEGIN|START TRANSACTION)) routes to writers. The same connection from the application can issue a write, then a read, then a write — ProxySQL multiplexes them onto whichever backend pool is appropriate.
The pieces that interact:
mysql_servers: the inventory of backends, keyed by(hostgroup_id, hostname, port)with per-backend weight, max connections, and status.mysql_replication_hostgroups: declares “writers are HG 10, readers are HG 20”; ProxySQL polls each backend’sread_onlyflag and moves it between groups when it flips, so a Patroni or MHA-style automatic failover is reflected in the routing without operator action.mysql_query_rules: ordered list of regex patterns. Each rule has arule_id(lower = higher priority), a regex on the SQL, and a destination host group. The first match wins.mysql-monitor_writer_is_also_reader: when true, a writer is also kept in the reader pool — useful for small fleets where you don’t want the primary idle during low read load. We set it false in production because we want the primary’s buffer pool dedicated to writes.mysql_replication_hostgroups.check_type=read_only+mysql-monitor_replication_lag_interval_ms: ProxySQL polls each replica’sSeconds_Behind_Sourceand shunts a replica whose lag exceeds themax_replication_lagthreshold (per-row inmysql_servers). Default threshold is “disabled”; set it explicitly (e.g. 30 seconds) and reads automatically fall back to the writer if every replica is stale.
How to verify
Three things to check after starting ProxySQL:
-- Connect via the ADMIN interface (usually port 6032)
-- 1. Backends discovered and assigned to correct host groups
SELECT hostgroup_id, hostname, port, status, weight,
comment, max_replication_lag
FROM main.mysql_servers
ORDER BY hostgroup_id, hostname;
-- 2. Query rules in priority order
SELECT rule_id, active, match_pattern, destination_hostgroup, apply, comment
FROM main.mysql_query_rules
WHERE active = 1
ORDER BY rule_id;
-- 3. Live stats: which host group is serving which query pattern
SELECT hostgroup, schemaname, srv_host, srv_port,
Queries, Bytes_data_sent, Bytes_data_recv, Latency_us
FROM stats.stats_mysql_connection_pool
ORDER BY hostgroup, srv_host;
The third query is the one that tells you whether routing is actually happening. If Queries is zero on the reader host group, either no SELECT has been issued through ProxySQL, or your query rules don’t match. Watch the live query log briefly:
-- Enable for 60 seconds, then disable
SET mysql-eventslog_filename='/var/lib/proxysql/queries.log';
SET mysql-eventslog_default_log=1;
SAVE MYSQL VARIABLES TO RUNTIME;
-- ... wait 60s ...
SET mysql-eventslog_default_log=0;
SAVE MYSQL VARIABLES TO RUNTIME;
Then tail /var/lib/proxysql/queries.log and look for the destination_hostgroup field per query.
The fix
A minimum-viable routing configuration that handles the four cases you actually care about: read-only SELECT goes to readers; anything inside a transaction stays on the writer (consistency); explicit SELECT ... FOR UPDATE goes to the writer (locking); replicas more than 30 seconds behind get pulled from rotation automatically.
-- Run via ADMIN (6032). Replace IPs with yours.
-- 1) Declare host group topology
DELETE FROM mysql_replication_hostgroups;
INSERT INTO mysql_replication_hostgroups (writer_hostgroup, reader_hostgroup, comment)
VALUES (10, 20, 'app-cluster');
-- 2) Backends (writer + 2 readers)
DELETE FROM mysql_servers;
INSERT INTO mysql_servers (hostgroup_id, hostname, port, weight, max_replication_lag, max_connections, comment) VALUES
(10, '10.10.0.11', 3306, 1000, 0, 500, 'primary'),
(20, '10.10.0.12', 3306, 1000, 30, 500, 'replica-1'),
(20, '10.10.0.13', 3306, 1000, 30, 500, 'replica-2');
-- 3) Query rules (LOW rule_id = higher priority — match first wins)
DELETE FROM mysql_query_rules;
-- Rule 10: anything inside an explicit transaction stays on writer
INSERT INTO mysql_query_rules (rule_id, active, match_pattern, destination_hostgroup, apply, comment) VALUES
(10, 1, '^(BEGIN|START TRANSACTION|COMMIT|ROLLBACK|SAVEPOINT|RELEASE SAVEPOINT|SET autocommit)', 10, 1, 'txn control -> writer');
-- Rule 20: SELECT ... FOR UPDATE / LOCK IN SHARE MODE -> writer
INSERT INTO mysql_query_rules (rule_id, active, match_pattern, destination_hostgroup, apply, comment) VALUES
(20, 1, '^SELECT .+ (FOR UPDATE|LOCK IN SHARE MODE|FOR SHARE)', 10, 1, 'locking reads -> writer');
-- Rule 30: writes -> writer (explicit, in case the default changes)
INSERT INTO mysql_query_rules (rule_id, active, match_pattern, destination_hostgroup, apply, comment) VALUES
(30, 1, '^(INSERT|UPDATE|DELETE|REPLACE|CALL|CREATE|ALTER|DROP|TRUNCATE)', 10, 1, 'writes/DDL -> writer');
-- Rule 100: SELECT -> readers
INSERT INTO mysql_query_rules (rule_id, active, match_pattern, destination_hostgroup, apply, comment) VALUES
(100, 1, '^SELECT', 20, 1, 'reads -> readers');
-- 4) Monitor user — runs the read_only / replication_lag checks
UPDATE global_variables SET variable_value='monitor' WHERE variable_name='mysql-monitor_username';
UPDATE global_variables SET variable_value='CHANGE_ME_MONITOR' WHERE variable_name='mysql-monitor_password';
UPDATE global_variables SET variable_value=2000 WHERE variable_name='mysql-monitor_replication_lag_interval';
UPDATE global_variables SET variable_value='false' WHERE variable_name='mysql-monitor_writer_is_also_reader';
-- 5) Apply everything to runtime + disk
LOAD MYSQL SERVERS TO RUNTIME;
LOAD MYSQL QUERY RULES TO RUNTIME;
LOAD MYSQL VARIABLES TO RUNTIME;
SAVE MYSQL SERVERS TO DISK;
SAVE MYSQL QUERY RULES TO DISK;
SAVE MYSQL VARIABLES TO DISK;
The max_replication_lag=30 on replica rows is what makes this fail-safe under stress. When replica lag exceeds 30 seconds, ProxySQL marks that backend SHUNNED_REPLICATION_LAG and stops routing reads to it. If both replicas are shunned, the reader host group is empty — and ProxySQL falls back to the writer host group automatically (because the writer-also-reader relationship is configured by mysql_replication_hostgroups, even with monitor_writer_is_also_reader=false we get fallback when readers are unavailable). The application keeps serving; you get an alert from ProxySQL’s stats_mysql_query_rules or from the monitor logs that say replication lag too high, shunning server.
Three operational notes. First: the query rules above route based on the first keyword. They won’t catch a WITH ... SELECT (CTE) without an additional rule — most production rule sets add an explicit ^WITH rule. Second: any application that uses session variables (SET @user_id = 123) must use a single backend for the lifetime of those variables, which means the application should declare mysql-default_query_rules_fast_routing=1 and use a dedicated user/schema if it depends on session state. Third: read-after-write consistency is your responsibility — if a user updates their profile and then immediately reads it, the read may hit a replica that hasn’t applied the write yet. The standard pattern is to route any read inside N seconds of a write back to the writer; ProxySQL handles this via mysql_query_rules.cache_ttl for explicit caching, but for write-then-read consistency the cleanest approach is to flag the connection with a hint (/* @@ProxySQL_hostgroup=10 */) that forces it back to the writer for the next read.
For ProxySQL operated under our environment management with rule-change review, lag-threshold tuning, and Sev-1 escalation, see Cloud PaaS — or book a routing review if your current setup sends everything to the primary.