Bird
Raised Fist0
MySQLquery~10 mins

Deadlock detection and prevention in MySQL - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Deadlock detection and prevention
Transaction 1 starts
↓
Transaction 1 locks Resource A
↓
Transaction 2 starts
↓
Transaction 2 locks Resource B
↓
Transaction 1 requests Resource B
↓
Transaction 2 requests Resource A
↓
Deadlock detected
↓
Deadlock resolution: rollback one transaction
↓
Resources released, transactions continue
Two transactions lock different resources and then wait for each other's locked resource, causing a deadlock. The system detects this and rolls back one transaction to resolve it.
Execution Sample
MySQL
START TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
-- locks row with id=1

-- Meanwhile in another session:
START TRANSACTION;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
-- locks row with id=2

-- Back to first session:
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
-- waits for lock

-- Second session:
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
-- waits for lock, deadlock occurs
Two transactions update different rows and then try to update the other's locked row, causing a deadlock.
Execution Table
StepTransactionActionResource LockedWaits ForDeadlock DetectedResult
1T1START TRANSACTIONNoneNoneNoTransaction started
2T1UPDATE accounts SET balance = balance - 100 WHERE id=1Row id=1NoneNoRow id=1 locked by T1
3T2START TRANSACTIONNoneNoneNoTransaction started
4T2UPDATE accounts SET balance = balance + 100 WHERE id=2Row id=2NoneNoRow id=2 locked by T2
5T1UPDATE accounts SET balance = balance + 100 WHERE id=2Row id=1Row id=2NoT1 waits for lock on row id=2
6T2UPDATE accounts SET balance = balance - 100 WHERE id=1Row id=2Row id=1YesDeadlock detected: T1 waits for T2, T2 waits for T1
7SystemDeadlock resolutionNoneNoneYesRollback T2 to break deadlock
8T1Resumes and completesRow id=1 and id=2NoneNoT1 commits successfully
9T2Restart transactionNoneNoneNoT2 can retry after rollback
💡 Deadlock detected at step 6; system rolls back one transaction to resolve.
Variable Tracker
VariableStartAfter Step 2After Step 4After Step 5After Step 6After Step 7Final
T1_locked_rowsNoneRow id=1Row id=1Row id=1Row id=1Row id=1None after commit
T2_locked_rowsNoneNoneRow id=2Row id=2Row id=2None after rollbackNone
T1_waiting_forNoneNoneNoneRow id=2Row id=2NoneNone
T2_waiting_forNoneNoneNoneNoneRow id=1NoneNone
Deadlock_statusNoNoNoNoYesResolvedNo
Key Moments - 3 Insights
Why does Transaction 1 wait at step 5?
At step 5 in the execution_table, Transaction 1 tries to lock row id=2, but Transaction 2 already holds that lock, so T1 must wait.
How does the system detect the deadlock?
At step 6, the system sees that T1 waits for T2 and T2 waits for T1, creating a cycle. This cycle is the deadlock detected.
What happens after the deadlock is detected?
At step 7, the system rolls back Transaction 2 to release its locks, allowing Transaction 1 to continue and complete.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 5, what resource is Transaction 1 waiting for?
ANo resource, it proceeds
BRow id=1
CRow id=2
DRow id=3
💡 Hint
Check the 'Waits For' column at step 5 in the execution_table.
At which step does the deadlock get detected?
AStep 6
BStep 7
CStep 4
DStep 9
💡 Hint
Look for 'Deadlock Detected' column marked 'Yes' in the execution_table.
If the system did not roll back Transaction 2 at step 7, what would happen?
ABoth transactions would complete successfully
BDeadlock would persist and block both transactions
CTransaction 1 would automatically commit
DTransaction 2 would commit first
💡 Hint
Refer to the 'Result' column at step 7 and the concept of deadlock resolution.
Concept Snapshot
Deadlock occurs when two transactions wait for each other's locked resources.
MySQL detects deadlocks by finding cycles in waiting.
It resolves deadlocks by rolling back one transaction.
Use transactions carefully to minimize deadlocks.
Check locks and wait states to debug deadlocks.
Full Transcript
Deadlock happens when two transactions lock resources and each waits for the other to release a lock. In the example, Transaction 1 locks row id=1 and waits for row id=2 locked by Transaction 2. Transaction 2 locks row id=2 and waits for row id=1 locked by Transaction 1. This cycle causes a deadlock. MySQL detects this cycle and resolves it by rolling back one transaction, here Transaction 2. After rollback, Transaction 1 can continue and commit. Understanding which transaction waits for which resource helps detect deadlocks. Rolling back one transaction breaks the cycle and allows progress.

Practice

(1/5)
1. What is a deadlock in MySQL InnoDB storage engine?
easy
A. A type of backup failure during database replication.
B. A syntax error in SQL queries causing transaction failure.
C. A temporary network disconnection between client and server.
D. A situation where two or more transactions wait indefinitely for each other to release locks.

