Lab 08: Deadlocks & Detection

Time: 40 minutes | Level: Practitioner | DB: MySQL 8.0 + PostgreSQL 15

A deadlock occurs when two transactions each hold a lock the other needs, creating a circular wait. Both databases detect and resolve deadlocks automatically — but understanding them lets you prevent them.


Step 1 — How Deadlocks Occur

Transaction A                    Transaction B
─────────────────────────────    ─────────────────────────────
LOCK row 1 (success)             LOCK row 2 (success)
LOCK row 2 → WAITING             LOCK row 1 → WAITING
             ↑                                ↑
             └──────── DEADLOCK ──────────────┘

The database's deadlock detector finds the cycle and aborts the transaction with lower cost (or younger start time).


Step 2 — MySQL Deadlock Settings

-- Check deadlock detection (default: ON)
SELECT @@innodb_deadlock_detect;
-- 1 = ON (immediate detection)

-- Lock wait timeout
SELECT @@innodb_lock_wait_timeout;
-- 50 seconds default

-- In high-throughput systems, you might set:
SET GLOBAL innodb_lock_wait_timeout = 5;

-- View recent deadlock
SHOW ENGINE INNODB STATUS\G
-- Look for: LATEST DETECTED DEADLOCK section

📸 Verified Output:


Step 3 — Intentional Deadlock Demo (MySQL)

Run these in two simultaneous MySQL sessions:

💡 When MySQL detects a deadlock, it rolls back the smaller transaction (fewer undo log records). Your application should catch error 1213 and retry.


Step 4 — MySQL: Reading INNODB STATUS

The LATEST DETECTED DEADLOCK section shows:


Step 5 — PostgreSQL: Detecting Locks

📸 Verified Output:


Step 6 — PostgreSQL: Deadlock Demo

Run in two separate psql sessions simultaneously:

One session receives:

💡 PostgreSQL deadlock_timeout (default 1s) is how long to wait before checking for deadlocks. Lower it for fast-fail; raise it to reduce overhead.


Step 7 — Deadlock Prevention Strategies

Strategy 1: Lock Ordering Convention

Always acquire locks in a consistent order (e.g., always lock by ID ascending):

Strategy 2: Minimize Transaction Duration

Strategy 3: Use Advisory Locks


Step 8 — Capstone: Transfer Function with Deadlock Prevention


Summary

Topic
MySQL
PostgreSQL

Deadlock detection

Automatic, immediate

After deadlock_timeout (1s)

Victim choice

Smaller transaction

Youngest/cheapest

View deadlock

SHOW ENGINE INNODB STATUS

Server log + pg_stat_activity

Error code

1213

deadlock_detected

Lock timeout

innodb_lock_wait_timeout

lock_timeout GUC

Prevention

Lock ordering, short Tx

Lock ordering, advisory locks

Last updated