Skip to content
acc-create-saga-pattern logo

Saga Pattern Generator

acc-create-saga-pattern

Generates Saga pattern components for PHP 8.5. Creates Saga interfaces, steps, orchestrator, state management, and compensation logic with unit tests.

SKILL.md

Full skill instructions

Saga Pattern Generator

Creates Saga pattern infrastructure for distributed transaction coordination.

When to Use

  • Distributed transactions across multiple services
  • Long-running business processes
  • Operations requiring compensation on failure
  • Multi-step workflows with rollback capability

Component Characteristics

SagaState Enum

  • Domain layer enum
  • Defines saga lifecycle states: Pending, Running, Compensating, Completed, Failed, CompensationFailed
  • Includes state transition validation
  • Terminal states detection

SagaStep Interface

  • Domain layer interface
  • Execute and compensate methods
  • Idempotency declaration
  • Timeout configuration

SagaContext

  • Carries saga execution data
  • Serializable for persistence
  • Supports data accumulation across steps

SagaOrchestrator

  • Application layer coordinator
  • Manages step execution
  • Handles compensation flow (reverse order)
  • Persists state after each step

SagaPersistence

  • Stores saga state for recovery
  • Supports finding incomplete sagas
  • Dead letter handling

Generation Process

Step 1: Analyze Request

Determine:

  • Context name (Order, Payment, Shipping)
  • Required saga steps
  • Compensation logic for each step

Step 2: Generate Core Components

Create in this order:

  1. Domain Layer (src/​Domain/​Shared/​Saga/)

    • SagaState.php — State enum with transitions
    • StepResult.php — Step result value object
    • SagaStepInterface.php — Step contract
    • SagaContext.php — Execution context
    • SagaResult.php — Saga result
    • Exception classes
  2. Application Layer (src/​Application/​Shared/​Saga/)

    • SagaPersistenceInterface.php — Persistence port
    • SagaRecord.php — Persisted record
    • AbstractSagaStep.php — Base step class
    • SagaOrchestrator.php — Orchestrator
  3. Infrastructure Layer

    • DoctrineSagaPersistence.php — Doctrine implementation
    • Database migration
  4. Tests

    • SagaStateTest.php
    • SagaOrchestratorTest.php

Step 3: Generate Context-Specific Steps

For each saga step (e.g., Order saga):

src/​Application/​{Context}/​Saga/​Step/
├── ReserveInventoryStep.php
├── ChargePaymentStep.php
└── CreateShipmentStep.php

src/​Application/​{Context}/​Saga/
└── {Context}SagaFactory.php

File Placement

LayerPath
Domain Typessrc/​Domain/​Shared/​Saga/
Application Sagasrc/​Application/​Shared/​Saga/
Context Stepssrc/​Application/​{Context}/​Saga/​Step/
Saga Factorysrc/​Application/​{Context}/​Saga/
Infrastructuresrc/​Infrastructure/​Persistence/​Doctrine/​Repository/
Unit Teststests/​Unit/​{Layer}/​{Path}/

Key Principles

Compensation Rules

  1. Compensate in reverse order of execution
  2. Compensations must be idempotent
  3. Handle "already compensated" gracefully
  4. Log all compensation attempts

Idempotency

  1. Use idempotency keys for each step
  2. Check for existing results before executing
  3. Return existing result if found

State Transitions

Pending → Running → Completed
              ↓
         Compensating → Failed
              ↓
         CompensationFailed

Naming Conventions

ComponentPatternExample
State EnumSagaStateSagaState
Step InterfaceSagaStepInterfaceSagaStepInterface
Abstract StepAbstractSagaStepAbstractSagaStep
Concrete Step{Action}StepReserveInventoryStep
OrchestratorSagaOrchestratorSagaOrchestrator
Factory{Name}SagaFactoryOrderSagaFactory
Test{ClassName}TestSagaOrchestratorTest

Quick Template Reference

SagaStepInterface

interface SagaStepInterface
{
    public function name(): string;
    public function execute(SagaContext $context): StepResult;
    public function compensate(SagaContext $context): StepResult;
    public function isIdempotent(): bool;
    public function timeout(): int;
}

StepResult

final readonly class StepResult
{
    public static function success(array $data = []): self;
    public static function failure(string $error): self;
    public function isSuccess(): bool;
    public function isFailure(): bool;
}

Concrete Step Pattern

final readonly class {Action}Step extends AbstractSagaStep
{
    public function name(): string
    {
        return '{action_name}';
    }

    public function execute(SagaContext $context): StepResult
    {
        $idempotencyKey = $this->idempotencyKey($context);

        // Check for existing result (idempotency)
        // Execute action
        // Return StepResult::success([...data...]) or failure
    }

    public function compensate(SagaContext $context): StepResult
    {
        // Get data from context
        // Undo action
        // Handle "already undone" gracefully
        return StepResult::success();
    }
}

