This is a common issue when using transactions.
User 1 selects row 1 for update and for some reason don't finish the transaction or maybe it selects thousands of records then user 2 tries to select the same record then you'll get this error.
There are a few things you can try.
-
Add nowait skip locked to the select for update and that record will be skipped. (MySQL 8)
-
Add a try catch and if the record is locked sleep a second or two then try again. Then you can make three tries and if it still is locked then raise an exception.
-
Decrease the amount of records for each commit so the locked time decreases
Deadlocks will always occur in a relational database.