[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79DX7X9Y83YJ9V3RVMRS7EG":3,"skill-same:01M79DX7X9Y83YJ9V3RVMRS7EG":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M79DX7X9Y83YJ9V3RVMRS7EG","event-driven-architecture-saga-patterns",null,"Designing resilient, eventual-consistency distributed transactions using the Saga Pattern (Choreography and Orchestration). Includes Outbox Pattern, Change Data Capture (CDC), idempotent consumers, compensating transactions, dual-write prevention, and saga recovery mechanisms. Use when implementing distributed multi-service workflows without two-phase commit (2PC).","hamzabellouch\u002Fagent-skills","hamzabellouch","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F237856042?v=4","01M79BRYW7XAMK3YDWQEMTWGWS","Hamza Bellouch","01M79BRYWXQV3JK2TGVTX8GN2A",8,"MIT","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FProgramming\u002FBackend\u002FEvent_Driven_and_Messaging\u002Fevent-driven-architecture-saga-patterns\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: event-driven-architecture-saga-patterns\ndescription: Designing resilient, eventual-consistency distributed transactions using the Saga Pattern (Choreography and Orchestration). Includes Outbox Pattern, Change Data Capture (CDC), idempotent consumers, compensating transactions, dual-write prevention, and saga recovery mechanisms. Use when implementing distributed multi-service workflows without two-phase commit (2PC).\n---\n\n# Event-Driven Architecture: Saga Patterns & Eventual Consistency Guide\n\n## 1. Architectural Foundations: BASE over ACID\n\nIn microservices architectures, each service maintains its own private database to ensure loose coupling and independent scalability. This renders distributed ACID transactions impossible without two-phase commit (2PC). However, 2PC introduces high latency, synchronous blocking, single points of failure, and deadlocks across service boundaries.\n\nThe **Saga Pattern** manages distributed transactions as a sequence of local transactions. Each local transaction updates a single service's database and emits an event or message to trigger the next step. If a step fails, the Saga executes **compensating transactions** in reverse order to undo changes and restore data consistency.\n\n### 1.1 Transaction Classification\n\n```\n[ Local Tx 1: Compensable ] ──► [ Local Tx 2: Pivot ] ──► [ Local Tx 3: Retryable ]\n        │                             │                         │\n   (Rollbackable)              (Point of No Return)       (Guaranteed Success)\n```\n\n- **Compensable Transactions**: Transactions that can be undone by running an explicit compensating transaction.\n- **Pivot Transaction**: The critical decision point of the Saga. Once the pivot transaction succeeds, the Saga MUST go to completion. It cannot be compensated.\n- **Retryable Transactions**: Transactions that follow the pivot point and are guaranteed to eventually succeed through retries.\n\n---\n\n## 2. Saga Execution Models: Choreography vs. Orchestration\n\n```\nCHOREOGRAPHY:\n[ Order Service ] ── OrderCreated ──► [ Payment Service ] ── PaymentProcessed ──► [ Inventory Service ]\n\nORCHESTRATION:\n                        ┌──► [ Payment Service ]\n                        │\n[ Saga Orchestrator ] ──┼──► [ Inventory Service ]\n                        │\n                        └──► [ Shipping Service ]\n```\n\n### 2.1 Comparative Analysis\n\n| Dimension | Choreography Saga | Orchestration Saga |\n| :--- | :--- | :--- |\n| **Control Model** | Decentralized; services react to domain events. | Centralized; dedicated orchestrator directs participants. |\n| **Coupling** | Loosely coupled; services know events, not handlers. | Moderate coupling; orchestrator knows participant APIs. |\n| **State Visibility** | Distributed across service logs; hard to query global status. | Centralized state store; easy to track saga status. |\n| **Complexity** | Simple for small flows (2-3 steps); cyclic dependencies in large flows. | High initial setup; manages complex branching & parallel paths easily. |\n| **Failure Handling** | Complex cascading compensation logic across events. | Explicit compensation routines directed by orchestrator. |\n\n### 2.2 Decision Matrix\n- **Choose Choreography** when workflows are simple (2-3 microservices), linear, and teams want maximum domain event decoupling.\n- **Choose Orchestration** when workflows involve 4+ services, complex conditional branching, parallel execution steps, or require strict operational auditing.\n\n---\n\n## 3. Dual-Write Prevention: Transactional Outbox & CDC\n\nA major vulnerability in event-driven systems is the **Dual-Write Problem**: attempting to update a database and publish a message to a broker in a single code block without atomic guarantees.\n\n```\nWRONG (Dual Write Risk):\ndb.orders.insert(order);       \u002F\u002F Success\nbroker.publish(\"OrderCreated\"); \u002F\u002F Network Failure! -> DB & Broker state out of sync!\n```\n\n### 3.1 Transactional Outbox Pattern Architecture\n\n```\n[ Business Logic ]\n       │\n       ▼ (Single ACID Local DB Transaction)\n┌──────────────────────────────────────────────┐\n│  Service Database                            │\n│  ├── Orders Table:   [ Insert Order ]        │\n│  └── Outbox Table:   [ Insert Outbox Event ] │\n└──────────────────────────────────────────────┘\n       │\n       ▼ (Async Log Tailing \u002F CDC)\n[ Debezium \u002F Outbox Publisher ] ──► [ Message Broker (Kafka \u002F RabbitMQ) ]\n```\n\n1. Business record update and message metadata insertion are committed into the service's local database within a **single local ACID transaction**.\n2. A separate process (e.g., Debezium CDC or a dedicated polling worker) reads the `outbox` table and safely forwards events to the message broker with **at-least-once** delivery guarantees.\n\n---\n\n## 4. Idempotency & De-duplication Engineering\n\nBecause event delivery is **at-least-once**, consumers WILL receive duplicate events. Consumers must be designed to be completely **idempotent**.\n\n### 4.1 Idempotent Consumer Design Patterns\n\n1. **Natural Unique Key Constraints**: Insert incoming event processing results using database unique constraints (e.g., `PRIMARY KEY (payment_id)`).\n2. **Idempotency Key \u002F Deduplication Table**:\n   ```sql\n   CREATE TABLE processed_events (\n       event_id VARCHAR(128) PRIMARY KEY,\n       consumer_group VARCHAR(64) NOT NULL,\n       processed_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP\n   );\n   ```\n   Before processing logic begins, attempt atomic insertion into `processed_events`. If duplicate key violation occurs, skip processing and immediately ACK message.\n3. **State Machine Guardrails**: Only allow state transitions that are valid from the current state (e.g., `UPDATE orders SET status = 'PAID' WHERE id = :id AND status = 'PENDING'`).\n\n---\n\n## 5. Compensating Transactions & Failure Recovery\n\nCompensating transactions are inverse operations that semantically undo completed local transactions.\n\n### 5.1 Rules for Compensating Actions\n- **Must Be Idempotent**: A compensating step may be retried multiple times during recovery.\n- **Must Never Fail Permanently**: If a compensating action encounters transient errors, it must retry until successful. If business invariants prevent auto-compensation, route to a **Human-in-the-Loop (HITL)** DLQ queue.\n- **Semantic Rollback**: Compensation does not necessarily mean \"deleting\" rows. It often means applying a counter-action (e.g., issuing a credit refund rather than un-writing a credit charge).\n\n---\n\n## 6. Critical Anti-Patterns & Production Traps\n\n1. **Dual Writes without Outbox Pattern**: Updating local DB state and calling `broker.publish()` directly without outbox tables or transactional CDC.\n2. **Missing Compensating Triggers**: Implementing forward execution steps without defining corresponding inverse compensation handlers.\n3. **Cyclic Choreography Dependencies**: Service A triggers Service B, which triggers Service C, which triggers Service A again, creating un-traceable infinite loops.\n4. **Non-Idempotent Compensations**: Compensating transactions that double-credit or double-refund when retried.\n5. **Synchronous REST Calls inside Sagas**: Mixing blocking HTTP calls within asynchronous event-driven sagas, leading to thread pool exhaustion and cascading failures.\n\n---\n\n## 7. Production Code Reference\n\n### 7.1 Transactional Outbox Pattern in Python (SQLAlchemy)\n\n```python\nimport uuid\nimport json\nfrom datetime import datetime, timezone\nfrom sqlalchemy import create_engine, Column, String, Float, DateTime, Text\nfrom sqlalchemy.orm import declarative_base, sessionmaker\n\nBase = declarative_base()\n\nclass Order(Base):\n    __tablename__ = 'orders'\n    id = Column(String(64), primary_key=True)\n    customer_id = Column(String(64), nullable=False)\n    total_amount = Column(Float, nullable=False)\n    status = Column(String(32), nullable=False)\n\nclass OutboxEvent(Base):\n    __tablename__ = 'outbox'\n    id = Column(String(64), primary_key=True)\n    aggregate_type = Column(String(64), nullable=False)\n    aggregate_id = Column(String(64), nullable=False)\n    event_type = Column(String(64), nullable=False)\n    payload = Column(Text, nullable=False)\n    created_at = Column(DateTime(timezone=True), nullable=False)\n\nengine = create_engine(\"postgresql:\u002F\u002Fapp_user:secret@db.prod.internal:5432\u002Forders_db\")\nSessionLocal = sessionmaker(bind=engine)\n\ndef create_order_with_outbox(customer_id: str, amount: float) -> str:\n    session = SessionLocal()\n    order_id = f\"ord-{uuid.uuid4()}\"\n    event_id = f\"evt-{uuid.uuid4()}\"\n    \n    order = Order(\n        id=order_id,\n        customer_id=customer_id,\n        total_amount=amount,\n        status=\"PENDING_PAYMENT\"\n    )\n    \n    event_payload = json.dumps({\n        \"event_id\": event_id,\n        \"order_id\": order_id,\n        \"customer_id\": customer_id,\n        \"amount\": amount,\n        \"timestamp\": datetime.now(timezone.utc).isoformat()\n    })\n    \n    outbox_entry = OutboxEvent(\n        id=event_id,\n        aggregate_type=\"Order\",\n        aggregate_id=order_id,\n        event_type=\"OrderCreated\",\n        payload=event_payload,\n        created_at=datetime.now(timezone.utc)\n    )\n\n    try:\n        # Atomic single local ACID transaction\n        session.add(order)\n        session.add(outbox_entry)\n        session.commit()\n        return order_id\n    except Exception as e:\n        session.rollback()\n        raise RuntimeError(f\"Failed to create order atomically: {str(e)}\")\n    finally:\n        session.close()\n```\n\n### 7.2 Saga Orchestrator State Machine in TypeScript \u002F Node.js\n\n```typescript\ntype SagaState = 'STARTED' | 'PAYMENT_RESERVED' | 'INVENTORY_RESERVED' | 'COMPLETED' | 'FAILED' | 'COMPENSATING';\n\ninterface SagaContext {\n  sagaId: string;\n  orderId: string;\n  customerId: string;\n  amount: number;\n  items: Array\u003C{ sku: string; qty: number }>;\n  currentState: SagaState;\n  failureReason?: string;\n}\n\nexport class OrderSagaOrchestrator {\n  private context: SagaContext;\n\n  constructor(context: SagaContext) {\n    this.context = context;\n  }\n\n  async executeSaga(): Promise\u003Cvoid> {\n    try {\n      \u002F\u002F Step 1: Reserve Payment (Compensable)\n      await this.executeStep('PAYMENT_RESERVED', \n        () => this.callPaymentService('\u002Fpayments\u002Freserve', { amount: this.context.amount }),\n        () => this.callPaymentService('\u002Fpayments\u002Frefund', { amount: this.context.amount })\n      );\n\n      \u002F\u002F Step 2: Reserve Inventory (Compensable)\n      await this.executeStep('INVENTORY_RESERVED', \n        () => this.callInventoryService('\u002Finventory\u002Freserve', { items: this.context.items }),\n        () => this.callInventoryService('\u002Finventory\u002Frelease', { items: this.context.items })\n      );\n\n      \u002F\u002F Step 3: Pivot Point - Approve Order (Retryable)\n      this.context.currentState = 'COMPLETED';\n      await this.updateSagaState('COMPLETED');\n      await this.callOrderService(`\u002Forders\u002F${this.context.orderId}\u002Fapprove`, {});\n\n    } catch (error: any) {\n      console.error(`Saga ${this.context.sagaId} failed at state ${this.context.currentState}: ${error.message}`);\n      this.context.failureReason = error.message;\n      await this.compensateSaga();\n    }\n  }\n\n  private async executeStep(\n    targetState: SagaState, \n    action: () => Promise\u003Cvoid>, \n    compensation: () => Promise\u003Cvoid>\n  ): Promise\u003Cvoid> {\n    try {\n      await action();\n      this.context.currentState = targetState;\n      await this.updateSagaState(targetState);\n    } catch (err) {\n      \u002F\u002F Register compensation step for reverse execution\n      this.compensations.push(compensation);\n      throw err;\n    }\n  }\n\n  private compensations: Array\u003C() => Promise\u003Cvoid>> = [];\n\n  private async compensateSaga(): Promise\u003Cvoid> {\n    this.context.currentState = 'COMPENSATING';\n    await this.updateSagaState('COMPENSATING');\n\n    \u002F\u002F Run compensations in reverse order\n    for (const compensation of this.compensations.reverse()) {\n      let retryCount = 0;\n      let success = false;\n      \n      while (!success && retryCount \u003C 5) {\n        try {\n          await compensation();\n          success = true;\n        } catch (compErr) {\n          retryCount++;\n          console.error(`Compensation retry ${retryCount} failed:`, compErr);\n          await new Promise(res => setTimeout(res, 1000 * Math.pow(2, retryCount)));\n        }\n      }\n\n      if (!success) {\n        \u002F\u002F Escalate to Human-In-The-Loop \u002F DLQ Alerting\n        console.error(`CRITICAL: Compensation failed permanently for Saga ${this.context.sagaId}`);\n        await this.routeToHumanInterventionDLQ(this.context);\n      }\n    }\n\n    this.context.currentState = 'FAILED';\n    await this.updateSagaState('FAILED');\n  }\n\n  private async updateSagaState(state: SagaState): Promise\u003Cvoid> {\u002F* DB state update *\u002F}\n  private async callPaymentService(path: string, payload: any): Promise\u003Cvoid> {\u002F* HTTP\u002FgRPC *\u002F}\n  private async callInventoryService(path: string, payload: any): Promise\u003Cvoid> {\u002F* HTTP\u002FgRPC *\u002F}\n  private async callOrderService(path: string, payload: any): Promise\u003Cvoid> {\u002F* HTTP\u002FgRPC *\u002F}\n  private async routeToHumanInterventionDLQ(context: SagaContext): Promise\u003Cvoid> {\u002F* DLQ Alert *\u002F}\n}\n```\n","# Event-Driven Architecture: Saga Patterns & Eventual Consistency Guide\n\n## 1. Architectural Foundations: BASE over ACID\n\nIn microservices architectures, each service maintains its own private database to ensure loose coupling and independent scalability. This renders distributed ACID transactions impossible without two-phase commit (2PC). However, 2PC introduces high latency, synchronous blocking, single points of failure, and deadlocks across service boundaries.\n\nThe **Saga Pattern** manages distributed transactions as a sequence of local transactions. Each local transaction updates a single service's database and emits an event or message to trigger the next step. If a step fails, the Saga executes **compensating transactions** in reverse order to undo changes and restore data consistency.\n\n### 1.1 Transaction Classification\n\n```\n[ Local Tx 1: Compensable ] ──► [ Local Tx 2: Pivot ] ──► [ Local Tx 3: Retryable ]\n        │                             │                         │\n   (Rollbackable)              (Point of No Return)       (Guaranteed Success)\n```\n\n- **Compensable Transactions**: Transactions that can be undone by running an explicit compensating transaction.\n- **Pivot Transaction**: The critical decision point of the Saga. Once the pivot transaction succeeds, the Saga MUST go to completion. It cannot be compensated.\n- **Retryable Transactions**: Transactions that follow the pivot point and are guaranteed to eventually succeed through retries.\n\n---\n\n## 2. Saga Execution Models: Choreography vs. Orchestration\n\n```\nCHOREOGRAPHY:\n[ Order Service ] ── OrderCreated ──► [ Payment Service ] ── PaymentProcessed ──► [ Inventory Service ]\n\nORCHESTRATION:\n                        ┌──► [ Payment Service ]\n                        │\n[ Saga Orchestrator ] ──┼──► [ Inventory Service ]\n                        │\n                        └──► [ Shipping Service ]\n```\n\n### 2.1 Comparative Analysis\n\n| Dimension | Choreography Saga | Orchestration Saga |\n| :--- | :--- | :--- |\n| **Control Model** | Decentralized; services react to domain events. | Centralized; dedicated orchestrator directs participants. |\n| **Coupling** | Loosely coupled; services know events, not handlers. | Moderate coupling; orchestrator knows participant APIs. |\n| **State Visibility** | Distributed across service logs; hard to query global status. | Centralized state store; easy to track saga status. |\n| **Complexity** | Simple for small flows (2-3 steps); cyclic dependencies in large flows. | High initial setup; manages complex branching & parallel paths easily. |\n| **Failure Handling** | Complex cascading compensation logic across events. | Explicit compensation routines directed by orchestrator. |\n\n### 2.2 Decision Matrix\n- **Choose Choreography** when workflows are simple (2-3 microservices), linear, and teams want maximum domain event decoupling.\n- **Choose Orchestration** when workflows involve 4+ services, complex conditional branching, parallel execution steps, or require strict operational auditing.\n\n---\n\n## 3. Dual-Write Prevention: Transactional Outbox & CDC\n\nA major vulnerability in event-driven systems is the **Dual-Write Problem**: attempting to update a database and publish a message to a broker in a single code block without atomic guarantees.\n\n```\nWRONG (Dual Write Risk):\ndb.orders.insert(order);       \u002F\u002F Success\nbroker.publish(\"OrderCreated\"); \u002F\u002F Network Failure! -> DB & Broker state out of sync!\n```\n\n### 3.1 Transactional Outbox Pattern Architecture\n\n```\n[ Business Logic ]\n       │\n       ▼ (Single ACID Local DB Transaction)\n┌──────────────────────────────────────────────┐\n│  Service Database                            │\n│  ├── Orders Table:   [ Insert Order ]        │\n│  └── Outbox Table:   [ Insert Outbox Event ] │\n└──────────────────────────────────────────────┘\n       │\n       ▼ (Async Log Tailing \u002F CDC)\n[ Debezium \u002F Outbox Publisher ] ──► [ Message Broker (Kafka \u002F RabbitMQ) ]\n```\n\n1. Business record update and message metadata insertion are committed into the service's local database within a **single local ACID transaction**.\n2. A separate process (e.g., Debezium CDC or a dedicated polling worker) reads the `outbox` table and safely forwards events to the message broker with **at-least-once** delivery guarantees.\n\n---\n\n## 4. Idempotency & De-duplication Engineering\n\nBecause event delivery is **at-least-once**, consumers WILL receive duplicate events. Consumers must be designed to be completely **idempotent**.\n\n### 4.1 Idempotent Consumer Design Patterns\n\n1. **Natural Unique Key Constraints**: Insert incoming event processing results using database unique constraints (e.g., `PRIMARY KEY (payment_id)`).\n2. **Idempotency Key \u002F Deduplication Table**:\n   ```sql\n   CREATE TABLE processed_events (\n       event_id VARCHAR(128) PRIMARY KEY,\n       consumer_group VARCHAR(64) NOT NULL,\n       processed_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP\n   );\n   ```\n   Before processing logic begins, attempt atomic insertion into `processed_events`. If duplicate key violation occurs, skip processing and immediately ACK message.\n3. **State Machine Guardrails**: Only allow state transitions that are valid from the current state (e.g., `UPDATE orders SET status = 'PAID' WHERE id = :id AND status = 'PENDING'`).\n\n---\n\n## 5. Compensating Transactions & Failure Recovery\n\nCompensating transactions are inverse operations that semantically undo completed local transactions.\n\n### 5.1 Rules for Compensating Actions\n- **Must Be Idempotent**: A compensating step may be retried multiple times during recovery.\n- **Must Never Fail Permanently**: If a compensating action encounters transient errors, it must retry until successful. If business invariants prevent auto-compensation, route to a **Human-in-the-Loop (HITL)** DLQ queue.\n- **Semantic Rollback**: Compensation does not necessarily mean \"deleting\" rows. It often means applying a counter-action (e.g., issuing a credit refund rather than un-writing a credit charge).\n\n---\n\n## 6. Critical Anti-Patterns & Production Traps\n\n1. **Dual Writes without Outbox Pattern**: Updating local DB state and calling `broker.publish()` directly without outbox tables or transactional CDC.\n2. **Missing Compensating Triggers**: Implementing forward execution steps without defining corresponding inverse compensation handlers.\n3. **Cyclic Choreography Dependencies**: Service A triggers Service B, which triggers Service C, which triggers Service A again, creating un-traceable infinite loops.\n4. **Non-Idempotent Compensations**: Compensating transactions that double-credit or double-refund when retried.\n5. **Synchronous REST Calls inside Sagas**: Mixing blocking HTTP calls within asynchronous event-driven sagas, leading to thread pool exhaustion and cascading failures.\n\n---\n\n## 7. Production Code Reference\n\n### 7.1 Transactional Outbox Pattern in Python (SQLAlchemy)\n\n```python\nimport uuid\nimport json\nfrom datetime import datetime, timezone\nfrom sqlalchemy import create_engine, Column, String, Float, DateTime, Text\nfrom sqlalchemy.orm import declarative_base, sessionmaker\n\nBase = declarative_base()\n\nclass Order(Base):\n    __tablename__ = 'orders'\n    id = Column(String(64), primary_key=True)\n    customer_id = Column(String(64), nullable=False)\n    total_amount = Column(Float, nullable=False)\n    status = Column(String(32), nullable=False)\n\nclass OutboxEvent(Base):\n    __tablename__ = 'outbox'\n    id = Column(String(64), primary_key=True)\n    aggregate_type = Column(String(64), nullable=False)\n    aggregate_id = Column(String(64), nullable=False)\n    event_type = Column(String(64), nullable=False)\n    payload = Column(Text, nullable=False)\n    created_at = Column(DateTime(timezone=True), nullable=False)\n\nengine = create_engine(\"postgresql:\u002F\u002Fapp_user:secret@db.prod.internal:5432\u002Forders_db\")\nSessionLocal = sessionmaker(bind=engine)\n\ndef create_order_with_outbox(customer_id: str, amount: float) -> str:\n    session = SessionLocal()\n    order_id = f\"ord-{uuid.uuid4()}\"\n    event_id = f\"evt-{uuid.uuid4()}\"\n    \n    order = Order(\n        id=order_id,\n        customer_id=customer_id,\n        total_amount=amount,\n        status=\"PENDING_PAYMENT\"\n    )\n    \n    event_payload = json.dumps({\n        \"event_id\": event_id,\n        \"order_id\": order_id,\n        \"customer_id\": customer_id,\n        \"amount\": amount,\n        \"timestamp\": datetime.now(timezone.utc).isoformat()\n    })\n    \n    outbox_entry = OutboxEvent(\n        id=event_id,\n        aggregate_type=\"Order\",\n        aggregate_id=order_id,\n        event_type=\"OrderCreated\",\n        payload=event_payload,\n        created_at=datetime.now(timezone.utc)\n    )\n\n    try:\n        # Atomic single local ACID transaction\n        session.add(order)\n        session.add(outbox_entry)\n        session.commit()\n        return order_id\n    except Exception as e:\n        session.rollback()\n        raise RuntimeError(f\"Failed to create order atomically: {str(e)}\")\n    finally:\n        session.close()\n```\n\n### 7.2 Saga Orchestrator State Machine in TypeScript \u002F Node.js\n\n```typescript\ntype SagaState = 'STARTED' | 'PAYMENT_RESERVED' | 'INVENTORY_RESERVED' | 'COMPLETED' | 'FAILED' | 'COMPENSATING';\n\ninterface SagaContext {\n  sagaId: string;\n  orderId: string;\n  customerId: string;\n  amount: number;\n  items: Array\u003C{ sku: string; qty: number }>;\n  currentState: SagaState;\n  failureReason?: string;\n}\n\nexport class OrderSagaOrchestrator {\n  private context: SagaContext;\n\n  constructor(context: SagaContext) {\n    this.context = context;\n  }\n\n  async executeSaga(): Promise\u003Cvoid> {\n    try {\n      \u002F\u002F Step 1: Reserve Payment (Compensable)\n      await this.executeStep('PAYMENT_RESERVED', \n        () => this.callPaymentService('\u002Fpayments\u002Freserve', { amount: this.context.amount }),\n        () => this.callPaymentService('\u002Fpayments\u002Frefund', { amount: this.context.amount })\n      );\n\n      \u002F\u002F Step 2: Reserve Inventory (Compensable)\n      await this.executeStep('INVENTORY_RESERVED', \n        () => this.callInventoryService('\u002Finventory\u002Freserve', { items: this.context.items }),\n        () => this.callInventoryService('\u002Finventory\u002Frelease', { items: this.context.items })\n      );\n\n      \u002F\u002F Step 3: Pivot Point - Approve Order (Retryable)\n      this.context.currentState = 'COMPLETED';\n      await this.updateSagaState('COMPLETED');\n      await this.callOrderService(`\u002Forders\u002F${this.context.orderId}\u002Fapprove`, {});\n\n    } catch (error: any) {\n      console.error(`Saga ${this.context.sagaId} failed at state ${this.context.currentState}: ${error.message}`);\n      this.context.failureReason = error.message;\n      await this.compensateSaga();\n    }\n  }\n\n  private async executeStep(\n    targetState: SagaState, \n    action: () => Promise\u003Cvoid>, \n    compensation: () => Promise\u003Cvoid>\n  ): Promise\u003Cvoid> {\n    try {\n      await action();\n      this.context.currentState = targetState;\n      await this.updateSagaState(targetState);\n    } catch (err) {\n      \u002F\u002F Register compensation step for reverse execution\n      this.compensations.push(compensation);\n      throw err;\n    }\n  }\n\n  private compensations: Array\u003C() => Promise\u003Cvoid>> = [];\n\n  private async compensateSaga(): Promise\u003Cvoid> {\n    this.context.currentState = 'COMPENSATING';\n    await this.updateSagaState('COMPENSATING');\n\n    \u002F\u002F Run compensations in reverse order\n    for (const compensation of this.compensations.reverse()) {\n      let retryCount = 0;\n      let success = false;\n      \n      while (!success && retryCount \u003C 5) {\n        try {\n          await compensation();\n          success = true;\n        } catch (compErr) {\n          retryCount++;\n          console.error(`Compensation retry ${retryCount} failed:`, compErr);\n          await new Promise(res => setTimeout(res, 1000 * Math.pow(2, retryCount)));\n        }\n      }\n\n      if (!success) {\n        \u002F\u002F Escalate to Human-In-The-Loop \u002F DLQ Alerting\n        console.error(`CRITICAL: Compensation failed permanently for Saga ${this.context.sagaId}`);\n        await this.routeToHumanInterventionDLQ(this.context);\n      }\n    }\n\n    this.context.currentState = 'FAILED';\n    await this.updateSagaState('FAILED');\n  }\n\n  private async updateSagaState(state: SagaState): Promise\u003Cvoid> {\u002F* DB state update *\u002F}\n  private async callPaymentService(path: string, payload: any): Promise\u003Cvoid> {\u002F* HTTP\u002FgRPC *\u002F}\n  private async callInventoryService(path: string, payload: any): Promise\u003Cvoid> {\u002F* HTTP\u002FgRPC *\u002F}\n  private async callOrderService(path: string, payload: any): Promise\u003Cvoid> {\u002F* HTTP\u002FgRPC *\u002F}\n  private async routeToHumanInterventionDLQ(context: SagaContext): Promise\u003Cvoid> {\u002F* DLQ Alert *\u002F}\n}\n```\n",{"name":5,"description":7},"main","e905af21e5f1e1c3ca605e9656c3a7930360a84e","Programming\u002FBackend\u002FEvent_Driven_and_Messaging\u002Fevent-driven-architecture-saga-patterns",1,"https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills","https:\u002F\u002Fhamzabellouch.github.io\u002F","https:\u002F\u002Fgithub.com\u002Fhamzabellouch","hamzabellouch.github.io","CEO & Founder of @tknoglobal | Researcher in Technology & Applied Sciences.","2026-10-17 03:20:19",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add hamzabellouch\u002Fagent-skills --skill event-driven-architecture-saga-patterns",{"tool":40,"command":41},"bunx","bunx skills add hamzabellouch\u002Fagent-skills --skill event-driven-architecture-saga-patterns",{"tool":43,"command":44},"pnpm","pnpm dlx skills add hamzabellouch\u002Fagent-skills --skill event-driven-architecture-saga-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FProgramming\u002FBackend\u002FEvent_Driven_and_Messaging\u002Fevent-driven-architecture-saga-patterns\u002FSKILL.md",true,[],[49,56,63,70,77,84],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":19},"01M79FHH2H815A9TAP6WNKH4Q8","security-audit","Comprehensive security guidance, source code audit, vulnerability assessment, and penetration test review for codebases, APIs, microservices, CLI tools, libraries, and LLM-backed applications. Triggers on requests to audit a codebase, conduct security reviews, find vulnerabilities or flaws, pen-test source code, or when the user asks in Arabic (فحص أمني، تدقيق الكود أمنياً، مراجعة الثغرات، فحص أمان المشروع). Supports Guidance mode (focused review) and Full Audit mode (deterministic 6-phase harness).","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FSecurity\u002FSecurity_Audit_and_Code_Review\u002Fsecurity-audit\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":59,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":19},"01M79FHBGXVBY6VQ1X7ETAZMF1","malware-analysis-reversing","Production malware analysis workflows, reverse engineering methodologies, isolated sandbox triage, static\u002Fdynamic binary analysis, memory forensics, and YARA detection rule authoring.","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FSecurity\u002FOffensive_Security_and_Pentesting\u002Fmalware-analysis-reversing\u002FSKILL.md",[],[],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":19},"01M79FH6EACDR801TZCE4R8SAC","application-security-pentesting","Production Application Security (AppSec) standards, OWASP Top 10 vulnerability remediation, SAST\u002FDAST pipeline integration, secure code review, threat modeling, and defensive security posture.","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FSecurity\u002FOffensive_Security_and_Pentesting\u002Fapplication-security-pentesting\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M79FH0VKVT44FK923K520ZQA","oauth2-oidc-security-flows","Implement enterprise OAuth 2.1 and OpenID Connect (OIDC) authorization code flow with Proof Key for Code Exchange (PKCE), state and nonce verification, refresh token rotation, token revocation, and centralized IdP federation (Keycloak, Auth0, Okta). Trigger when building secure authentication, single sign-on (SSO), or third-party delegated authorization.","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FSecurity\u002FIdentity_and_Access_Management_IAM\u002Foauth2-oidc-security-flows\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M79FGVVB3R4T88XXD8FRSV5B","jwt-session-management-hardening","Harden JWT-based authentication and session lifecycles using asymmetric signing (RS256\u002FEdDSA), JWKS rotation, strict claims validation, Redis-backed sliding window sessions, revocation lists, and secure HttpOnly cookie storage. Trigger when implementing token validation, session revocation, or hardening API authentication.","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FSecurity\u002FIdentity_and_Access_Management_IAM\u002Fjwt-session-management-hardening\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M79FGNCPZ85CVEY0B3NE4H3B","soc2-compliance-automation","Best practices for implementing SOC 2 Type II compliance controls, continuous evidence collection, infrastructure policy-as-code, and automated security monitoring. Use when automating Trust Services Criteria (Security, Availability, Confidentiality, Processing Integrity, Privacy), audit logging, IAM least privilege, or CI\u002FCD security gates.","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FSecurity\u002FGovernance_Compliance_and_Legal_Tech\u002Fsoc2-compliance-automation\u002FSKILL.md",[],[]]