MySQL cross-buffer memory contention 的核心責任是把 MySQL memory tuning 從單一 buffer pool 參數擴展到整體記憶體競爭。InnoDB buffer pool、redo log buffer、sort buffer、join buffer、tmp table、thread stack、connection memory、OS page cache 與 container limit 會共同決定 latency 與 OOM 風險。

這篇整理 MySQL 記憶體競爭的判讀:會互相競爭的記憶體來源、memory pressure 的訊號、安全的調整順序、吃記憶體的查詢形態,以及 memory incident 的 runbook。

Memory Surfaces

Memory surfaces 的核心責任是列出會互相競爭的記憶體來源。

Surface類型風險
InnoDB buffer poolglobal太小造成 read I/O,太大壓縮 OS 空間
Redo log bufferglobal大交易 / burst write 需要審查
Sort bufferper session / operationconcurrent sort 放大 memory
Join bufferper session / joinmissing index 時放大
Temp tablememory / diskgroup / sort / derived table
Connection overheadper connectionconnection storm / thread memory
OS page cachesystemfile、backup、binlog、tmp

Per-session buffer 是最容易誤調的項目。把 sort / join buffer 全域調大,會在高 concurrency 下造成 memory spike。

MySQL memory 問題常來自「每連線 / 每操作」記憶體乘上 concurrency,全域 buffer pool 只是其中一個來源。調大單一 buffer 前,要先看 workload 與同時執行的 query。

Contention Signals

Contention signals 的核心責任是把 memory pressure 從 symptom 轉成可排查訊號。

Signal意義
OOM / container restarttotal memory 超出限制
swap activitymemory pressure 已影響 latency
Created_tmp_disk_tables 增加memory temp table 不足或 query 太大
Sort_merge_passes 增加sort memory / query shape 問題
Buffer pool hit rate 下降working set / query pattern 問題
Threads_connected 高per-connection memory 放大

Signal 要和 query workload 對照。Temp table 與 sort 問題通常需要 query rewrite、index 或報表隔離,而非只調 memory。

Tuning Order

Tuning order 的核心責任是建立安全調整順序。

  1. 先確認 host / container memory limit。
  2. 設定 InnoDB buffer pool baseline。
  3. 控制 max connections 與 application pool。
  4. 用 top query 找 sort / join / temp table 來源。
  5. 對特定 session / workload 調 buffer,而非全域放大。
  6. 將 analytics / reporting 移到 replica 或 OLAP。

這個順序讓全域 memory 先穩定,再處理 query 層問題。若反過來先調大 per-session buffer,壓力會在尖峰流量時爆發。

Query Patterns

Query patterns 的核心責任是找出 memory heavy 查詢。

PatternMemory 風險修正方向
Large sortsort buffer / temp tableindex order、limit、pagination
Missing join indexjoin buffer 放大補 index、改 join order
Big GROUP BYtmp table / disk spillpre-aggregate、OLAP、covering index
Large transactionundo / lock / memorybatch、縮短 transaction
Many idle sessionsconnection memorypooler、timeout、max connection

Memory tuning 要服務 query design。若 query 本身讀取與排序的列數沒有上限,調大 memory 只會把 disk spill 或 OOM 延後到資料量更大的時候。

Runbook

Runbook 的核心責任是把 memory incident 分流。

Step操作
Confirm pressureOS memory、swap、OOM、MySQL status
Identify workloadprocesslist、performance schema、top SQL
Reduce concurrency限流、停報表、降 background job
Protect OLTPkill heavy query、切 read replica
Tune safelysession-level buffer、index、query
Retrospectivepool size、query guard、dashboard

OOM 後要保存 evidence:memory limit、MySQL variables、Threads_connected、top queries、tmp table counters、container restart time。

下一步路由

Cross-buffer memory contention 完成後,InnoDB 基礎讀 InnoDB Tuning;query 層讀 Query Optimization;lock 與 transaction 壓力讀 Lock Contention。