Solution

  1. Step 1: Understand transaction locking

    Transactions acquire locks on data to ensure consistency. If two transactions wait for each other's locks, progress stops.
  2. Step 2: Define deadlock

    This waiting cycle with no resolution is called a deadlock, causing transactions to block indefinitely.
  3. Final Answer:

    A situation where two or more transactions wait indefinitely for each other to release locks. -> Option D
  4. Quick Check:

    Deadlock = Transactions waiting on each other [OK]
Hint: Deadlock means transactions block each other forever [OK]
Common Mistakes:
  • Confusing deadlock with syntax errors
  • Thinking deadlock is a network issue
  • Assuming deadlock is a backup problem
2. Which MySQL command helps you check the latest deadlock information in InnoDB?
easy
A. SHOW PROCESSLIST;
B. SHOW ENGINE INNODB STATUS;
C. SHOW TRANSACTION LOCKS;
D. SHOW DEADLOCKS;

Solution

  1. Step 1: Identify command for deadlock info

    MySQL does not have a direct SHOW DEADLOCKS command, but SHOW ENGINE INNODB STATUS shows detailed InnoDB info including deadlocks.
  2. Step 2: Confirm other options

    SHOW PROCESSLIST shows running threads, not deadlocks. SHOW TRANSACTION LOCKS is invalid syntax.
  3. Final Answer:

    SHOW ENGINE INNODB STATUS; -> Option B
  4. Quick Check:

    SHOW ENGINE INNODB STATUS = Deadlock info [OK]
Hint: Use SHOW ENGINE INNODB STATUS for deadlock details [OK]
Common Mistakes:
  • Using non-existent SHOW DEADLOCKS command
  • Confusing PROCESSLIST with deadlock info
  • Trying SHOW TRANSACTION LOCKS which is invalid
3. Consider two transactions T1 and T2 running concurrently:
-- T1: START TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;

-- T2: START TRANSACTION;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;

What is the likely outcome if both run at the same time without deadlock prevention?
medium
A. A deadlock occurs causing one transaction to be rolled back.
B. Both transactions complete successfully without waiting.
C. Both transactions fail with syntax errors.
D. Transactions run sequentially without any lock conflicts.

Solution

  1. Step 1: Analyze lock acquisition order

    T1 locks account id=1 first, then id=2. T2 locks id=2 first, then id=1. This creates a circular wait.
  2. Step 2: Identify deadlock

    Because each transaction waits for the other's locked row, a deadlock occurs. MySQL detects this and rolls back one transaction.
  3. Final Answer:

    A deadlock occurs causing one transaction to be rolled back. -> Option A
  4. Quick Check:

    Opposite lock order = Deadlock and rollback [OK]
Hint: Opposite lock order in transactions causes deadlock [OK]
Common Mistakes:
  • Assuming both transactions succeed without conflict
  • Thinking syntax errors cause failure
  • Believing transactions run sequentially automatically
4. You have this MySQL transaction code causing deadlocks:
START TRANSACTION;
UPDATE products SET stock = stock - 1 WHERE id = 10;
UPDATE orders SET status = 'processed' WHERE id = 100;
COMMIT;

How can you fix deadlocks by changing the transaction?
medium
A. Keep transactions short and access tables in the same order everywhere.
B. Add a LOCK TABLES statement before updates.
C. Use multiple COMMIT statements inside the transaction.
D. Disable autocommit mode.

Solution

  1. Step 1: Understand deadlock causes

    Deadlocks often happen when transactions lock tables in different orders or run too long holding locks.
  2. Step 2: Apply prevention best practice

    Keeping transactions short and always locking tables in the same order prevents circular waits and deadlocks.
  3. Final Answer:

    Keep transactions short and access tables in the same order everywhere. -> Option A
  4. Quick Check:

    Short, ordered transactions prevent deadlocks [OK]
Hint: Short, consistent lock order avoids deadlocks [OK]
Common Mistakes:
  • Thinking LOCK TABLES solves deadlocks alone
  • Using multiple COMMITs inside one transaction
  • Confusing autocommit disabling with deadlock fix
5. You want to prevent deadlocks in a high-traffic MySQL application. Which combination of strategies is best?
  • 1. Keep transactions short
  • 2. Set innodb_lock_wait_timeout to a low value
  • 3. Use consistent lock order in all transactions
  • 4. Disable foreign key constraints
hard
A. 1 and 4 only
B. 2 and 4 only
C. 1, 2, and 3 only
D. All four strategies

Solution

  1. Step 1: Evaluate each strategy

    Keeping transactions short and consistent lock order reduce deadlocks. Setting a low innodb_lock_wait_timeout helps detect and abort deadlocks quickly.
  2. Step 2: Assess disabling foreign keys

    Disabling foreign keys can cause data integrity issues and does not prevent deadlocks effectively.
  3. Final Answer:

    1, 2, and 3 only -> Option C
  4. Quick Check:

    Short, timeout, order = Deadlock prevention [OK]
Hint: Short transactions + timeout + lock order prevent deadlocks [OK]
Common Mistakes:
  • Disabling foreign keys to prevent deadlocks
  • Ignoring lock wait timeout settings
  • Not enforcing consistent lock order
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard