saga-orchestration
它能做什么
这个工具可以帮你管理涉及多个系统的复杂流程。如果其中某一步失败了,它能有条理地把整个流程撤销,就像撤销一次多步骤的购买(付款、库存、发货)一样。
适用场景
- ✓当你需要协调跨多个系统的操作,又不想把所有东西都锁住时。
- ✓当你需要撤销部分失败的操作时。
- ✓当你要管理可能持续数小时的长时间运行流程时。
技能链接
https://github.com/wshobson/agents/blob/main/plugins/backend-development/skills/saga-orchestration/SKILL.md复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。
使用方法
最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 Claude Code、Codex 或 Cursor:在项目文件夹中运行,即可安装该技能。
下载 SKILL.md,放进智能体的技能文件夹。
可以这样问 AI
“如果付款后发货失败,我怎样确保订单能被正确取消?”
每周 5 个新技能,1 分钟读完。
工作原理
它会定义流程的各个步骤、每一步要做什么,以及某一步出错时如何撤销该步骤。整个过程是异步进行的,不会让系统卡住。
技术内容(原始 SKILL.md)
作者在 GitHub 上的英文原文。
Saga Orchestration
Patterns for managing distributed transactions and long-running business processes without two-phase commit.
Inputs and Outputs
What you provide:
- Service boundaries and ownership (which service owns which step)
- Transaction requirements (which steps must be atomic, which can be eventual)
- Failure modes for each step (transient vs. permanent, retry policy)
- SLA requirements per step (informs timeout configuration)
- Existing event/messaging infrastructure (Kafka, RabbitMQ, SQS, etc.)
What this skill produces:
- Saga definition with ordered steps, action commands, and compensation commands
- Orchestrator or choreography implementation for your chosen pattern
- Compensation logic for each participant service (idempotent, always-succeeds)
- Step timeout configuration with per-step deadlines
- Monitoring setup: state machine metrics, stuck saga detection, DLQ recovery
When to Use This Skill
- Coordinating multi-service transactions without distributed locks
- Implementing compensating transactions for partial failures
- Managing long-running business workflows (minutes to hours)
- Handling failures in distributed systems where atomicity is required
- Building order fulfillment, approval, or booking processes
- Replacing fragile two-phase commit with async compensation
Detailed section: Core Concepts
Moved to references/details.md.
Detailed section: Templates
Moved to references/details.md.
Best Practices
Do's
- Make every step idempotent — Commands may be replayed on broker reconnect
- Design compensations carefully — They are the most critical code path
- Use correlation IDs — The
saga_idmust flow through every event and log - Implement per-step timeouts — Never wait indefinitely for a participant reply
- Log state transitions —
saga_id,step_name,old_state → new_stateon every change - Test compensation paths explicitly — Inject failures at each step index in integration tests
Don'ts
- Don't assume instant completion — Sagas are async and may take minutes
- Don't skip compensation testing — The rollback path is the hardest to get right
- Don't couple services directly — Use async messaging, never synchronous calls inside a saga step
- Don't ignore partial failures — A step that partially executed still needs compensation
- Don't use a global timeout — Each step has different latency characteristics
Troubleshooting
Saga stuck in COMPENSATING state
A saga enters compensation but never reaches FAILED. This means a compensation handler is throwing an unhandled exception and never publishing SagaCompensationCompleted. Add dead-letter queue (DLQ) handling to compensation consumers and ensure every compensation action publishes a result event even when the underlying operation was already rolled back.
async def handle_release_reservation(self, command: Dict):
try:
await self.release_reservation(command["original_result"]["reservation_id"])
except ReservationNotFoundError:
pass # Already released — treat as success
# Always publish completion, regardless of outcome
await self.event_publisher.publish("SagaCompensationCompleted", {
"saga_id": command["saga_id"],
"step_name": "reserve_inventory"
})
Duplicate saga executions on restart
If your orchestrator service restarts mid-saga, it may replay events and re-execute already-completed steps. Guard every step action with an idempotency key — see Template 3 above.
Choreography saga losing events
In a choreography-based saga, a downstream service may miss an event if it was offline when published. Use a durable message broker (Kafka with replication, RabbitMQ with persistence) and store the current saga state in a dedicated saga_log table so you can replay from the last known good step.
Timeout firing before a slow-but-valid step completes
A step like create_shipment might take up to 15 minutes during peak load but your global timeout is 5 minutes, causing spurious compensation. Make step timeouts configurable per step type — see references/advanced-patterns.md for the TimeoutSagaOrchestrator implementation and the STEP_TIMEOUTS dict pattern.
Compensation order not matching execution order
…
常见问题
什么是“分布式事务”?
这是指涉及多个系统或数据库的操作,需要被当作一个整体来处理:要么全部成功,要么全部不成功。
“补偿”是什么意思?
如果流程后面的某一步失败,补偿就是撤销前面步骤已经完成的操作。例如,如果商品无法发货,就把已付的款退还。
为什么不用“两阶段提交”(2PC)?
2PC 可能会锁住系统,在现代分布式环境中也不太好用。Saga 采用更灵活的异步模型。
详情
作者的原始描述
Implement saga patterns for distributed transactions and cross-aggregate workflows. Use this skill when implementing distributed transactions across microservices where 2PC is unavailable, designing compensating actions for failed order workflows that span inventory, payment, and shipping services, building event-driven saga coordinators for travel booking systems that must roll back hotel, flight
repo: wshobson/agents
热度
- GitHub 星标
- 41k
- 排名
- #6641
- 许可证
- MIT
- 更新时间
- 2026/10/15
评论
- …