Detecting database deadlocks

From jeremylongshore/claude-code-plugins-plus-skills · View interactive version

Detecting database deadlocks is an AI agent skill from the GitHub repository jeremylongshore/claude-code-plugins-plus-skills. Process use when you need to work with deadlock detection. This skill provides deadlock detection and resolution with comprehensive guidance and automation. Trigger with phrases like "detect deadlocks", "resolve deadlocks", or "prevent deadlocks".

How to use this skill

Skill file

Database Deadlock Detector

Overview

Detect, analyze, and prevent database deadlocks in PostgreSQL, MySQL, and MongoDB by examining lock wait graphs, parsing deadlock log entries, identifying the application code paths that cause lock ordering conflicts, and implementing preventive patterns.

Prerequisites

Instructions

  1. Check for currently blocked transactions and their blockers:
  1. Parse recent deadlock events from database logs:
  1. Construct the lock wait graph from the deadlock log. Map which transaction held which lock and which lock each transaction was waiting for. The circular dependency reveals the deadlock cycle. Identify the specific rows or index ranges involved.
  1. Trace the deadlocking queries back to application code. Use Grep to find the SQL statements in the codebase and identify the transaction boundaries (BEGIN/COMMIT blocks or ORM transaction decorators). Map the full sequence of operations within each transaction.
  1. Identify the root cause pattern:
  1. Implement deadlock prevention strategies:
  1. Add retry logic for deadlock victims. When the database aborts a transaction due to deadlock, catch the error (PostgreSQL error code 40P01, MySQL error code 1213) and retry the entire transaction up to 3 times with a short random delay.
  1. Monitor deadlock frequency over time. Create a query or script that counts deadlock events per hour from the database logs. Alert when deadlock frequency exceeds the baseline by more than 3x.
  1. For persistent deadlocks on specific tables, consider advisory locks (pg_advisory_lock() in PostgreSQL) to serialize access to contended resources at the application level, avoiding database-level lock contention entirely.
  1. Document all identified deadlock patterns, root causes, and fixes in a deadlock analysis report for the development team.

Output

Error Handling

| Error | Cause | Solution |

|-------|-------|---------|

| PostgreSQL error 40P01: deadlock detected | Circular lock dependency between transactions | Implement retry logic; fix lock ordering in application code; reduce transaction scope |

| MySQL error 1213: Deadlock found when trying to get lock | InnoDB detected circular wait in lock wait graph | Enable innodb_print_all_deadlocks; analyze SHOW ENGINE INNODB STATUS; implement retry logic |

| Lock wait timeout (not deadlock) | Transaction holding lock too long, exceeding lock_wait_timeout | Investigate the blocking transaction; increase timeout or implement NOWAIT; optimize the long-running transaction |

| Phantom deadlocks in monitoring | Transient lock waits resolved before deadlock detection runs | Increase monitoring frequency; use database deadlock log instead of snapshot queries; set deadlock_timeout lower |

| Deadlock frequency increases after schema change | New index or constraint creates additional lock targets | Analyze new lock patterns with EXPLAIN and pg_locks; adjust transaction scope to avoid locking new index entries |

Examples

Classic opposite-ordering deadlock in an order processing system: Transaction A processes order 100 (locks order row), then updates inventory for product 50 (waits for inventory lock). Transaction B processes order 200 with product 50 (locks inventory row), then updates order 100 status (waits for order lock). Fix: always lock inventory first, then order, regardless of the business flow.

MySQL gap lock deadlock on a queue table: Two workers concurrently DELETE FROM job_queue WHERE status = 'pending' LIMIT 1. InnoDB gap locks on the index range conflict even though the workers target different rows. Fix: use SELECT ... FOR UPDATE SKIP LOCKED to skip already-locked rows, or add unique job IDs and target specific rows.

Foreign key deadlock between parent and child inserts: Concurrent transactions inserting into order_items (child) acquire shared locks on orders (parent) for FK validation. A third transaction updating orders requires an exclusive lock and deadlocks with the shared FK locks. Fix: explicitly SELECT ... FOR UPDATE on the parent order row before inserting child items.

Resources

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.