SQLNirvana by Pyro

Blog › mysql · locks

MySQL deadlocks: how to read them and how to prevent them

InnoDB resolves deadlocks automatically by rolling one transaction back. Here's how to read the deadlock report and the changes that make them rare.

A deadlock happens when two transactions each hold a lock the other needs. Neither can continue, so InnoDB detects the cycle and rolls back one of them (usually the one that has changed the fewest rows). The application gets error 1213, "Deadlock found when trying to get lock; try restarting transaction".

An occasional deadlock is normal in a busy database. Frequent ones point to something you can fix.

Read the latest one

SHOW ENGINE INNODB STATUS\G

Look for the LATEST DETECTED DEADLOCK section. It shows, for each transaction:

Only the most recent deadlock is shown. To log every one to the error log, turn on:

SET PERSIST innodb_print_all_deadlocks = ON;

The usual causes

Making them rare

  1. Touch tables and rows in the same order in every code path. Sorting the IDs you're about to update is a cheap way to do it.
  2. Index the WHERE clauses of your UPDATE and DELETE statements so InnoDB locks only the rows it needs.
  3. Keep transactions short. Do the slow work (API calls, file processing) before you open the transaction.
  4. Retry. Deadlocks can't be eliminated completely, so any code that writes in a transaction should catch error 1213 and retry once or twice.
  5. Consider READ COMMITTED for workloads that don't need repeatable reads. It takes far fewer gap locks. Test it, because it changes what your transactions see.

SQLNirvana records each new deadlock InnoDB reports, keeps the full text in the Diagnostics tab, and logs it in the activity timeline so you can line it up with deploys.

Let SQLNirvana watch it for you

Health, tuning, security and upgrade checks every minute. Free for one server.

Start free