{
    "slug": "saga_pattern",
    "term": "Saga Pattern",
    "category": "messaging",
    "difficulty": "advanced",
    "short": "The Saga pattern manages distributed transactions across services using a sequence of local transactions — each step publishes an event, and compensating transactions undo completed steps on failure.",
    "long": "Distributed transactions across microservices can't use 2PC (too slow, too coupled). Saga: a sequence of local transactions (T1, T2, ..., Tn) where each Ti publishes an event triggering Ti+1. On failure at Ti: run compensating transactions (C(i-1), ..., C1) to undo. Two styles: choreography (each service publishes events and other services react — no central coordinator) and orchestration (a Saga orchestrator sends commands to services and handles failures centrally). Choreography: decoupled but hard to trace. Orchestration: easier to monitor and debug. PHP: Symfony Messenger workflows, custom saga state machine.",
    "aliases": [],
    "tags": [
        "messaging",
        "saga",
        "distributed-transactions",
        "microservices"
    ],
    "misconception": "Sagas provide ACID guarantees — they provide ACI (no isolation). Other transactions can see intermediate saga state. Use compensating logic, not database rollback.",
    "why_it_matters": "Saga is the standard solution for distributed transactions in microservices — without it, services either couple via distributed transactions (2PC) or leave data inconsistent.",
    "common_mistakes": [
        "No compensating transactions defined — partial failures leave data inconsistent.",
        "Choreography without correlation ID — impossible to trace saga execution.",
        "Not handling compensating transaction failures — need retry + alerting."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "message_broker",
        "outbox_pattern",
        "event_sourcing_messaging",
        "at_least_once_delivery"
    ],
    "prerequisites": [
        "message_broker",
        "outbox_pattern"
    ],
    "refs": [
        "https://microservices.io/patterns/data/saga.html"
    ],
    "bad_code": "// 2PC across services — tight coupling, deadlock risk:\n$coordinator->prepare('order-service', $orderTx);\n$coordinator->prepare('payment-service', $paymentTx);\n$coordinator->commit(); // Both or neither",
    "good_code": "// Saga orchestration:\n// 1. OrderService.createOrder() → publishes OrderCreated\n// 2. PaymentService.processPayment() → publishes PaymentProcessed\n// 3. InventoryService.reserveItems() → publishes ItemsReserved\n// On PaymentFailed: publish OrderCancelled → inventory released\n\n$sagaState = ['order_id' => $orderId, 'step' => 'payment', 'status' => 'pending'];\n// Orchestrator retries failed steps, triggers compensations on unrecoverable failure",
    "quick_fix": "Define compensating transactions for every step. Assign correlation ID to track saga state. Use orchestration for complex sagas (easier to debug). Persist saga state between steps.",
    "severity": "high",
    "effort": "high",
    "created": "2026-03-23",
    "updated": "2026-03-23",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/saga_pattern",
        "html_url": "https://codeclaritylab.com/glossary/saga_pattern",
        "json_url": "https://codeclaritylab.com/glossary/saga_pattern.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": "[Saga Pattern](https://codeclaritylab.com/glossary/saga_pattern) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/saga_pattern"
            }
        }
    }
}