{
    "slug": "optimistic_locking",
    "term": "Optimistic Locking",
    "category": "concurrency",
    "difficulty": "intermediate",
    "short": "Optimistic locking detects conflicts at commit time using a version number — no locks held during the transaction, high throughput for low-contention scenarios.",
    "long": "Pattern: read record with version number, modify, update WHERE version = read_version, check rows affected = 1. If 0 rows updated: conflict — retry or error. The version column increments on every update. No locks held between read and write — high throughput. Best for: low-contention scenarios (most updates succeed without conflict). Implementations: Doctrine ORM @Version annotation, JPA @Version, Hibernate. Database: UPDATE ... WHERE id = ? AND version = ?. Redis: WATCH/MULTI/EXEC (optimistic transaction). Contrast with pessimistic locking (SELECT FOR UPDATE — locks row immediately).",
    "aliases": [],
    "tags": [
        "concurrency",
        "optimistic-locking",
        "database",
        "orm"
    ],
    "misconception": "Optimistic locking prevents all conflicts — it detects them at commit time and requires application-level retry logic. Conflicts still occur but are handled gracefully.",
    "why_it_matters": "Optimistic locking enables high-throughput concurrent updates without holding DB row locks — essential for scenarios like inventory management where most updates don't conflict.",
    "common_mistakes": [
        "Not incrementing the version on every update — defeats the mechanism.",
        "Not handling the 0-rows-updated case — silent data loss.",
        "Using optimistic locking for high-contention scenarios — many retries degrade performance."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "pessimistic_locking",
        "race_condition",
        "mutex",
        "cas_operation"
    ],
    "prerequisites": [
        "race_condition",
        "database_transactions"
    ],
    "refs": [
        "https://en.wikipedia.org/wiki/Optimistic_concurrency_control"
    ],
    "bad_code": "// No conflict detection:\nSELECT qty FROM inventory WHERE id = 1;\n-- Another process also reads qty = 10\nUPDATE inventory SET qty = 9 WHERE id = 1; -- Both processes set 9, losing one decrement",
    "good_code": "-- Read:\nSELECT qty, version FROM inventory WHERE id = 1;\n-- (qty=10, version=5)\n\n-- Write with version check:\nUPDATE inventory\nSET qty = 9, version = version + 1\nWHERE id = 1 AND version = 5;\n-- 0 rows updated? Another process got there first — retry or error",
    "quick_fix": "Add a version column. Check rows-affected after UPDATE ... WHERE version = N. If 0: retry or throw ConcurrentModificationException.",
    "severity": "medium",
    "effort": "medium",
    "created": "2026-03-23",
    "updated": "2026-03-23",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/optimistic_locking",
        "html_url": "https://codeclaritylab.com/glossary/optimistic_locking",
        "json_url": "https://codeclaritylab.com/glossary/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/optimistic_locking) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/optimistic_locking"
            }
        }
    }
}