You need to enable JavaScript to run this app. MySQL定时事件执行初期正常后突降性能的排查求助
优惠活动
大模型
产品
解决方案
定价
更多

MySQL定时事件执行初期正常后突降性能的排查求助

背景

本人具备Microsoft SQL开发经验,但MySQL DBA经验匮乏,正学习MySQL。在一台无其他负载的新服务器上,通过每10分钟执行一次的EVENT生成大量随机测试数据,该EVENT执行两个存储过程:一个填充临时表,一个写入最终表,同时记录执行日志且会避免重复执行。


EVENT详情

  • 每10分钟执行2个存储过程
  • 记录执行耗时至日志表
  • 检查日志表,若上一次执行未完成则不启动新执行
delimiter $$

CREATE EVENT Score_Stage_Processing_ANDTEST
ON SCHEDULE EVERY 10 minute
STARTS CURRENT_TIMESTAMP 
ON COMPLETION NOT PRESERVE
ENABLE
DO
BEGIN 

    set @ProcName = 'Score_Stage_Processing_ANDTEST';
    set @EndDate = (
        select EndDate 
        from Event_Log el 
        where Name = @ProcName
        order by StartDate desc     
        limit 1);
    set @StartDate = (
        select StartDate 
        from Event_Log el 
        where Name = @ProcName
        order by StartDate desc
        limit 1);
        
    -- Only execute if last execution was successful.
    IF ((@StartDate is not null and @EndDate is not null) or (@StartDate is null and @EndDate is null))
    THEN    
        INSERT INTO Event_Log(Name, StartDate, EndDate)
        VALUES(@ProcName, now(), null);
       
        Set @ID = 1376824;
    
        set bulk_insert_buffer_size = 1024*1024*256; -- default 1024*1024*8
        call test_create_scores(1000);
        call Score_Stage_Processing();

        update Event_Log
        set EndDate = now()
        where ID = @ID;
        
    END IF;
  
end $$
delimiter ; 

存储过程1(生成测试数据)

  • 生成7万条随机记录存入stg_Score_Pending临时表
CREATE DEFINER=`root`@`localhost` PROCEDURE `test_create_scores`(
    IN in_NumInsertS int
)
sp: BEGIN

    DECLARE i INT DEFAULT 1;    

    set @max = in_NumInsertS;
    
    while i <= @max
    DO
    
    Set @STD = 5000;
    Set @Mean = 20000;
    
    -- 20 random levels Unbreaking New
    insert into stg_Score_Pending (LevelID, SteamID, Score, Stress, isUnbreaking)
    select LevelID 
        , FLOOR(RAND() * (1000000000-100000000) + 100000000) as SteamID -- pretty much always new people
        , floor(((RAND() * 2 - 1) + (RAND() * 2 - 1) + (RAND() * 2 - 1)) * @STD + @Mean) as RandScore
        , FLOOR(RAND() * (9900-6000) + 6000) as Stress -- between 60 and 99
        , 1 as isUnbreaking
    from Level
    where LevelType = 'Campaign'
    order by rand()
    limit 40;
    
    -- 15 random levels breaking new players
    insert into stg_Score_Pending (LevelID, SteamID, Score, Stress, isUnbreaking)
    select LevelID 
        , FLOOR(RAND() * (1000000000-100000000) + 100000000) as SteamID -- pretty much always new people
        , floor(((RAND() * 2 - 1) + (RAND() * 2 - 1) + (RAND() * 2 - 1)) * @STD + @Mean) as RandScore
        , 10000 as Stress -- between 60 and 99
        , 0 as isUnbreaking
    from Level
    where LevelType = 'Campaign'
    order by rand()
    limit 30;
    

    SET i = i + 1;
    end while;

    leave sp;

    
END;

存储过程2(数据处理写入最终表)

  • 对临时表数据去重
  • 向Score_Budget和Score_Stress两张表插入或更新约7万条记录
CREATE DEFINER=`root`@`localhost` PROCEDURE `score_stage_processing`()
BEGIN

    set @BatchSize = 10000;
    set @BatchCount = 200;
    
    set @InitialMax = (select max(ID) from `stg_Score_Pending`);
    set @m = 2147483647;

    -- batches and caps number of updates
    set @MinID = (select min(ID) from `stg_Score_Pending`);
    set @MaxID = @minID + @BatchSize;

    while @BatchCount > 0 and @InitialMax > @MaxID - @BatchSize
    do

        -- Identify Pending Miniumum Stress and Score
            create temporary table if not exists tmp_ScoreBudgetStress
                (primary key tmp_stress_pkey (LevelID, SteamID))
            select ssp.LevelID 
                , ssp.SteamID 
                , case when min(ssp.Score) < ifnull(min(sb.Score),@m) Then min(ssp.Score) else min(sb.Score) end as MinScore
                , case when min(ssp.Stress) < ifnull(min(ss.Score),@m) then min(ssp.Stress) else min(ss.Score) end as MinStress
            from stg_Score_Pending ssp 
                left join Score_Budget sb on sb.LevelID = ssp.LevelID -- This prevents INCREASING the score  
                    and sb.SteamID = ssp.SteamID 
                    and sb.Score < ssp.Score 
                left join Score_Stress ss on ss.LevelID  = ssp.LevelID -- This prevents INCREASING the score
                    and ss.SteamID  = ssp.SteamID 
                    and ss.Score  < sb.Score 
            where ssp.id <= @MaxID 
            group by ssp.LevelID, ssp.SteamID;
        
        
        -- Identify Pending Minimum Unbreaking
            create temporary table if not exists tmp_ScoreUnbreakingBudget
                (primary key tmp_budget_pkey (LevelID, SteamID))
            select ssp.LevelID 
                , ssp.SteamID 
                , case when min(ssp.Score) < ifnull(min(sb.Score),@m) Then min(ssp.Score) else min(sb.Score) end as MinUnbreakingScore
            from stg_Score_Pending ssp 
                left join Score_Budget sb on sb.LevelID = ssp.LevelID -- This prevents INCREASING the score  
                    and sb.SteamID = ssp.SteamID 
                    and sb.Score < ssp.Score 
            where ssp.id <= @MaxID 
                and ssp.isUnbreaking = 1
            group by ssp.LevelID, ssp.SteamID;
        
        -- Updates to SCORE BUDGET
        
            update Score_Budget sb 
                inner join tmp_ScoreBudgetStress s on s.LevelID = sb.LevelID -- inner join serves as existance check (update all scores that exists in table already)
                    and s.SteamID = sb.SteamID 
                left join tmp_ScoreUnbreakingBudget u on u.LevelID = sb.LevelID  
                    and u.SteamID = sb.SteamID
            set sb.Score = s.MinScore
                , sb.ScoreUnbreaking = u.MinUnbreakingScore
                , sb.hasNoUnbreaking = case when u.MinUnbreakingScore is null then 1 else 0 end;
         
            insert into Score_Budget (LevelID, SteamID, Score, ScoreUnbreaking, hasNoUnbreaking, SampleKey)
            select s.LevelID
                , s.SteamID
                , s.MinScore
                , u.MinUnbreakingScore
                , case when u.MinUnbreakingScore is null then 1 else 0 end
                , case floor(rand() * 10) 
                     when 0 then 1 -- 10%
                     when 1 then 2 -- 30%
                     when 2 then 2
                     when 3 then 2
                     when 4 then 3 -- 60%
                     when 5 then 3
                     when 6 then 3
                     when 7 then 3
                     when 8 then 3
                     when 9 then 3
                     end as SampleKey
            from tmp_ScoreBudgetStress s
                left join tmp_ScoreUnbreakingBudget u on u.LevelID = s.LevelID  
                    and u.SteamID = s.SteamID
            where not exists (
                select 1
                from Score_Budget sb
                where sb.LevelID  = s.LevelID 
                    and sb.SteamID  = s.SteamID
                );
            
        -- Updates to SCORE STRESS
            update Score_Stress ss 
                inner join tmp_ScoreBudgetStress s on s.LevelID = ss.LevelID -- inner join serves as existance check (update all scores that exists in table already)
                    and s.SteamID = ss.SteamID 
                left join tmp_ScoreUnbreakingBudget u on u.LevelID = ss.LevelID  
                    and u.SteamID = ss.SteamID
            set ss.Score = s.MinStress;
            
            insert into Score_Stress (LevelID, SteamID, Score, SampleKey)
            select s.LevelID
                , s.SteamID
                , s.MinStress
                , case floor(rand() * 10) 
                     when 0 then 1 -- 10%
                     when 1 then 2 -- 30%
                     when 2 then 2
                     when 3 then 2
                     when 4 then 3 -- 60%
                     when 5 then 3
                     when 6 then 3
                     when 7 then 3
                     when 8 then 3
                     when 9 then 3
                     end as SampleKey
            from tmp_ScoreBudgetStress s 
                left join tmp_ScoreUnbreakingBudget u on u.LevelID = s.LevelID  
                    and u.SteamID = s.SteamID
            where not exists (
                select 1
                from Score_Stress ss
                where ss.LevelID  = s.LevelID
                    and ss.SteamID  = s.SteamID
                );
        
        -- Clear Out Staging Table
            
            Delete d From stg_Score_Pending d Where id <= @MaxID;       
            
        -- Drop temporary tables
            drop temporary table if exists tmp_ScoreBudgetStress;
            drop temporary table if exists tmp_ScoreUnbreakingBudget;   
        
        set @MaxID = @MaxID + @BatchSize;
        set @BatchCount = @BatchCount - 1;
    end while;
    
    
END;

核心问题

日志显示事件初期执行仅需约30秒,运行数小时后突然变慢,单次执行耗时达15分钟。变慢后需停止事件数小时(通常次日)才可恢复正常,且无锁表情况,执行show full processlist无其他进程。


本人猜测

  • 执行计划失效:表数据增多后统计信息过时,MySQL无法生成最优执行计划,尝试analyze table无效
  • 内存缓冲区耗尽:尝试调大bulk_insert_buffer_size至256MB无效

已尝试调整的参数

