{
    "slug": "mysql_optimistic_locking",
    "term": "Optimistic Locking",
    "category": "database",
    "difficulty": "advanced",
    "short": "A concurrency pattern using a version column to detect conflicting concurrent writes — no row locks held between read and write.",
    "long": "A version INT (or updated_at DATETIME) column is incremented on every UPDATE. The WHERE clause includes AND version = :expected — if rowCount() returns 0, another process changed the row first. Advantages: no lock contention, scales well for read-heavy workloads. Disadvantages: requires retry logic, degrades under high write contention on the same row. Preferred over pessimistic locking for most web application patterns.",
    "aliases": [
        "optimistic concurrency control",
        "version column pattern",
        "compare and swap database"
    ],
    "tags": [
        "database",
        "mysql",
        "concurrency",
        "pattern"
    ],
    "misconception": "Optimistic locking is always better than pessimistic locking. Under high write contention on the same row, optimistic locking causes excessive retries — pessimistic locking is more predictable in that case.",
    "why_it_matters": "Pessimistic locking holds locks during the full read-think-write cycle causing timeouts. Optimistic locking eliminates contention — conflicting writes are detected at commit time, not locked upfront.",
    "common_mistakes": [
        "Not implementing retry logic — silently discarding the failed update.",
        "Using updated_at as the version — two updates within the same second both pass the check.",
        "Using optimistic locking for financial operations where a lost update is unacceptable."
    ],
    "when_to_use": [
        "Use for read-heavy workflows where conflicts are infrequent.",
        "Use when holding locks between read and write is impractical — e.g. user edits a form for 30 seconds."
    ],
    "avoid_when": [
        "Avoid when conflict rate is high — retries become the dominant code path.",
        "Do not use for financial transfers where a missed update is a data integrity failure."
    ],
    "related": [
        "mysql_select_for_update",
        "pdo_transactions",
        "db_deadlocks"
    ],
    "prerequisites": [
        "pdo_transactions",
        "pdo_rowcount"
    ],
    "refs": [
        "https://martinfowler.com/eaaCatalog/optimisticOfflineLock.html"
    ],
    "bad_code": "// Last write wins — concurrent change silently overwritten\n$pdo->prepare('UPDATE products SET name = ? WHERE id = ?')->execute([$newName, $id]);",
    "good_code": "$stmt = $pdo->prepare('SELECT id, name, version FROM products WHERE id = ?');\n$stmt->execute([$id]);\n$product = $stmt->fetch();\n\n$stmt = $pdo->prepare(\n    'UPDATE products SET name = ?, version = version + 1 WHERE id = ? AND version = ?'\n);\n$stmt->execute([$newName, $id, $product['version']]);\nif ($stmt->rowCount() === 0) {\n    throw new ConcurrentModificationException('Row was modified by another process — retry');\n}",
    "quick_fix": "Add a version INT NOT NULL DEFAULT 0 column, increment in every UPDATE, check rowCount() === 1 after execute()",
    "effort": "medium",
    "created": "2026-03-31",
    "updated": "2026-03-31",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/mysql_optimistic_locking",
        "html_url": "https://codeclaritylab.com/glossary/mysql_optimistic_locking",
        "json_url": "https://codeclaritylab.com/glossary/mysql_optimistic_locking.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": "[Optimistic Locking](https://codeclaritylab.com/glossary/mysql_optimistic_locking) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/mysql_optimistic_locking"
            }
        }
    }
}