SQL throttling

Updated at:

SQL throttling limits the execution of problematic SQL statements on compute nodes. Use throttling rules to protect your PolarDB-X instance during request spikes, excessive resource consumption, or unexpected changes in SQL access patterns. Throttling rules are defined using CCL statements.

Supported versions

SQL throttling requires PolarDB-X Enterprise Edition instances with compute node version 5.4.9-16167266 or later.

Slow SQL throttling trigger requires compute node version 5.4.11-16251897 or later.

For version naming conventions, see Release notes. To check your current version, see View and update the version of an instance.

Create a throttling rule

Syntax

CREATE CCL_RULE [ IF NOT EXISTS ] `ccl_rule_name`
ON `database`.`table`
TO '<username>'@'<host>'
FOR { UPDATE | SELECT | INSERT | DELETE }
[ filter_options ]
with_options

filter_options:
    [ FILTER  BY KEYWORD('KEYWORD1', 'KEYWORD2',...) ]

Match parameters

These parameters determine which SQL statements the rule targets.

ParameterRequiredDescription
ccl_rule_nameYesRule name. Enclose in backticks (` ``) to avoid conflicts with SQL keywords.
` database.table `YesDatabase and table name. Use asterisks (*) as wildcards. Enclose each name in backticks.
'<username>'@'<host>'YesAccount username. Use % as a wildcard in the host part.
UPDATE &#124; SELECT &#124; INSERT &#124; DELETEYesSQL statement type. Each rule applies to one type only.
filter_optionsNoFilter conditions. See the following section.

Filter options

  • KEYWORD -- Matches SQL statements that contain the specified keywords. Keywords appear as a JSON string ["kwd1","kw2","kw3"...] in query results. The string has a maximum of 512 characters.

    • If a keyword matches a parameter value: matching is case-sensitive.

    • If a keyword matches any other part of the statement: matching is case-insensitive.

  • TEMPLATE -- The SQL template ID: a 16-bit hexadecimal hash of the parameterized SQL statement. This corresponds to the sql_code field in SQL logs. Run SHOW FULL PROCESSLIST or EXPLAIN to find the template ID.

WITH clause parameters

The WITH clause controls how matched statements are throttled. Specify at least one parameter.

ParameterRangeDefaultDescription
MAX_CONCURRENCY0 to 2^31 - 10Maximum concurrent matching statements allowed. The default value of 0 rejects every matching statement with an error.
WAIT_QUEUE_SIZE0 to 2^31 - 10Maximum queue length. When concurrency reaches the limit, additional statements enter this queue. When the queue is full, new statements are rejected. Large queues can cause out-of-memory (OOM) errors.
WAIT_TIMEOUT0 to 2^31 - 1600Maximum wait time in the queue, in seconds. Statements that exceed this duration are rejected.
FAST_MATCH0 or 1--Enables caching for faster rule matching. When set to 1, the system uses the template ID as a cache key.
Note

WITH clause parameters apply only to statements that match all match parameters in the rule.

Note

PolarDB-X is a distributed database. Each compute node enforces concurrency limits independently. The total instance concurrency equals the sum of each node's MAX_CONCURRENCY value. If loads across nodes are unbalanced, the instance may not reach its theoretical maximum.

Example

Create a rule named selectrule that limits SELECT statements from the ccltest user (any host) containing the keyword cclmatched to a maximum concurrency of 10:

CREATE CCL_RULE IF NOT EXISTS `selectrule` ON *.* TO 'ccltest'@'%'
FOR SELECT
FILTER BY KEYWORD('cclmatched')
WITH MAX_CONCURRENCY=10;

After this rule takes effect, SELECT statements from the ccltest account that contain the keyword cclmatched are limited to 10 concurrent executions.

Throttling behavior

When a matching SQL statement is detected, it enters one of four states based on the WITH clause parameters:

RUN

If concurrent matching statements have not reached MAX_CONCURRENCY, the statement runs normally.

WAIT

If concurrency has reached MAX_CONCURRENCY but the queue has not reached WAIT_QUEUE_SIZE, the statement enters the queue. It transitions to RUN when a slot opens, or to WAIT_TIMEOUT if the wait time is exceeded.

To view queued statements, run:

SHOW FULL PROCESSLIST;

Sample output:

+----+---------------+-----------------+----------+-------------------------------+------+-------+-----------------------+-----------------+
| ID | USER          | HOST            | DB       | COMMAND                       | TIME | STATE | INFO                  | SQL_TEMPLATE_ID |
+----+---------------+-----------------+----------+-------------------------------+------+-------+-----------------------+-----------------+
|  2 | polardbx_root | ***.*.*.*:62787 | polardbx | Query                         |    0 |       | show full processlist | NULL            |
|  1 | polardbx_root | ***.*.*.*:62775 | polardbx | Query(Waiting-selectrulereal) |   12 |       | select 1              | 9037e5e2        |
+----+---------------+-----------------+----------+-------------------------------+------+-------+-----------------------+-----------------+
2 rows in set (0.08 sec)

In this output, select 1 matches the selectrulereal rule and is waiting in the queue.

WAIT_TIMEOUT

A queued statement that exceeds the WAIT_TIMEOUT duration fails with an error.

For example, with WAIT_TIMEOUT set to 10 seconds:

ERROR 3009 (HY000): [11a07e23fd800000][30.225.XXX.XX:8527][polardbx]Exceeding the max concurrency 0 of ccl rule selectrulereal after waiting for 10060 ms

KILL

If both MAX_CONCURRENCY and WAIT_QUEUE_SIZE limits are reached, the statement is rejected immediately.

For example:

ERROR 3009 (HY000): [11a07c4425c00000][**.***.***.**:8527][polardbx]Exceeding the max concurrency 0 of ccl rule selectrulereal

Query throttling rules

To view specific rules, specify rule names separated by commas:

SHOW CCL_RULE `ccl_rule_name1` [, `ccl_rule_name2` ]

Example:

SHOW CCL_RULE `selectrulereal`

Sample output:

                     NO.: 1
               RULE_NAME: selectrulereal
                 RUNNING: 2
                 WAITING: 29
                  KILLED: 0
         MATCH_HIT_CACHE: 21374
             TOTAL_MATCH: 21406
       ACTIVE_NODE_COUNT: 2
MAX_CONCURRENCY_PER_NODE: 1
WAIT_QUEUE_SIZE_PER_NODE: 100
            WAIT_TIMEOUT: 600
              FAST_MATCH: 1
                SQL_TYPE: SELECT
                    USER: ccltest@%
                   TABLE: *.*
                KEYWORDS: ["SELECT"]
              TEMPLATEID: NULL
            CREATED_TIME: 2020-11-26 17:04:08

Output fields

FieldDescription
NO.Rule priority. Lower values indicate higher priority.
RULE_NAMEThrottling rule name.
RUNNINGMatching statements currently running.
WAITINGMatching statements in the queue.
KILLEDMatching statements that were rejected.
MATCH_HIT_CACHEMatches resolved through the template ID cache.
TOTAL_MATCHTotal times this rule was matched.
ACTIVE_NODE_COUNTCompute nodes where this rule is active.
MAX_CONCURRENCY_PER_NODEMaximum concurrency per compute node.
WAIT_QUEUE_SIZE_PER_NODEMaximum queue length per compute node.
WAIT_TIMEOUTMaximum queue wait time, in seconds.
FAST_MATCHWhether cache-accelerated matching is enabled.
SQL_TYPESQL statement type: SELECT, UPDATE, INSERT, or DELETE.
USERUsername the rule applies to.
TABLEDatabase and table the rule applies to.
KEYWORDSKeyword list for matching.
TEMPLATEIDSQL template ID for matching.
CREATED_TIMERule creation time, in yyyy-MM-dd HH:mm:ss format.

Query all rules

SHOW CCL_RULES;

Delete throttling rules

When a rule is deleted, it becomes invalid immediately. Any queued SQL statements are released and run normally.

To delete specific rules, specify rule names separated by commas:

DROP CCL_RULE [ IF EXISTS ] `ccl_rule_name1` [, `ccl_rule_name2`, ...]

Example:

DROP CCL_RULE IF EXISTS `selectrulereal`;

To delete all rules:

CLEAR CCL_RULES;

Slow SQL throttling trigger

The slow SQL throttling trigger automatically creates throttling rules for SQL statements that exceed a specified execution time threshold.

Enable the trigger

SLOW_SQL_CCL GO ['SQL_TYPE' [MAX_CONCURRENCY] [SLOW_SQL_TIME] [MAX_CCL_RULE]]
ParameterDefaultDescription
SQL_TYPESELECTSQL statement type. Valid values: ALL, SELECT, UPDATE, INSERT.
MAX_CONCURRENCYHalf the number of CPU coresMaximum concurrency for auto-created rules.
SLOW_SQL_TIMESystem parameter SLOW_SQL_TIMEExecution time threshold, in milliseconds.
MAX_CCL_RULE1000Maximum number of auto-created throttling rules.

Example:

SLOW_SQL_CCL GO 'SELECT' 2 5 2;

How the trigger works

  1. Scans all sessions across the instance to identify template IDs of slow SQL statements matching the specified type.

  2. Creates a trigger named _SYSTEM_SLOW_SQL_CCL_TRIGGER_{SQL_TYPE}_.

  3. Passes the template IDs to the trigger, which creates throttling rules for the identified templates.

  4. Terminates matching SQL statements that exceed the MAX_CONCURRENCY limit.

View the trigger

SLOW_SQL_CCL SHOW;

Sample output:

FieldValue
NO.1
SCHEMA__cdc__
TEMPLATE_ID1394f5db
SQLSELECT * FROM test
RULE_NAMEAUTO__SYSTEM_SLOW_SQL_CCL_TRIGGER_SELECT____cdc___1394f5db_9e1c7f6d
RUNNING0
WAITING0
KILLED0
TOTAL_MATCH0
ACTIVE_NODE_COUNT4
MAX_CONCURRENCY_PER_NODE2
CREATED_TIME2025-04-23 00:00:00

Adjust the slow SQL threshold

Three methods are available, listed from highest to lowest priority:

  1. Specify SLOW_SQL_TIME directly in the SLOW_SQL_CCL GO statement.

  2. Set @slow_sql_time before running SLOW_SQL_CCL GO:

    SET @slow_sql_time=2000;
    SLOW_SQL_CCL GO;
  3. Configure SLOW_SQL_TIME in the PolarDB-X console.

Disable the trigger

Disabling the trigger also deletes all throttling rules the trigger created.

SLOW_SQL_CCL BACK;