saga-orchestration
Что он делает
Этот инструмент помогает управлять сложными процессами, в которых участвуют несколько систем. Он гарантирует, что если одна часть даст сбой, весь процесс можно будет аккуратно откатить, например отменить многоэтапную покупку (оплату, склад, доставку).
Когда использовать
- ✓Когда нужно координировать действия в нескольких системах, не блокируя все подряд.
- ✓Чтобы откатывать операции, которые частично провалились.
- ✓Когда нужно управлять длительными процессами, которые могут идти часами.
Ссылка на скилл
https://github.com/wshobson/agents/blob/main/plugins/backend-development/skills/saga-orchestration/SKILL.mdСкопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.
Как использовать
Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.
Готовое сообщение для вставки
Для Claude Code, Codex или Cursor: запустите в папке проекта, и скилл установится.
Скачайте SKILL.md и положите его в папку скиллов вашего агента.
Пример запроса к вашему ИИ
“Как убедиться, что покупка будет корректно отменена, если доставка не удалась уже после списания оплаты?”
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 может блокировать системы и плохо работает в современных распределенных средах. Саги используют более гибкую асинхронную модель.
Подробности
Оригинальное описание автора
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
- Обновлён
- 15.10.2026
Комментарии
- …
Другие скиллы из этого репозитория
screen-reader-testing
41kАгент тестирует сайты с программами чтения с экрана на доступность.
wcag-audit-patterns
41kПомогает агенту проверять доступность сайтов по WCAG и исправлять проблемы.
multi-reviewer-patterns
41kАгент координирует параллельные ревью кода, объединяя находки в отчёт.
parallel-debugging
41kАгент отлаживает сложные проблемы параллельными расследованиями.
Похожие скиллы
api-connector-builder
280kАгент создаёт новые подключения к API по существующему шаблону. Используйте, когда нужна ещё одна интеграция без нового способа делать то же самое.
api-design
280kПомогает агенту проектировать REST API по лучшим практикам: как API общаются, как показываются ошибки и как организовать данные.
backend-patterns
280kПомогает агенту с архитектурными паттернами серверной части и оптимизацией баз данных. Полезен при создании и проверке серверного кода.