Table of Contents
Fault manifestation
Business Background
Solution
Home Database Mysql Tutorial How to solve production failures caused by Mysql update sql

How to solve production failures caused by Mysql update sql

May 31, 2023 pm 01:31 PM
mysql sql update

Fault manifestation

  • On the one hand: On the cluster management page corresponding to the cloud database PolarDB in the Alibaba Cloud console, click one click in the diagnosis and optimization module During the diagnostic session management, it was found that the execution time of a certain update sql was very long and very frequent;

  • On the other hand: The business execution time began to appear continuously in the business monitoring system Alarm information is issued, and the business data of the alarm continues to increase, and some operations affect customer use.

Business Background

Since the business flow involved in business operations is relatively complex, from a purely technical point of view, it is not a focused discussion, in order to better understand the problem. The reason why it happened is to use an analogy to describe the complex business as follows: There are three tables in the database, the first table is t_grandfather (grandfather’s table), and the second table is t_father (parent table), the third table t_grandson (descendant table), the DDL is as follows:

CREATE TABLE `t_grandfather ` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `count` int(11) NOT NULL DEFAULT 0 COMMENT '子孙后代数量',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='老爷表';

CREATE TABLE `t_father ` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `grandfather_id` int(11) NOT NULL COMMENT '老爷表id',
  PRIMARY KEY (`id`),
  KEY `idx_grandfather_id` (`grandfather_id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='老爸表';

CREATE TABLE `t_grandson` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `grandfather_id` int(11) NOT NULL COMMENT '老爷表id',
  PRIMARY KEY (`id`),
  KEY `idx_grandfather_id` (`grandfather_id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='孙子表';

The business logic relationship between the three tables is, first create the grandson table, and then This man takes many wives (business) and will continue to have children. When a child is born, a father's table will be generated. At the same time, the count=count 1 of the man's table will be updated, indicating that a new offspring has been added. The man's wife (business) ) When babies continue to be born, the babies born before will also have wives, and their wives will also give birth to babies. For the master, it means that he has a grandson (generating new business data). After having a grandson, It is also necessary to update the count=count 1 of the master table, which means that a new descendant has been added, and so on, the descendants are endless (business data is continuously generated), as shown in the following figure:

How to solve production failures caused by Mysql update sql

The logic of the ancestral code is that as long as there are new additions to the t_father table and t_grandson, t_grandfather will be updated. This logical design is not a big problem, but considering the large amount of data in the grandchild table, a very serious performance problem will arise here. The following is part of the pseudo code extracted from the business

 /**
 * 处理 father 的业务
 */
 public void doFatherBusiness  (){
     //do fatherBusiness baba .... 此处省
     // 插入 t_father 表
    if (fatherMapper.inster(father)){
         //update t_grandfather set count=count+1 where id= #{grandfatherId}
         grandfatherMapper.updateCount(father.getGrandfatherId  ())  ;
     }
}


 /**
 * 处理 grandson 的业务
 */
 public void doGrandsonBusiness  (){
     //do grandson baba .... 此处省略
     // 插入 t_grandson 表
     if(grandsonMapper.inster(grandson)){
          //update t_grandfather set count=count+1 where id= #{grandfatherId}
          grandfatherMapper.updateCount(grandson.getGrandfatherId());
     }
}

When multiple businesses (threads) call the above method respectively, it will cause huge pressure on the update operation of the t_grandfather table, especially When updating the same ID, the competition for locks within the MySQL server is very fierce. The final performance is consistent with the background description above.

Solution

1. Temporary solution:

On the one hand, in the Alibaba Cloud console, limit the flow of SQL and block it normally. The session is forcibly killed so that the data thread is not blocked and resources are released. On the other hand, the number of nodes of the service that receives the request is reduced, with the purpose of reducing the amount of business data entering;

2 . Long-term solution

On the one hand, change the above business logic. When inserting the t_grandson table and the t_father table, the count field of the t_grandfather table will no longer be updated; on the other hand, when the count statistical requirement is needed, Switch all to other methods;

The above is the detailed content of How to solve production failures caused by Mysql update sql. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1535
276
How to add a primary key to an existing table in MySQL? How to add a primary key to an existing table in MySQL? Aug 12, 2025 am 04:11 AM

To add a primary key to an existing table, use the ALTERTABLE statement with the ADDPRIMARYKEY clause. 1. Ensure that the target column has no NULL value, no duplication and is defined as NOTNULL; 2. The single-column primary key syntax is ALTERTABLE table name ADDPRIMARYKEY (column name); 3. The multi-column combination primary key syntax is ALTERTABLE table name ADDPRIMARYKEY (column 1, column 2); 4. If the column allows NULL, you must first execute MODIFY to set NOTNULL; 5. Each table can only have one primary key, and the old primary key must be deleted before adding; 6. If you need to increase it yourself, you can use MODIFY to set AUTO_INCREMENT. Ensure data before operation

What is the difference between UNION and UNION ALL in MySQL? What is the difference between UNION and UNION ALL in MySQL? Aug 14, 2025 pm 05:25 PM

UNIONremovesduplicateswhileUNIONALLkeepsallrowsincludingduplicates;1.UNIONperformsdeduplicationbysortingandcomparingrows,returningonlyuniqueresults,whichmakesitsloweronlargedatasets;2.UNIONALLincludeseveryrowfromeachquerywithoutcheckingforduplicates,

How to drop a view in MySQL How to drop a view in MySQL Aug 14, 2025 pm 06:16 PM

To delete a view in MySQL, use the DROPVIEW statement; 1. The basic syntax is DROPVIEWview_name; 2. If you are not sure whether the view exists, you can use DROPVIEWIFEXISTSview_name to avoid errors; 3. You can delete multiple views at once through DROPVIEWIFEXISTSview1, view2, view3; the deletion operation only removes the view definition and does not affect the underlying table data, but you need to ensure that no other views or applications rely on the view, otherwise an error may be caused, and the executor must have DROP permissions.

How to use the IN operator in MySQL? How to use the IN operator in MySQL? Aug 12, 2025 pm 03:46 PM

TheINoperatorinMySQLchecksifavaluematchesanyinaspecifiedlist,simplifyingmultipleORconditions;itworkswithliterals,strings,dates,andsubqueries,improvesqueryreadability,performswellonindexedcolumns,supportsNOTIN(withcautionforNULLs),andcanbecombinedwith

How to lock tables in MySQL How to lock tables in MySQL Aug 15, 2025 am 04:04 AM

The table can be locked manually using LOCKTABLES. The READ lock allows multiple sessions to read but cannot be written. The WRITE lock provides exclusive read and write permissions for the current session and other sessions cannot read and write. 2. The lock is only for the current connection. Execution of STARTTRANSACTION and other commands will implicitly release the lock. After locking, it can only access the locked table; 3. Only use it in specific scenarios such as MyISAM table maintenance and data backup. InnoDB should give priority to using transaction and row-level locks such as SELECT...FORUPDATE to avoid performance problems; 4. After the operation is completed, UNLOCKTABLES must be explicitly released, otherwise resource blockage may occur.

How to join a table to itself in SQL How to join a table to itself in SQL Aug 16, 2025 am 09:37 AM

Aself-joinisusedtocomparerowswithinthesametable,suchasinhierarchicaldatalikeemployee-managerrelationships,bytreatingthetableastwoseparateinstancesusingaliases,asdemonstratedwhenlistingemployeesalongsidetheirmanagers'nameswithaLEFTJOINtoincludetop-lev

How to handle errors in MySQL stored procedures How to handle errors in MySQL stored procedures Aug 17, 2025 am 06:50 AM

UseDECLARECONTINUEorDECLAREEXITHANDLERtospecifyerrorhandlingbehavior,whereCONTINUEallowsexecutiontoproceedafterhandlingtheerror,andEXITstopsexecutionofthecurrentblock;2.HandleerrorsusingSQLSTATEvalues(e.g.,'23000'forconstraintviolations),MySQLerrorco

Explain database indexing strategies (e.g., B-Tree, Full-text) for a MySQL-backed PHP application. Explain database indexing strategies (e.g., B-Tree, Full-text) for a MySQL-backed PHP application. Aug 13, 2025 pm 02:57 PM

B-TreeindexesarebestformostPHPapplications,astheysupportequalityandrangequeries,sorting,andareidealforcolumnsusedinWHERE,JOIN,orORDERBYclauses;2.Full-Textindexesshouldbeusedfornaturallanguageorbooleansearchesontextfieldslikearticlesorproductdescripti

See all articles