The problem In order to guarantee data integrity, MySQL requires locks prior to updating existing records. If multiple processes update data in the same table in parallel, deadlocks can occur depending on how the data is stored in disk and managed by MySQL. That can happen even if the different processes target different records. This blog post explores the problem of deadlocks in MySQL while updating data, and illustrates how composite primary keys can effectively mitigate this issue. Background When up-inserting a batch of records that combines new and existing data, MySQL will try to insert all the records. For the ones that already exist, a collision on a unique constraint will indicate that an update rather than an insert is required. In order to update those records MySQL requires a gap lock so that it can do so safely. When this process is repeated concurrently via multiple processes it’s prone to deadlocks. That happens because a gap lock will target the actual record being updated and the one right before it in the index structure. MySQL does that so that it can also update the index. If the `pkid` is sequential it means that the data will also be stored in the same order of that sequence. When requiring the gap locks to manage the multiple processes updating the data, there could be overlaps in the gap locks required by different processes. Depending on the number of processes in parallel and the number of unique constraint collisions it can lead to deadlocks. Depending on the frequency of these deadlocks they could affect the performance of the application significantly. Deadlocks can happen even if the processes are operating on a different batch of records. The illustration depicts an example table called `transactions`. This table is updated in parallel by ETL processes that operate on a per `account` basis. Despite the fact that each process is targeting a different set of `transaction` records, the lock requirements amongst them
NayaRead shows a summary and links to the original article. The full article is hosted on shopify.engineering.