TheRobotLearns Platform · ProxySQL: from first install to production

Prepared Query Result Cache

  • about 17 min read

Learning objectives

  • Explain prepared-query result reuse through existing query cache behavior, not a separate switch.
  • Select a narrow, frequently repeated read suitable for short-TTL reuse.
  • Configure mysql_query_rules with cache_ttl for an eligible binary prepared lookup.
  • Identify which transactional, locking, freshness, streamed, and hostgroup conditions bypass caching.
  • Verify reuse using Query_Cache_count_GET, execute counters, memory, and purge indicators.
  • Disable a rule or flush MySQL query cache when cached answers may be unsafe.

Reuse without a new switch

You want a binary prepared lookup to reuse an earlier result without a new toggle. Prepared-query result caching lets eligible binary prepared executions reuse a saved result without running the query on a backend again. This behavior caches returned rows. A saved row can answer a later eligible execution, so the backend does not run that query again.

This reuse rides on the existing query cache. It uses the query cache’s memory budget, expiration rules, and empty-result behavior. You do not turn it on with a separate switch. Existing rules with positive cache_ttl can select prepared requests after an upgrade. The result cache also sits apart from the prepared-statement metadata cache, which saves preparation work.

Review broad cache rules before upgrading, because a positive cache_ttl rule can affect prepared traffic. This result cache is experimental in published 3.1.12 and 4.0.12 prereleases. Stable 3.0.12 does not include it.

Takeaway: Ordinary cache_ttl query rules select prepared results; there is no separate prepared-cache switch.

Pick a short-lived read

An application browsing a catalog may accept a label fetched a few seconds earlier. That fits a short-TTL reuse case. Start with a frequent lookup whose answer may remain unchanged for a short period.

cache_ttl=5000 permits five seconds of reuse. It does not guarantee that backend data is no older than five seconds. A lagging replica may already return older rows.

Reading an entry does not restart its lifetime. Writes do not invalidate cached answers. If a read must see an update, it needs an uncached path. ProxySQL does not prove that a SELECT is safe to skip.

Exclude queries that depend on temporary tables, untracked session state, permissions that change their meaning, or functions with side effects. Cache only where the application’s freshness and execution requirements permit it.

Takeaway: Choose a narrow, frequent read; the TTL controls reuse, not validation or invalidation.

Rule that caches a lookup

Suppose catalog_reader reads catalog.public_labels(id, label) through MySQL’s binary prepared-statement API. Its driver prepares SELECT label FROM public_labels WHERE id = ?. A query rule can give this lookup a five-second cache life. Connect to ProxySQL Admin, choose an unused rule ID, and adapt the account, schema, and SQL spelling.

This block inserts rule 970101 into mysql_query_rules, loads it into runtime, and persists it. It excludes empty results. cache_empty_result=1 includes them; NULL uses mysql-query_cache_stores_empty_result. Check existing rule order: apply=1 ends evaluation, so this example assumes no later rule must supply another routing action. An earlier terminating rule can also prevent this rule from matching.

Use the application’s normal driver API to prepare once and execute the same lookup repeatedly with the same ID. SQL text commands such as PREPARE ... and EXECUTE ... do not exercise this binary-protocol cache.

INSERT INTO mysql_query_rules
  (rule_id, active, username, schemaname, match_pattern,
   cache_ttl, cache_empty_result, apply)
VALUES
  (970101, 1, 'catalog_reader', 'catalog',
   '^SELECT label FROM public_labels WHERE id = [?]$', 5000, 0, 1);
LOAD MYSQL QUERY RULES TO RUNTIME;
SAVE MYSQL QUERY RULES TO DISK;

Takeaway: Add a narrow rule with cache_ttl, then load and save it so prepared executions can use the query cache.

Bypasses, hits, and clears

Eligible executions use COM_STMT_EXECUTE with no cursor, iteration count one, and no pending streamed parameter data. The streamed check covers COM_STMT_SEND_LONG_DATA, including an empty streamed value.

Bypasses cover active transactions and sessions with autocommit disabled. They also cover sessions locked to a hostgroup. Rules or annotations requiring freshness constraints such as min_gtid, gtid_from_hostgroup, and max_lag_ms also bypass. Locking reads bypass too. The conservative check also bypasses SQL containing FOR or LOCK tokens in comments, strings, or identifiers.

