{
    "slug": "db_deadlocks",
    "term": "Database Deadlocks",
    "category": "database",
    "difficulty": "advanced",
    "short": "A situation where two or more transactions hold locks the other needs, each waiting indefinitely — resolved by the database killing one transaction.",
    "long": "Deadlocks occur when transaction A holds a lock on row 1 and waits for row 2, while transaction B holds row 2 and waits for row 1. Databases detect this cycle and roll back the transaction with the smallest undo log (the 'victim'). The application must retry the victim transaction. Prevention strategies: acquire locks in a consistent order, keep transactions short, use SELECT ... FOR UPDATE to acquire all locks upfront.",
    "aliases": [
        "deadlock",
        "circular wait",
        "lock cycle"
    ],
    "tags": [
        "database",
        "concurrency",
        "transactions",
        "locking"
    ],
    "misconception": "Deadlocks are always application bugs — databases handle them automatically by rolling back one transaction, but the application must retry to complete the operation.",
    "why_it_matters": "Unhandled deadlock exceptions cause silent data inconsistency when the rolled-back transaction is not retried — in high-concurrency systems they happen regularly and must be expected.",
    "common_mistakes": [
        "Not catching and retrying deadlock exceptions (error code 1213 in MySQL, 40P01 in PostgreSQL).",
        "Accessing rows in different orders in different transactions — consistent lock ordering prevents deadlocks.",
        "Long transactions that hold locks for seconds instead of milliseconds.",
        "Not using SELECT ... FOR UPDATE when a read-then-write sequence must be atomic."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "db_transactions",
        "db_isolation_levels",
        "race_condition",
        "optimistic_locking"
    ],
    "prerequisites": [
        "db_transactions",
        "db_locking_strategies",
        "race_condition"
    ],
    "refs": [
        "https://dev.mysql.com/doc/refman/8.0/en/innodb-deadlocks.html",
        "https://www.postgresql.org/docs/current/explicit-locking.html"
    ],
    "bad_code": "// Inconsistent lock order — deadlock prone:\n// Transaction A: lock user 1, then lock user 2\n// Transaction B: lock user 2, then lock user 1 — deadlock!\n$pdo->beginTransaction();\n$pdo->query('SELECT ... FROM accounts WHERE id = ' . $fromId . ' FOR UPDATE');\n$pdo->query('SELECT ... FROM accounts WHERE id = ' . $toId . ' FOR UPDATE');",
    "good_code": "// Consistent lock order — always lock lower ID first:\n$pdo->beginTransaction();\n$ids = [$fromId, $toId];\nsort($ids); // Always acquire locks in ascending ID order\nforeach ($ids as $id) {\n    $pdo->query('SELECT ... FROM accounts WHERE id = ' . $id . ' FOR UPDATE');\n}",
    "quick_fix": "Acquire locks in a consistent order across all transactions; keep transactions short; use SELECT FOR UPDATE only on rows you will modify in the same transaction",
    "severity": "high",
    "effort": "high",
    "created": "2026-03-15",
    "updated": "2026-03-22",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/db_deadlocks",
        "html_url": "https://codeclaritylab.com/glossary/db_deadlocks",
        "json_url": "https://codeclaritylab.com/glossary/db_deadlocks.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[Database Deadlocks](https://codeclaritylab.com/glossary/db_deadlocks) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/db_deadlocks"
            }
        }
    }
}