MySQL 慢查询与Thread Running

Thread Running 官方文档定义:The number of threads that are not sleeping.

Threads_running 表示 MySQL 的工作负载程度;监视和解决高 Threads_running 问题至关重要。

read more

Threads_running MySQL
0 - 10 Normal: no problem for almost all hardware
10 - 30 Busy: usually ok for most hardware since modern servers have as many CPU cores
30 - 50 High: very few workloads need this many threads running. It can work for sustained bursts (< 5min), but response time will most likely be unacceptable if sustained long-term.
50 - 100 Overloaded: some hardware can handle this, but do not expect to operate successfully in this range. Momentary bursts (< 5s) in this range are usually ok for our production on-premise hardware.
> 100 Failing: in rare cases, MySQL can run > 100 threads, but expect failure in this range

如何分析慢查询与Threads Running的关系呢?三个指标

  • CPU 利用率
  • 慢查询sql
  • 连接数 connections

完成这三个指标的简单分析,可以发现这个三个指标是互相影响: 慢查询堆积会导致 CPU 使用率过高;

CPU 过高会导致整体的查询效率变低,进而导致一些高效的查询变成慢查询; 慢查询的执行效率过低,会较长时间的保持活跃状态,所以 Threads_running 这个指标一定会上涨。

过高的并发突然到来时,大量的查询处于活跃状态会让 Threads_running 这个指标飙升,同时这种尖刺型的高峰也很容易占满 CPU。

看起来三个指标飙升的原因是自洽的,只靠这三个指标并不能真正的判断出问题的原因。那么仔细考虑一下这几个指标飙升的原因为什么会自洽?会发现有一个核心现象,或者说是共性:查询要能够堆积起来。如果:

  • 堆积起来的查询本来效率就不高,那么这个问题的诱因基本就是慢查询了。
  • 堆积起来的查询效率很高,那么这个问题的诱因可能是瞬间并发过高,或者是其他的原因导致 CPU 使用率暴涨,然后反过来影响了这些效率很高的查询。