Skip to content

Saga pattern

Коротко:

Saga pattern — способ обеспечить consistency в distributed transactions без 2PC (two-phase commit). Разбивает транзакцию на локальные steps + compensation actions (отмена step'а, если следующий failed). Два стиля: choreography (events между сервисами) и orchestration (central coordinator). Popular в microservices при purchase flows: order → payment → shipping → confirm, rollback on any failure.

Ниже: подробности, пример, смежные термины, FAQ.

Подробности

  • Choreography: services listen to events, react. Loose coupling, harder to debug
  • Orchestration: saga orchestrator manages flow (Netflix Conductor, Temporal, AWS Step Functions)
  • Compensation: каждый step имеет inverse. Payment → RefundPayment
  • Idempotency: steps должны быть idempotent на retry
  • Failure modes: partial completion, retry storms

Пример

Saga: PlaceOrder
1. ReserveInventory      → compensation: ReleaseInventory
2. ChargePayment         → compensation: RefundPayment
3. ShipOrder             → compensation: CancelShipment
On failure at step 3 → run compensations 2, 1 in reverse

Смежные термины

Больше по теме

Часто задаваемые вопросы

Saga vs 2PC?

2PC (XA transactions) — synchronous, locks ресурсы, не масштабируется, редко в cloud. Saga — async, eventual consistency, no locks.

Choreography или orchestration?

Choreography для 2-3 services. Orchestration для complex flows (5+ steps) — легче debug и modify.

Tool recommendations?

Temporal (temporal.io) — modern, durable execution. Netflix Conductor. AWS Step Functions. For simpler — just messages via Kafka/RabbitMQ.