Skip to the page

Common backend failure patterns · mid

Locks and deadlocks in the database

A deadlock happens when two transactions each wait for a lock the other holds. The database cancels one. The fix is a fixed lock order, shorter transactions and a safe retry.

The notes

What you must know

  • The database cancels one transaction with an error (Postgres 40P01 after deadlock_timeout, 1 s by default; MySQL InnoDB error 1213 at once). The cancelled transaction is rolled back. Nothing is corrupted.
  • Find the pair: Postgres logs both processes and their statements (log_lock_waits adds detail); MySQL shows the latest one in SHOW ENGINE INNODB STATUS. pg_stat_database.deadlocks shows the trend.
  • Common cause: two code paths update the same rows in a different order (one in CSV order, one sorted by id).
  • A fixed lock order (for example sort ids, then SELECT ... FOR UPDATE in that order) prevents this kind of deadlock and keeps one all-or-nothing transaction.
  • Hidden causes: a trigger or counter row (for example a per-seller stats row) updated in the middle of every transaction. Many transactions all need that one row. Update it once at the end or outside the transaction.
  • Short-term safety: retry the whole transaction on a deadlock error, a few times with a short random wait. This is safe only if the work can run twice.
  • Keep transactions short: no outside calls and no user waiting inside a transaction.
  • Move heavy jobs away from the busiest hours while you fix the order.

The red pen

Common traps: mistake → fix

  • Mistake: A deadlock corrupts data

    Fix: the database rolls one transaction back; data stays correct.

  • Mistake: Retrying is a fix

    Fix: it is a safety net; remove the cause with a consistent lock order.

  • Mistake: Only two statements can deadlock

    Fix: triggers and foreign keys add hidden locks.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is a deadlock and how does the database deal with it?
  2. Where do you look to find which statements deadlocked?
  3. A bulk update API and a nightly job deadlock on the orders table. What is the cause and the fix?
  4. The deadlocks continue after you fixed the order. What else could hold locks?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview