{
    "slug": "two_phase_commit",
    "term": "Two-Phase Commit (2PC)",
    "category": "architecture",
    "difficulty": "advanced",
    "short": "A distributed transaction protocol ensuring all nodes commit or all roll back — providing strong atomicity across multiple databases.",
    "long": "2PC is a consensus protocol: Phase 1 (Prepare) — a coordinator asks all participants to lock resources and vote commit/abort. Phase 2 (Commit/Rollback) — if all voted commit, the coordinator instructs commit; any abort triggers a full rollback. 2PC guarantees ACID atomicity across multiple databases but has significant costs: blocking (if the coordinator crashes after prepare, participants remain locked indefinitely), two network round trips per transaction, and reduced throughput. Most modern distributed systems prefer the Saga pattern for long-lived business transactions and accept eventual consistency rather than paying 2PC's availability and latency costs.",
    "aliases": [
        "2PC",
        "two-phase commit",
        "distributed commit"
    ],
    "tags": [
        "architecture",
        "distributed",
        "database",
        "transactions"
    ],
    "misconception": "Two-phase commit solves distributed transactions reliably. 2PC is blocking — if the coordinator fails after phase one, participants are stuck waiting indefinitely. This is why 2PC is avoided in modern distributed systems in favour of sagas and eventual consistency.",
    "why_it_matters": "Two-phase commit coordinates atomic transactions across multiple databases or services — ensuring all participants commit or all roll back, preventing partial distributed transactions.",
    "common_mistakes": [
        "Using 2PC for high-throughput operations — the coordinator is a bottleneck and failure point.",
        "Not handling coordinator failure — if the coordinator crashes between prepare and commit, participants are blocked.",
        "Using 2PC when saga or outbox patterns would provide better availability with eventual consistency.",
        "Not testing the failure path — 2PC rollback code is rarely exercised and often broken."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "acid_properties",
        "saga_pattern",
        "cap_theorem",
        "optimistic_locking"
    ],
    "prerequisites": [
        "db_transactions",
        "distributed_tracing",
        "saga_pattern"
    ],
    "refs": [
        "https://en.wikipedia.org/wiki/Two-phase_commit_protocol"
    ],
    "bad_code": "// Distributed transaction without 2PC — inconsistent state on failure:\nfunction transferFunds(): void {\n    $bankA->debit($amount);   // Succeeds\n    $bankB->credit($amount);  // Network failure — money lost!\n}\n// 2PC prepare phase: both banks lock funds\n// 2PC commit phase: both banks execute if both prepared successfully\n// Rollback phase: both debit/credit reversed if either failed",
    "good_code": "// 2PC: coordinator asks all participants to PREPARE, then COMMIT\n// Ensures atomicity across distributed resources\n\n// PHP example: transfer across two databases\nfunction transfer(PDO \\$dbA, PDO \\$dbB, int \\$amount): void {\n    // Phase 1: PREPARE\n    \\$dbA->beginTransaction();\n    \\$dbB->beginTransaction();\n\n    try {\n        \\$dbA->exec(\"UPDATE accounts SET balance = balance - \\$amount WHERE id = 1\");\n        \\$dbB->exec(\"UPDATE accounts SET balance = balance + \\$amount WHERE id = 2\");\n\n        // Phase 2: COMMIT both\n        \\$dbA->commit();\n        \\$dbB->commit();\n    } catch (\\Throwable \\$e) {\n        \\$dbA->rollBack();\n        \\$dbB->rollBack();\n        throw \\$e;\n    }\n}\n\n// 2PC is blocking — prefer Saga pattern for long-running distributed transactions",
    "quick_fix": "Avoid 2PC in PHP microservices — use the Saga pattern with compensating transactions instead; 2PC requires all participants to stay locked during the protocol which kills throughput",
    "severity": "medium",
    "effort": "high",
    "created": "2026-03-15",
    "updated": "2026-03-22",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/two_phase_commit",
        "html_url": "https://codeclaritylab.com/glossary/two_phase_commit",
        "json_url": "https://codeclaritylab.com/glossary/two_phase_commit.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": "[Two-Phase Commit (2PC)](https://codeclaritylab.com/glossary/two_phase_commit) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/two_phase_commit"
            }
        }
    }
}