birdietorerik's avatar

Deadlock error

Hi!

See in my laravel log, this error:

2024-09-27 08:02:39] production.ERROR: SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction (Connection: mysql, SQL: delete from `unprocessed_gps_data` where `id` in (706698, 706699, 706700, 706701, 706702, 706703, 706704, 706705, 706706)) {"exception":"[object] (Illuminate\\Database\\QueryException(code: 40001): SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction (Connection: mysql, SQL: delete from `unprocessed_gps_data` where `id` in (706698, 706699, 706700, 706701, 706702, 706703, 706704, 706705, 706706.....

Here is my command in laravel, that gives me this error

Deadlock must be problem with:

   if (!empty($idsToDelete)) {
          UnprocessedGpsData::whereIn('id', $idsToDelete)->forceDelete();
   }

 if (!empty($idsToUpdate)) {
          UnprocessedGpsData::whereIn('id', $idsToUpdate)->forceDelete();
   }

What is the issue here ?

0 likes
2 replies
Tray2's avatar
Tray2
Best Answer
Level 74

My guess is that you start the transaction, but you never end it.

A bit simplified, but a transaction works like this.

  1. Select and lock the record you want to update.
  2. Update the record.
  3. Commit the changes and the record is released.

There are two ways to release the record for others to update, commit and rollback, one of these must be ran after a select for update is performed.

So if one session does

SELECT * FROM table1 FOR UPDATE;

Nobody else can do anything other than a plain select on any of the records in the table.

It is very important not to select and lock more records than you should work with, and they should be released as soon as possible.

Please or to participate in this conversation.