Bypassed requests use the normal execution path. Only complete, successful, single result sets are stored. Errors and multiple results are not cached. Incomplete or already streamed responses are not cached. Command-only responses are not cached.

Read these counters in Admin before and after repeated application requests. This SELECT returns query-cache counters and statement-execute counters.

SELECT Variable_Name, Variable_Value
FROM stats_mysql_global
WHERE Variable_Name IN (
  'Query_Cache_count_GET', 'Query_Cache_count_GET_OK',
  'Query_Cache_count_SET', 'Query_Cache_Memory_bytes',
  'Query_Cache_Entries', 'Query_Cache_Purged',
  'Com_frontend_stmt_execute', 'Com_backend_stmt_execute');

GET counts lookups. GET_OK counts hits. SET counts insertions.

For an eligible, warmed lookup, frontend executes and hits increase while corresponding backend executes are avoided. If repeats miss, check rule order. Then review transaction state. Also review parameter values and types. Also review session settings and destination hostgroup.

Different encodings of equivalent values can use separate entries. Requests that match can share entries across connections. Text and binary results remain separate.

Prepared results share mysql-query_cache_size_MB with text-query results. Check memory and purges when sizing it. The budget is a soft limit. Disabling a rule does not remove stored entries. To clear saved answers immediately, run PROXYSQL FLUSH MYSQL QUERY CACHE. The flush clears the whole MySQL result cache, not one statement or parameter value. It also clears text-query entries. Flush when backend defaults change. Flush when permissions or schema semantics change. Flush when other context changes a cached answer’s meaning.

Takeaway: Use GET, GET_OK, and SET to spot reuse, then flush the MySQL query cache when changed context affects stored answers.

Warm, check, disable, and flush one catalog rule

Run this admin sequence to warm the rule, compare cache counters, disable the rule, and clear saved answers.

INSERT INTO mysql_query_rules (rule_id, active, username, schemaname, match_pattern, cache_ttl, cache_empty_result, apply) VALUES (970101, 1, 'catalog_reader', 'catalog', '^SELECT label FROM public_labels WHERE id = [?]$', 5000, 0, 1);
LOAD MYSQL QUERY RULES TO RUNTIME;
SAVE MYSQL QUERY RULES TO DISK;
SELECT Variable_Name, Variable_Value FROM stats_mysql_global WHERE Variable_Name IN ('Query_Cache_count_GET','Query_Cache_count_GET_OK','Query_Cache_count_SET','Query_Cache_Memory_bytes','Query_Cache_Entries','Query_Cache_Purged','Com_frontend_stmt_execute','Com_backend_stmt_execute');
UPDATE mysql_query_rules SET active=0 WHERE rule_id=970101;
LOAD MYSQL QUERY RULES TO RUNTIME;
SAVE MYSQL QUERY RULES TO DISK;
PROXYSQL FLUSH MYSQL QUERY CACHE;

The first INSERT creates rule 970101. It sets the rule active and gives it cache_ttl=5000. It sets cache_empty_result=0 and apply=1. The first LOAD loads the rules into runtime. The first SAVE saves the rules to disk. The SELECT returns Query_Cache_count_GET, Query_Cache_count_GET_OK, Query_Cache_count_SET, Query_Cache_Memory_bytes, Query_Cache_Entries, Query_Cache_Purged, Com_frontend_stmt_execute, and Com_backend_stmt_execute. The UPDATE sets rule 970101 inactive. The second LOAD loads the rules into runtime. The second SAVE saves the rules to disk. The FLUSH clears saved answers immediately, including text-query entries.

Try it: query_rule_playground

Create a narrow rule for a binary prepared lookup such as SELECT label FROM public_labels WHERE id = [?]. Set active=1, a short cache_ttl, cache_empty_result=0, and apply=1. Run LOAD MYSQL QUERY RULES TO RUNTIME and SAVE MYSQL QUERY RULES TO DISK. Use the application’s normal driver API to prepare once and execute the same lookup repeatedly with the same ID. Read stats_mysql_global for Query_Cache_count_GET_OK and Com_backend_stmt_execute. Then set active=0, load and save the rules, and run PROXYSQL FLUSH MYSQL QUERY CACHE.

Sources

Do more with an account

Prepared Query Result Cache — ProxySQL: from first install to production