[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill-22c6b7a9-2234-483e-a475-b094a364403e":3,"$fWXhcEWRMItNUKvjm2CAdMSRSARA5E6qdIe97mOwoRjI":43},{"id":4,"title":5,"description":6,"categoryId":7,"moduleId":8,"tags":9,"prompt":10,"icon":11,"source":12,"sourceUrl":13,"authorId":14,"authorName":15,"isPublic":16,"stars":17,"runs":18,"createdAt":19,"updatedAt":19,"module":20,"category":27,"packages":34},"22c6b7a9-2234-483e-a475-b094a364403e","workflow-orchestration-patterns","掌握Temporal的流程编排架构，涵盖基本设计决策、弹性模式以及构建可靠分布式系统的最佳实践。","cat_prod_automation","mod_productivity","sickn33,productivity","---\nname: workflow-orchestration-patterns\ndescription: \"Master workflow orchestration architecture with Temporal, covering fundamental design decisions, resilience patterns, and best practices for building reliable distributed systems.\"\nrisk: unknown\nsource: community\ndate_added: \"2026-02-27\"\n---\n\n# Workflow Orchestration Patterns\n\nMaster workflow orchestration architecture with Temporal, covering fundamental design decisions, resilience patterns, and best practices for building reliable distributed systems.\n\n## Use this skill when\n\n- Working on workflow orchestration patterns tasks or workflows\n- Needing guidance, best practices, or checklists for workflow orchestration patterns\n\n## Do not use this skill when\n\n- The task is unrelated to workflow orchestration patterns\n- You need a different domain or tool outside this scope\n\n## Instructions\n\n- Clarify goals, constraints, and required inputs.\n- Apply relevant best practices and validate outcomes.\n- Provide actionable steps and verification.\n- If detailed examples are required, open `resources\u002Fimplementation-playbook.md`.\n\n## When to Use Workflow Orchestration\n\n### Ideal Use Cases (Source: docs.temporal.io)\n\n- **Multi-step processes** spanning machines\u002Fservices\u002Fdatabases\n- **Distributed transactions** requiring all-or-nothing semantics\n- **Long-running workflows** (hours to years) with automatic state persistence\n- **Failure recovery** that must resume from last successful step\n- **Business processes**: bookings, orders, campaigns, approvals\n- **Entity lifecycle management**: inventory tracking, account management, cart workflows\n- **Infrastructure automation**: CI\u002FCD pipelines, provisioning, deployments\n- **Human-in-the-loop** systems requiring timeouts and escalations\n\n### When NOT to Use\n\n- Simple CRUD operations (use direct API calls)\n- Pure data processing pipelines (use Airflow, batch processing)\n- Stateless request\u002Fresponse (use standard APIs)\n- Real-time streaming (use Kafka, event processors)\n\n## Critical Design Decision: Workflows vs Activities\n\n**The Fundamental Rule** (Source: temporal.io\u002Fblog\u002Fworkflow-engine-principles):\n\n- **Workflows** = Orchestration logic and decision-making\n- **Activities** = External interactions (APIs, databases, network calls)\n\n### Workflows (Orchestration)\n\n**Characteristics:**\n\n- Contain business logic and coordination\n- **MUST be deterministic** (same inputs → same outputs)\n- **Cannot** perform direct external calls\n- State automatically preserved across failures\n- Can run for years despite infrastructure failures\n\n**Example workflow tasks:**\n\n- Decide which steps to execute\n- Handle compensation logic\n- Manage timeouts and retries\n- Coordinate child workflows\n\n### Activities (External Interactions)\n\n**Characteristics:**\n\n- Handle all external system interactions\n- Can be non-deterministic (API calls, DB writes)\n- Include built-in timeouts and retry logic\n- **Must be idempotent** (calling N times = calling once)\n- Short-lived (seconds to minutes typically)\n\n**Example activity tasks:**\n\n- Call payment gateway API\n- Write to database\n- Send emails or notifications\n- Query external services\n\n### Design Decision Framework\n\n```\nDoes it touch external systems? → Activity\nIs it orchestration\u002Fdecision logic? → Workflow\n```\n\n## Core Workflow Patterns\n\n### 1. Saga Pattern with Compensation\n\n**Purpose**: Implement distributed transactions with rollback capability\n\n**Pattern** (Source: temporal.io\u002Fblog\u002Fcompensating-actions-part-of-a-complete-breakfast-with-sagas):\n\n```\nFor each step:\n  1. Register compensation BEFORE executing\n  2. Execute the step (via activity)\n  3. On failure, run all compensations in reverse order (LIFO)\n```\n\n**Example: Payment Workflow**\n\n1. Reserve inventory (compensation: release inventory)\n2. Charge payment (compensation: refund payment)\n3. Fulfill order (compensation: cancel fulfillment)\n\n**Critical Requirements:**\n\n- Compensations must be idempotent\n- Register compensation BEFORE executing step\n- Run compensations in reverse order\n- Handle partial failures gracefully\n\n### 2. Entity Workflows (Actor Model)\n\n**Purpose**: Long-lived workflow representing single entity instance\n\n**Pattern** (Source: docs.temporal.io\u002Fevaluate\u002Fuse-cases-design-patterns):\n\n- One workflow execution = one entity (cart, account, inventory item)\n- Workflow persists for entity lifetime\n- Receives signals for state changes\n- Supports queries for current state\n\n**Example Use Cases:**\n\n- Shopping cart (add items, checkout, expiration)\n- Bank account (deposits, withdrawals, balance checks)\n- Product inventory (stock updates, reservations)\n\n**Benefits:**\n\n- Encapsulates entity behavior\n- Guarantees consistency per entity\n- Natural event sourcing\n\n### 3. Fan-Out\u002FFan-In (Parallel Execution)\n\n**Purpose**: Execute multiple tasks in parallel, aggregate results\n\n**Pattern:**\n\n- Spawn child workflows or parallel activities\n- Wait for all to complete\n- Aggregate results\n- Handle partial failures\n\n**Scaling Rule** (Source: temporal.io\u002Fblog\u002Fworkflow-engine-principles):\n\n- Don't scale individual workflows\n- For 1M tasks: spawn 1K child workflows × 1K tasks each\n- Keep each workflow bounded\n\n### 4. Async Callback Pattern\n\n**Purpose**: Wait for external event or human approval\n\n**Pattern:**\n\n- Workflow sends request and waits for signal\n- External system processes asynchronously\n- Sends signal to resume workflow\n- Workflow continues with response\n\n**Use Cases:**\n\n- Human approval workflows\n- Webhook callbacks\n- Long-running external processes\n\n## State Management and Determinism\n\n### Automatic State Preservation\n\n**How Temporal Works** (Source: docs.temporal.io\u002Fworkflows):\n\n- Complete program state preserved automatically\n- Event History records every command and event\n- Seamless recovery from crashes\n- Applications restore pre-failure state\n\n### Determinism Constraints\n\n**Workflows Execute as State Machines**:\n\n- Replay behavior must be consistent\n- Same inputs → identical outputs every time\n\n**Prohibited in Workflows** (Source: docs.temporal.io\u002Fworkflows):\n\n- ❌ Threading, locks, synchronization primitives\n- ❌ Random number generation (`random()`)\n- ❌ Global state or static variables\n- ❌ System time (`datetime.now()`)\n- ❌ Direct file I\u002FO or network calls\n- ❌ Non-deterministic libraries\n\n**Allowed in Workflows**:\n\n- ✅ `workflow.now()` (deterministic time)\n- ✅ `workflow.random()` (deterministic random)\n- ✅ Pure functions and calculations\n- ✅ Calling activities (non-deterministic operations)\n\n### Versioning Strategies\n\n**Challenge**: Changing workflow code while old executions still running\n\n**Solutions**:\n\n1. **Versioning API**: Use `workflow.get_version()` for safe changes\n2. **New Workflow Type**: Create new workflow, route new executions to it\n3. **Backward Compatibility**: Ensure old events replay correctly\n\n## Resilience and Error Handling\n\n### Retry Policies\n\n**Default Behavior**: Temporal retries activities forever\n\n**Configure Retry**:\n\n- Initial retry interval\n- Backoff coefficient (exponential backoff)\n- Maximum interval (cap retry delay)\n- Maximum attempts (eventually fail)\n\n**Non-Retryable Errors**:\n\n- Invalid input (validation failures)\n- Business rule violations\n- Permanent failures (resource not found)\n\n### Idempotency Requirements\n\n**Why Critical** (Source: docs.temporal.io\u002Factivities):\n\n- Activities may execute multiple times\n- Network failures trigger retries\n- Duplicate execution must be safe\n\n**Implementation Strategies**:\n\n- Idempotency keys (deduplication)\n- Check-then-act with unique constraints\n- Upsert operations instead of insert\n- Track processed request IDs\n\n### Activity Heartbeats\n\n**Purpose**: Detect stalled long-running activities\n\n**Pattern**:\n\n- Activity sends periodic heartbeat\n- Includes progress information\n- Timeout if no heartbeat received\n- Enables progress-based retry\n\n## Best Practices\n\n### Workflow Design\n\n1. **Keep workflows focused** - Single responsibility per workflow\n2. **Small workflows** - Use child workflows for scalability\n3. **Clear boundaries** - Workflow orchestrates, activities execute\n4. **Test locally** - Use time-skipping test environment\n\n### Activity Design\n\n1. **Idempotent operations** - Safe to retry\n2. **Short-lived** - Seconds to minutes, not hours\n3. **Timeout configuration** - Always set timeouts\n4. **Heartbeat for long tasks** - Report progress\n5. **Error handling** - Distinguish retryable vs non-retryable\n\n### Common Pitfalls\n\n**Workflow Violations**:\n\n- Using `datetime.now()` instead of `workflow.now()`\n- Threading or async operations in workflow code\n- Calling external APIs directly from workflow\n- Non-deterministic logic in workflows\n\n**Activity Mistakes**:\n\n- Non-idempotent operations (can't handle retries)\n- Missing timeouts (activities run forever)\n- No error classification (retry validation errors)\n- Ignoring payload limits (2MB per argument)\n\n### Operational Considerations\n\n**Monitoring**:\n\n- Workflow execution duration\n- Activity failure rates\n- Retry attempts and backoff\n- Pending workflow counts\n\n**Scalability**:\n\n- Horizontal scaling with workers\n- Task queue partitioning\n- Child workflow decomposition\n- Activity batching when appropriate\n\n## Additional Resources\n\n**Official Documentation**:\n\n- Temporal Core Concepts: docs.temporal.io\u002Fworkflows\n- Workflow Patterns: docs.temporal.io\u002Fevaluate\u002Fuse-cases-design-patterns\n- Best Practices: docs.temporal.io\u002Fdevelop\u002Fbest-practices\n- Saga Pattern: temporal.io\u002Fblog\u002Fsaga-pattern-made-easy\n\n**Key Principles**:\n\n1. Workflows = orchestration, Activities = external calls\n2. Determinism is non-negotiable for workflows\n3. Idempotency is critical for activities\n4. State preservation is automatic\n5. Design for failure and recovery\n\n## Limitations\n- Use this skill only when the task clearly matches the scope described above.\n- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.\n- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.\n","","imported","https:\u002F\u002Fgithub.com\u002Fsickn33\u002Fantigravity-awesome-skills","user_system_seed","SkillOPIC",true,52,883,"2026-05-16 13:47:36",{"id":8,"name":21,"slug":22,"icon":23,"description":24,"sort":25,"createdAt":26},"效率工具","productivity","mdi-lightning-bolt-outline","文档处理、数据分析、自动化工作流",4,"2026-05-16 12:53:40",{"id":7,"name":28,"slug":29,"icon":30,"description":31,"moduleId":8,"sort":32,"skillCount":33,"createdAt":26},"自动化","automation","mdi-robot-outline","工作流自动化、批处理",3,101,[35],{"id":36,"skillId":4,"version":37,"fileName":38,"fileSize":39,"filePath":40,"fileHash":41,"manifest":42,"createdAt":19},"a315c1d4-466e-43a8-9bcd-ec64c4abbc1f","1.0.0","workflow-orchestration-patterns.zip",4143,"uploads\u002Fskills\u002F22c6b7a9-2234-483e-a475-b094a364403e\u002Fworkflow-orchestration-patterns.zip","5779297dde98459fa0822948a83d2088e28cbec4b758673d3959d5b84ad926c8","[{\"path\":\"SKILL.md\",\"isDirectory\":false,\"size\":10031}]",{"code":44,"message":45,"data":46},200,"success",{"items":47,"stats":48,"page":51},[],{"averageRating":49,"totalRatings":49,"ratingCounts":50},0,[49,49,49,49,49],{"limit":52,"offset":49,"hasMore":53,"nextOffset":52,"ratedOnly":16},15,false]