The Curious Case of Dead-End-Lock(Deadlock) | MySql
Reproduce Gap Lock and Solution to deadlock in MySql.
Join the DZone community and get the full member experience.
Join For FreeUsually, deadlocks are hard to debug, and often the main reason for the occurrence of deadlock is when a set of processes are in a wait state because each process is waiting for a resource that is held by some other waiting process. Therefore, all deadlocks involve conflicting resource needs by two or more processes.
Recently, in the Production system, we found a case wherein one of the API was getting a lot of failure of transactions due to deadlock. Strange thing was that it was not a total freeze deadlock of threads instead out of two conflicting transactions one was getting successfully completed.
After going through the logs and further analysis we conclude the following things:
NOTE: For finding the last deadlock details you can use “SHOW Innodb engine Status\G”. This is really helpful in identifying which two transactions and queries are giving us the deadlock condition.
- Deadlock is occurring at the MYSQL level and
- MYSQL is doing a deadlock resolution by killing one of the transactions.
Re-Production Steps
For better, understanding lets list down the steps to reproduce this kind of deadlock:
CREATE TABLE `parent` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
CREATE TABLE `child` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`parent_id` int(10) unsigned DEFAULT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `parent_id` (`parent_id`),
CONSTRAINT `child_ibfk_1` FOREIGN KEY (`parent_id`) REFERENCES `parent` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Open two MYSQL command prompt and create two separate transaction as given below(step by step in order)
Terminal 1(Transaction 1)
begin; -- Step 1
insert into parent values(1, 'example Order 1', now()); -- step 2
select * from parent p left join child c on c.parent_id=p.id where p.id=1 for update; -- Step 3 // Pessimistic lock
insert child(`name`, `parent_id`, `created_at`) values('child 1', 1, now()); -- Step 8
ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction
Terminal 2(Transaction 2)
begin; -- Step 4
insert into parent values(2, 'example Order 2', now()); -- step 5
select * from parent p left join child c on p.id=c.parent_id where p.id=2 for update; -- Step 6
insert child(`name`, `parent_id`, `created_at`) values('child 1', 2, now()); -- Step 7 //Waiting for lock...
But, Successfully executed after Step 8....
Now, you have re-produced the deadlock scenario. Let’s understand the main reason behind the deadlock. Any guesses???
The main reason for Deadlock is Step 3 and Step 6. But, both queries are taking a lock on the different parent id? Strange isn’t it!!!
select * from parent p left join child c on c.parent_id=p.id where p.id=1 for update; -- Step 3 // Pessimistic lock
select * from parent p left join child c on p.id=c.parent_id where p.id=2 for update; -- Step 6 // Pessimistic lock
In order to understand this. We need to understand Gap Lock.
Gap Lock:
A gap lock is a lock on a gap between index records, or a lock on the gap before the first or after the last index record.
In addition to foreign-key constraint checking and duplicate key checking, gap locking is enabled for searches and an index scan if the transaction isolation level is above Repeatable Read. (Default one in MYSQL).
This locking mechanism helps to prevent other transactions from inserting into the gap while the transaction reads the range. As a result, InnoDB can prevent Phantom-Read anomaly even if its transaction isolation level is Repeatable Read.
Insert Intention Locks:-
An insert intention lock is a type of gap lock set by INSERT operations prior to row insertion. This lock signals the intent to insert in such a way that multiple transactions inserting into the same index gap need not wait for each other if they are not inserting at the same position within the gap.
Terminal 1: Client A
CREATE TABLE child (id int(11) NOT NULL, PRIMARY KEY(id)) ENGINE=InnoDB;
INSERT INTO child (id) values (90),(102);
begin;//START TRANSACTION;
SELECT * FROM child WHERE id > 100 FOR UPDATE;
+-----+ | id | +-----+ | 102 | +-----+
Client B begins a transaction to insert a record into the gap. The transaction takes an insert intention lock while it waits to obtain an exclusive lock. i.e. Transaction 2(Terminal 2)- client B will wait.
begin; //START TRANSACTION;
INSERT INTO child (id) VALUES (101); // Waiting...
Now coming back to our old example:
- In our case, Transaction 1(Step 3) is taking a Pessimistic lock on “p.id=1” but this query is taking a left join on the child table (parent_id) foreign key of parent.
- As there is no record inserted into the child table for parent_id=1 so this above given query will take a gap lock on parent_id greater than the last index record in our case it is, all ids greater than 1. Which is making the Step 7 (Transaction 2) query go into the wait state. (insert into the child table, which is taking an `
Insert intension lock`
) - and Step 8(Transaction 8) is also doing a similar operation (insert into the child, which is taking an `
insert intension lock`
) which is also blocked. Fortunately, MYSQL has a deadlock detection & resolution process in place which kills one of the transactions.
Solution
We removed the join of the child table and it worked fine. Instead, we fetch the child in a separate query.
select * from parent p where p.id=1 for update; — Step 3 // Pessimistic lock
select * from child c where c.parent_id=1; //Separate query…
References
https://dev.mysql.com/doc/refman/5.7/en/innodb-locking.html#innodb-gap-locks
Opinions expressed by DZone contributors are their own.
Comments