Search Sreeni's Insights

Filter by content type
technical December 14, 2017 6 min read

Saga pattern - managing transactions across microservices

The Saga pattern coordinates distributed transactions through choreography, orchestration and compensation, with a fund subscription example covering failures and durable state.

Share:

Saga pattern - managing transactions across microservices

A fund subscription is crossing several service boundaries. One service reserves units, another takes payment, another confirms allocation and a document service sends the factsheet. A database transaction cannot safely include all these services, and a failure in the middle is leaving the business process incomplete.

In this article, we are going to see the Saga pattern, why two-phase commit does not fit many microservice designs, and how choreography, orchestration and compensating transactions can manage a fund subscription workflow. This article is closing the 2017 Software Architecture series.

TL;DR Summary

  • A saga is a sequence of local transactions with compensating actions.
  • Two-phase commit and MSDTC create availability and ownership coupling across services.
  • Choreography lets services react to events; orchestration uses a coordinator to direct steps.
  • A fund subscription can reserve units, take payment, confirm allocation and notify the investor.
  • Compensation is a business action, not a database rollback.
  • Correlation, idempotency, timeouts and persisted saga state are mandatory for diagnosis and recovery.

Challenges

No global transaction

A subscription service, unit service and payment service are owning separate data stores. A transaction which spans all of them is coupling availability and technology, and a failed coordinator can leave locks or uncertain outcomes.

Partial completion

The reserve-units step may succeed while payment fails. The system must release the units or place the subscription in a review state. “Rollback” is not undoing a remote business action automatically.

Long-running workflow

The process may wait for payment confirmation or an external settlement result. Keeping a web request open is reducing reliability, so the workflow needs persisted state and asynchronous commands.

What is the Saga pattern?

The Saga pattern is a sequence of local transactions where each step publishes an outcome and a failure triggers compensating actions for completed steps.

In simple terms, a saga is a business process with memory. It is remembering which steps succeeded, which action is next and what to do when a later step fails. The origin is commonly traced to Garcia-Molina and Salem’s 1987 work on sagas.

The following diagram compares choreography and orchestration for the same subscription workflow.

Saga choreography versus orchestration
Saga choreography versus orchestration

Choreography has services reacting to events without one central coordinator. Orchestration has a saga coordinator sending commands and recording state. The purple path highlights orchestration, which is often easier to understand for a long fund workflow.

Why sagas are important?

Sagas are important because they are allowing a business transaction to cross services without pretending that one database transaction owns everything. The application can make progress, handle partial failure and show an explicit pending or rejected state.

In our case, a fund subscription saga can reserve units, take payment, confirm allocation and notify the investor. If payment fails, the compensation is releasing the units. If notification fails, the allocation may remain confirmed while notification is retried, because sending a notification is not the same business action as reserving units.

Why not two-phase commit?

Two-phase commit coordinates a prepare and commit across participants, but it is coupling services to a transaction coordinator and requiring participants to hold resources while the global decision is made. In a distributed, independently deployed platform, the availability and operational cost are often not acceptable.

MSDTC can be useful in a controlled Windows and SQL environment, but it is not making a microservice boundary independent. Choose a saga when the business can accept eventual consistency and compensating actions.

Choreography versus orchestration

ApproachProsCons
Choreography+ No central coordinator
+ Services react to events
− Flow is harder to see
− Event coupling can spread
Orchestration+ One workflow and state owner
+ Easier timeout and compensation view
− Coordinator needs operations
− Can become a central business bottleneck

Choose choreography for a small number of independent reactions. Choose orchestration when the fund workflow has ordered steps, timeouts, compensation and a business owner who needs one status.

Worked fund subscription saga

The normal flow is,

  1. Create a subscription with status Pending.
  2. Send ReserveUnits to the units service.
  3. Send TakePayment after units are reserved.
  4. Confirm allocation after payment succeeds.
  5. Send NotifyInvestor.

If unit reservation fails, mark the subscription rejected. If payment fails after reservation, send ReleaseUnits and mark the subscription failed. If allocation confirmation fails, retry the command and move to manual review after the timeout. If notification fails, retry notification without reversing the financial allocation.

The following diagram depicts compensation for a failed payment step.

Saga compensation flow
Saga compensation flow

The purple path is the failure and compensation path. Compensation must be idempotent: receiving ReleaseUnits twice must not release units twice.

State, correlation and commands

Persist saga state in a store owned by the saga or orchestration service,

SubscriptionId: <subscription-id>
CorrelationId: <correlation-id>
State: PaymentFailed
Completed: ReserveUnits
Pending: ReleaseUnits
Attempt: <attempt-number>

Use Service Bus commands for durable steps, referring to the event-driven microservices article for the queue and topic design. Every command should contain correlation id, causation id, idempotency key and a deadline where practical.

Frameworks such as NServiceBus sagas and MassTransit Automatonymous can provide workflow support. They do not remove the need to design business compensation, state ownership and operational monitoring.

Selection criteria

Choose a saga when a business process crosses independent data stores, can tolerate eventual consistency and has a meaningful compensation or manual-review path. Do not use a saga for a simple local transaction which one service can complete atomically.

Choose orchestration when the order and compensation need to be visible. Choose choreography when independent reactions are more important than one central workflow. In both cases, persist state and make every consumer idempotent.

The saga status should be visible to support teams. A pending payment, rejected reservation and manual-review state are different business outcomes, not only technical failures. Include the current step, last error, next retry time and correlation id in the operational view, while keeping payment and investor data protected.

Test the failure matrix, not only the happy path. Stop the process after a reservation, after payment and after allocation, then restart the saga and verify that the persisted state drives the correct next command. Repeat a compensation message and confirm that the units, payment and notification records remain correct.

Timeouts should lead to a known business state. A payment timeout can remain pending while the payment service confirms the result, whereas a rejected payment can trigger release immediately. Do not treat every network failure as a business rejection, because the remote operation may have completed successfully before the response was lost.

Must Do / Should / Don’t

Must Do

  • Must define local transactions and compensating actions.
  • Must persist saga state, correlation id and current step.
  • Must make commands and compensations idempotent.
  • Must define timeout, retry, dead-letter and manual-review behaviour.

Should

  • Should use orchestration for a long, ordered fund workflow.
  • Should use Service Bus for durable commands.
  • Should test failures after every completed step.

Don’t

  • Don’t call compensation a database rollback.
  • Don’t assume two-phase commit creates an independent microservice.
  • Don’t leave a saga process in memory without persisted state.
  • Don’t notify an investor as successful before the business outcome is confirmed.

Wrap up

In this article, we have looked at the Saga pattern, local transactions, two-phase commit, choreography, orchestration, compensation, fund subscriptions, Service Bus commands and persisted state.

I really appreciate that you took the time to read this article. This article closes the 2017 Software Architecture series.

Related Posts