{
    "slug": "db_transactions",
    "term": "Database Transactions",
    "category": "database",
    "difficulty": "intermediate",
    "short": "A sequence of SQL operations treated as a single atomic unit — all succeed or all roll back — enforcing ACID guarantees.",
    "long": "A transaction wraps multiple SQL statements so they either all commit or all roll back on error. In PHP with PDO: $pdo->beginTransaction(); ... $pdo->commit(); with $pdo->rollBack() in a catch block. Key behaviours: implicit vs explicit transactions (autocommit mode), savepoints for nested rollback to a known point, and isolation levels controlling visibility of concurrent changes. Transaction scope should be as short as possible — open transactions hold locks. Avoid transactions spanning HTTP requests (leave a transaction open between user steps). Doctrine's EntityManager::flush() wraps all pending changes in one transaction. Eloquent's DB::transaction(fn) automatically retries on deadlock up to a configurable count.",
    "aliases": [
        "database transactions",
        "BEGIN COMMIT ROLLBACK",
        "transaction isolation"
    ],
    "tags": [
        "database",
        "sql",
        "acid",
        "reliability"
    ],
    "misconception": "Wrapping everything in a transaction guarantees data integrity. Transactions provide ACID guarantees, but long-running transactions hold locks, increase deadlock risk, and can cause timeout cascades. Transactions should be as short as possible — business logic and external calls should happen outside transaction boundaries.",
    "why_it_matters": "Database transactions group multiple operations into an atomic unit — if any step fails, the whole transaction rolls back, preventing partial updates that leave data in an inconsistent state.",
    "common_mistakes": [
        "Multi-step operations not wrapped in a transaction — a crash between steps corrupts data.",
        "Transactions that span user interactions (long transactions) — lock contention degrades performance.",
        "Catching exceptions inside a transaction and continuing instead of rolling back.",
        "Not using transactions for read-modify-write sequences — race conditions occur without locking."
    ],
    "when_to_use": [
        "Any operation that modifies multiple rows or tables that must succeed or fail together.",
        "Financial operations — debiting one account and crediting another must be atomic.",
        "Preventing partial writes that leave data in an inconsistent state.",
        "Operations that check a condition and act on it — wrap the check and write together to prevent TOCTOU races."
    ],
    "avoid_when": [
        "Long-running transactions that hold locks for seconds — other queries queue behind and throughput drops.",
        "Transactions spanning multiple microservices — use saga patterns or two-phase commit instead.",
        "Read-only operations that need no consistency guarantees — transactions add overhead with no benefit.",
        "Transactions containing external HTTP calls — the network call can hang while locks are held indefinitely."
    ],
    "related": [
        "acid_properties",
        "two_phase_commit",
        "optimistic_locking",
        "database_migrations"
    ],
    "prerequisites": [
        "acid_properties",
        "pdo",
        "race_condition"
    ],
    "refs": [
        "https://www.php.net/manual/en/pdo.transactions.php"
    ],
    "bad_code": "// No transaction — if second query fails, first already committed\n$pdo->exec('UPDATE accounts SET balance = balance - 100 WHERE id = 1');\n$pdo->exec('UPDATE accounts SET balance = balance + 100 WHERE id = 2');",
    "good_code": "try {\n    $pdo->beginTransaction();\n    $pdo->exec('UPDATE accounts SET balance = balance - 100 WHERE id = 1');\n    $pdo->exec('UPDATE accounts SET balance = balance + 100 WHERE id = 2');\n    $pdo->commit();\n} catch (\\Throwable $e) {\n    $pdo->rollBack();\n    throw $e;\n}",
    "quick_fix": "Use try/catch around PDO transactions: beginTransaction in try, rollback in catch, commit only after all operations succeed — never commit on exception",
    "severity": "high",
    "effort": "low",
    "created": "2026-03-15",
    "updated": "2026-03-25",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/db_transactions",
        "html_url": "https://codeclaritylab.com/glossary/db_transactions",
        "json_url": "https://codeclaritylab.com/glossary/db_transactions.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 Transactions](https://codeclaritylab.com/glossary/db_transactions) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/db_transactions"
            }
        }
    }
}