{
    "slug": "deadlock",
    "term": "Deadlock",
    "category": "concurrency",
    "difficulty": "intermediate",
    "short": "A deadlock occurs when two or more processes each hold a resource the other needs — both wait forever. Prevention requires consistent lock ordering or timeouts.",
    "long": "Classic deadlock: Thread A holds Lock 1, wants Lock 2. Thread B holds Lock 2, wants Lock 1. Both wait forever. Four conditions (Coffman): mutual exclusion, hold and wait, no preemption, circular wait. Breaking any one prevents deadlock. Strategies: (1) Lock ordering — always acquire locks in the same order. (2) Timeouts — acquire with timeout, retry. (3) Deadlock detection — detect cycles and break them. (4) Avoid nested locks — flat locking patterns. In PHP/databases: deadlocks occur in MySQL when two transactions update rows in different orders. MySQL auto-detects and kills one transaction — catch PDOException with SQLSTATE 40001.",
    "aliases": [],
    "tags": [
        "concurrency",
        "deadlock",
        "database",
        "locking"
    ],
    "misconception": "Deadlocks only happen in multi-threaded programs — database deadlocks are extremely common in PHP applications with concurrent transactions updating multiple rows.",
    "why_it_matters": "Database deadlocks silently fail requests in production unless caught and retried — they're a common source of mysterious 500 errors under load.",
    "common_mistakes": [
        "Not retrying on MySQL deadlock error (SQLSTATE 40001).",
        "Acquiring database row locks in different orders across transactions.",
        "Holding application-level locks while waiting for DB locks."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "race_condition",
        "mutex",
        "optimistic_locking",
        "database_migrations"
    ],
    "prerequisites": [
        "race_condition",
        "database_transactions"
    ],
    "refs": [
        "https://dev.mysql.com/doc/refman/8.0/en/innodb-deadlocks.html"
    ],
    "bad_code": "// Transaction A: locks user then order\n// Transaction B: locks order then user\n// → Deadlock\nDB::transaction(function() use ($userId, $orderId) {\n    User::lockForUpdate()->find($userId);\n    Order::lockForUpdate()->find($orderId);\n});",
    "good_code": "// Consistent lock order (always user before order):\nDB::transaction(function() use ($userId, $orderId) {\n    $ids = [$userId, $orderId];\n    sort($ids); // Consistent order prevents deadlock\n    foreach ($ids as $id) { /* lock in order */ }\n});\n\n// Catch and retry deadlocks:\ntry {\n    DB::transaction(fn() => processOrder($orderId));\n} catch (\\PDOException $e) {\n    if ($e->getCode() === '40001') {\n        // Deadlock — retry once\n        DB::transaction(fn() => processOrder($orderId));\n    } else throw $e;\n}",
    "quick_fix": "Always acquire locks in a consistent order. Set lock timeouts. Catch PDOException SQLSTATE 40001 and retry. Use optimistic locking to avoid locks entirely.",
    "severity": "high",
    "effort": "medium",
    "created": "2026-03-23",
    "updated": "2026-03-23",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/deadlock",
        "html_url": "https://codeclaritylab.com/glossary/deadlock",
        "json_url": "https://codeclaritylab.com/glossary/deadlock.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": "[Deadlock](https://codeclaritylab.com/glossary/deadlock) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/deadlock"
            }
        }
    }
}