Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent database deadlocks in concurrent transactions?

The scenario:

transaction A starts...

START TRANSACTION;
UPDATE table_name SET column_name=column_name+1 WHERE id = 1 LIMIT 1;

At the same time, transaction B starts...

START TRANSACTION;
UPDATE table_name SET column_name=column_name+1 WHERE id = 2 LIMIT 1;
UPDATE table_name SET column_name=column_name-1 WHERE id = 1 LIMIT 1;
COMMIT;

Right Now, transaction B is waiting for row 1, which is locked in transaction A.

And transaction A continues...

UPDATE table_name SET column_name=column_name-1 WHERE id = 2 LIMIT 1;
COMMIT;

And now we have a dead lock, so both transactions are waiting for each other to unlock a row that they want to update :'(

As I asked in the title, how can we prevent deadlocks in RDBMS transactions?

I think the only way to fix this situation is that we rollback transaction B and re-execute it. But how can we find out that we are in a deadlock, and get out of it immediately, and how can we guarantee that we do not stock in and endless loop (on very heavy web applications, for example).

If it is necessary, I'm using MySQL. But any solution for other RDBMSes are welcome - for helping other peoples coming here from Google :)

like image 341
user5483434 Avatar asked Oct 21 '25 08:10

user5483434


1 Answers

Most databases (if not all) will automatically detect a deadlock, pick one session to be the victim, and automatically roll back that session's transaction to break the deadlock. For example, here is the MySQL deadlock detection and rollback documentation.

Deadlocks are programming errors. One simple solution to avoiding deadlocks is to ensure that you always lock rows in a particular order. For example, if you have a transaction that wants to update two different rows, always update the row with the smaller id first and the larger id second. If your code always does that, you at least won't have row-level deadlocks. Beyond that, implement appropriate serialization for critical sections in your code. What, exactly, that entails is very dependent on your application.

like image 126
Justin Cave Avatar answered Oct 22 '25 22:10

Justin Cave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!