Usage Example

// Create saga
$saga = $orderSagaFactory->create($command);

// Execute
$result = $saga->execute();

if ($result->isCompleted()) {
    // Success
} elseif ($result->isFailed()) {
    // Failed but compensated
    $error = $result->error;
} elseif ($result->isCompensationFailed()) {
    // Needs manual intervention
    $originalError = $result->error;
    $compensationError = $result->compensationError;
}

DI Configuration

# Symfony services.yaml
Domain\Shared\Saga\SagaStepInterface:
    tags: ['saga.step']

Application\Shared\Saga\SagaPersistenceInterface:
    alias: Infrastructure\Persistence\Doctrine\Repository\DoctrineSagaPersistence

Application\Order\Saga\OrderSagaFactory:
    arguments:
        $reserveStep: '@Application\Order\Saga\Step\ReserveInventoryStep'
        $chargeStep: '@Application\Order\Saga\Step\ChargePaymentStep'
        $shipStep: '@Application\Order\Saga\Step\CreateShipmentStep'

Database Schema

CREATE TABLE sagas (
    id VARCHAR(255) PRIMARY KEY,
    type VARCHAR(255) NOT NULL,
    state VARCHAR(50) NOT NULL,
    completed_steps JSONB NOT NULL DEFAULT '[]',
    context JSONB NOT NULL,
    error TEXT,
    created_at TIMESTAMP(6) NOT NULL,
    updated_at TIMESTAMP(6) NOT NULL,
    completed_at TIMESTAMP(6)
);

CREATE INDEX idx_sagas_state ON sagas (state);
CREATE INDEX idx_sagas_type_state ON sagas (type, state);

References

For complete PHP templates and test examples, see:

  • references/​templates.md — All component templates
  • references/​examples.md — Order saga example and unit tests

More DevOps & CI/CD skills

Project scaffolding, deployment configuration, and CI/CD setup for Google ADK agents.

6K 472.6K
View

Set up tracing, logging, and monitoring for deployed ADK agents across Cloud Trace, BigQuery, and third-party platforms.

6K 472.6K
View

Enterprise Azure infrastructure architect generating Bicep or Terraform from workload descriptions.

1.5K 454.3K
View
azure-kubernetes logo
DevOps & CI/CD

azure-kubernetes

Plan and configure production-ready Azure Kubernetes Service clusters with Day-0 and Day-1 best practices.

1.5K 447.1K
View

Raw mechanical interfaces fusing Swiss typographic print with military terminal aesthetics. Rigid grids, extreme type scale contrast, utilitarian color, analog degradation effects. For data-heavy dashboards, portfolios, or editorial sites that need to feel like declassified blueprints.

92.7K 354.9K
View
just-scrape logo
DevOps & CI/CD

just-scrape

Web search, scraping, extraction, crawling, and monitoring via ScrapeGraph AI CLI.

69 245K
View

Skill for working with Firebase Hosting (Classic). Use this when you want to deploy static web apps, Single Page Apps (SPAs), or simple microservices. Do NOT use for Firebase App Hosting.

462 159.7K
View

Deploy and manage web apps with Firebase App Hosting. Use this skill when deploying Next.js/Angular apps with backends.

462 159.1K
View
deploy-to-vercel logo
DevOps & CI/CD

deploy-to-vercel

Deploy applications and websites to Vercel. Use when the user requests deployment actions like "deploy my app", "deploy and give me the link", "push this live", or "create a preview deployment".

31.9K 146.6K
View
programmatic-seo logo
DevOps & CI/CD

programmatic-seo

Build SEO-optimized pages at scale using templates, data, and proven playbook patterns.

53.3K 140.1K
View

Design and build isolated, reusable Convex backend components with clear boundaries and app-facing wrappers.

63 123.5K
View

Deploy and manage projects on Vercel using token-based authentication. Use when working with Vercel CLI using access tokens rather than interactive login — e.g. "deploy to vercel", "set up vercel", "add environment variables to vercel".

31.9K 116.1K
View

Coding & apps AI tools

Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View
I
Coding & apps

Imagica

Build a no-code AI app in minutes.

Freemium
View
E
Coding & apps

Emergent.sh

An IDE for code migration from legacy to modern frameworks through coding agents.

Freemium
View
Wonder Dynamics logo
Coding & apps

Wonder Dynamics

Automate CGI animation in live-action scenes

Paid
View
M
Coding & apps

Mixo

Launch a website in seconds with AI.

Paid
View
AI Code Convert logo
Coding & apps

AI Code Convert

Streamline Your Coding Experience with AI Code Helper

Free
View