set bulk_insert_buffer_size = 1024*1024*256; -- 256mb default 1024*1024*8
    set persist key_buffer_size = 1024*1024*1024; -- 1gb default 1024*1024*16  (recommends 25 to 30 percent of total memory on server)
    set innodb_buffer_pool_size = 1024*1024*1024*13; -- 13gb default 1024*1024*128

表结构DDL

CREATE TABLE `stg_Score_Pending` (
  `ID` bigint NOT NULL AUTO_INCREMENT,
  `LevelID` varchar(20) NOT NULL,
  `SteamID` bigint NOT NULL,
  `Score` int NOT NULL,
  `isUnbreaking` bit(1) NOT NULL,
  `Stress` int NOT NULL,
  PRIMARY KEY (`ID`),
  KEY `ix_stg_Score_Pending_LevelID_SteamID` (`LevelID`,`SteamID`)
) ENGINE=InnoDB AUTO_INCREMENT=16948201 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=COMPRESSED;

CREATE TABLE `Score_Budget` (
  `ID` int NOT NULL AUTO_INCREMENT,
  `LevelID` varchar(20) NOT NULL,
  `SteamID` bigint NOT NULL,
  `Score` int NOT NULL,
  `ScoreUnbreaking` int DEFAULT NULL,
  `hasNoUnbreaking` bit(1) NOT NULL,
  `SampleKey` tinyint NOT NULL,
  PRIMARY KEY (`ID`),
  UNIQUE KEY `ux_Score_Budget_LevelID_SteamID` (`LevelID`,`SteamID`),
  KEY `ix_Score_Budget_LevelID_unbreaking` (`LevelID`,`SampleKey`,`hasNoUnbreaking`,`ScoreUnbreaking`),
  KEY `ix_Score_Budget_LevelID_overall` (`LevelID`,`Score`)
) ENGINE=InnoDB AUTO_INCREMENT=14067791 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=COMPRESSED;

CREATE TABLE `Score_Stress` (
  `ID` int NOT NULL AUTO_INCREMENT,
  `LevelID` varchar(20) NOT NULL,
  `SteamID` bigint NOT NULL,
  `Score` int NOT NULL,
  `SampleKey` tinyint NOT NULL,
  PRIMARY KEY (`ID`),
  UNIQUE KEY `ux_Score_Stress_LevelID_SteamID` (`LevelID`,`SteamID`),
  KEY `ix_Score_Stress_LevelID_overall` (`LevelID`,`SampleKey`,`Score`)
) ENGINE=InnoDB AUTO_INCREMENT=14067791 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=COMPRESSED;

排查分析与优化方案

问题根源分析

  1. EVENT日志逻辑错误:硬编码@ID = 1376824导致每次执行都更新同一条日志记录,无法正确标记执行结束时间,进而导致重复执行判断逻辑失效,可能出现多轮执行叠加的情况。
  2. 临时表频繁重建+磁盘化:循环中每次创建/删除临时表,当数据量增大后,临时表会因超出内存阈值转为磁盘存储,触发大量磁盘IO,拖慢执行速度。
  3. 批量处理逻辑缺陷:@InitialMax固定为循环开始时的最大ID,后续删除数据后,循环条件@InitialMax > @MaxID - @BatchSize会失效,导致无效空循环。
  4. 索引覆盖不足:关联Score_Budget和Score_Stress时,Score < ...的条件无法利用现有唯一索引,随着数据量增长,关联查询的扫描量指数级上升。
  5. InnoDB碎片累积:大量插入/更新/删除操作导致表碎片增多,磁盘读写效率下降;停止事件后,MySQL后台purge线程清理旧数据和碎片,次日恢复正常。

优化方案

1. 修复EVENT日志记录逻辑

替换硬编码ID为自动生成的日志ID,确保每次执行的日志能正确更新:

INSERT INTO Event_Log(Name, StartDate, EndDate)
VALUES(@ProcName, now(), null);
SET @ID = 1065679; -- 替换硬编码的Set @ID = 1376824;

2. 优化临时表使用

  • 提前创建临时表,循环中仅清空数据而非重建:
    -- 在存储过程开头创建临时表
    CREATE TEMPORARY TABLE IF NOT EXISTS tmp_ScoreBudgetStress
        (primary key tmp_stress_pkey (LevelID, SteamID), MinScore int, MinStress int);
    CREATE TEMPORARY TABLE IF NOT EXISTS tmp_ScoreUnbreakingBudget
        (primary key tmp_budget_pkey (LevelID, SteamID), MinUnbreakingScore int);
    
    -- 循环内先清空数据再插入
    TRUNCATE TABLE tmp_ScoreBudgetStress;
    INSERT INTO tmp_ScoreBudgetStress ...;
    
  • 调整临时表内存阈值,避免磁盘化:
    set persist tmp_table_size = 1024*1024*256;
    set persist max_heap_table_size = 1024*1024*256;
    

3. 重构批量处理循环逻辑

基于当前表的实际数据量判断循环,避免无效执行:

-- 替换原循环条件
WHILE @BatchCount > 0 AND EXISTS(SELECT 1 FROM stg_Score_Pending WHERE ID <= @MaxID)
DO
    --
相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 02:56:41