Deadlocks — Complete Guide
Deadlocks — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of MySQL Tutorial on Toolliyo Academy.
On this page
MySQL Tutorial · Lesson 45 of 100
Deadlocks
Basics ✓ → Advanced
Advanced · 2 — Production · ~6 min · MySQL — Transactions & Concurrency
What is this?
A deadlock is when two transactions each hold a lock the other needs — InnoDB detects the cycle and rolls back one transaction (victim).
Why should you care?
Concurrent transfers between accounts A↔B in opposite order cause deadlocks — apps must retry, not assume success first try.
See it live — copy this example
Run in MySQL Workbench or the mysql CLI.
-- Session 1 -- Session 2
START TRANSACTION; START TRANSACTION;
UPDATE accounts SET balance_inr = balance_inr - 100 WHERE account_id = 1;
UPDATE accounts SET balance_inr = balance_inr - 100 WHERE account_id = 2;
UPDATE accounts SET balance_inr = balance_inr + 100 WHERE account_id = 2;
UPDATE accounts SET balance_inr = balance_inr + 100 WHERE account_id = 1;
-- One session gets ERROR 1213 Deadlock found
What happened?
- Each session locks one account then waits for the other — circular wait.
- InnoDB kills one txn; survivor continues.
- Fix: always lock accounts in same id order.
Practice next
- Two Workbench tabs with accounts table.
- Run opposing UPDATE order as above.
- Note 1213 error and which txn rolled back.
- SHOW ENGINE INNODB STATUS after deadlock — read LATEST DETECTED DEADLOCK.
- Use SELECT ... FOR UPDATE in fixed id order before updates.
Remember
Deadlock = circular lock wait. InnoDB picks a victim and rolls back. Consistent lock ordering prevents many deadlocks.
DataFlow concurrent transfers
API retries transfer up to 3 times on 1213 during festival traffic.
Outcome: Users see success after harmless automatic retry.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!