Sagas and Process Managers
Sagas and Process Managers in Symfony 8: compensating transactions, choreography, and orchestration of long-running processes through Messenger. Including timeouts, parallel steps, and monitoring.
In this chapter
Event Sourcing from the previous chapter handles persistence inside a single aggregate. Sagas coordinate processes across several aggregates and Bounded Contexts that communicate through domain events.
14.01 Why do we need sagas?#
The illustrative example is a typical online store: a customer submits an order, and the system has to carry out four steps in four different Bounded Contexts:
- Ordering – creating the order (the
Orderaggregate), - Payment – charging the customer (the
Paymentaggregate), - Warehouse – reserving the goods in stock (the
StockReservationaggregate), - Shipping – creating the shipment (the
Shipmentaggregate).
Each of these contexts has its own aggregate, its own database (or at least its own tables with strictly separated responsibility), and its own invariants to protect. Aggregates from different Bounded Contexts are not changed in one database transaction, because that would violate the autonomy of the contexts. One context does not reach into another's database; it communicates only through messages (events and commands).
On top of that, the contexts may run on different servers and use different database systems (PostgreSQL for orders, Redis for stock reservations, an external payment gateway for payments). They communicate asynchronously through a message queue. No atomic transaction spans them.
An example of failure: the system successfully charges the customer (step 2), but when reserving stock it finds that the goods are not available (step 3 fails). The customer has lost money, has no goods, and the system is in an inconsistent state. Without a mechanism that detects and repairs the state, the situation will not resolve itself.
The basic shape of the solution was described back in 1987 by Hector Garcia-Molina and Kenneth Salem in the paper Sagas. They call a saga a long-running transaction broken down into a series of sub-transactions, each with a defined compensating action. If one of the steps fails, the system runs the compensations of all previous successful steps – in reverse order.
What a saga meant in 1987
The original motivation differed from today's. The authors were not dealing with distribution but with locks: a long transaction holds resources, and short transactions queue up behind it. The environment is a single centralized database, and the sub-transactions are ordinary ACID transactions on the same system. Coordination is handled by a component called the Saga Execution Component, which reads the transaction log and, after a crash, finds the last uncompensated transaction. It is, in other words, an orchestrator. Choreography, where the flow emerges from the reactions of the participants, does not appear in the paper at all.
One observation from the paper has survived unchanged: other transactions can see the effects of a partially executed saga. While compensation runs, nobody notifies or aborts the transactions that have meanwhile read the result of the compensated step. This is the origin of today's claim that a saga lacks isolation (see Saga isolation).
Today's distributed saga thus carries the name of an older pattern but solves a different problem: the autonomy of services with separate databases. The second root lies in Enterprise Integration Patterns, where a Process Manager holds the state of a sequence and decides the next step based on intermediate results. The third was added by Udi Dahan, who in 2007 dropped the term workflow in NServiceBus in favor of the saga as a stateful message handler with correlation and timeouts. Compensations barely figure in his version; they belong to Richardson's line.
Which convention the book uses
The result is three incompatible definitions that live side by side today. The Microsoft patterns & practices team deliberately abandoned the term “saga” in its CQRS Journey guide and speaks only of a Process Manager, pointing to the older and different meaning of the word. It also proposes a dividing line that practice did not adopt: a Process Manager routes messages inside a single Bounded Context, while a saga drives a process across context boundaries. Richardson, by contrast, calls both a saga and treats orchestration as an implementation detail. The third line follows the style of coordination: a saga runs on events and compensations, while a Process Manager translates events into commands.
The book follows Richardson's view with one refinement. “Saga” is the umbrella term for a long-running process broken down into local transactions with compensations, whether it is driven by choreography or orchestration. “Process Manager” is the orchestrating component with persistent state that drives such a saga; section 14.05 shows it. With an outside source, it pays to check which of the conventions it uses.
Citations: Garcia-Molina, H. & Salem, K., Sagas, ACM SIGMOD (1987); Hohpe, G. & Woolf, B., Enterprise Integration Patterns (2003); Dahan, U., No more workflow for nServiceBus – please welcome the Saga (2007); Microsoft patterns & practices, CQRS Journey (2012), Reference 6: A Saga on Sagas; Vernon, V., Implementing Domain-Driven Design (2013), ch. 4 and 13; Richardson, C., Microservices Patterns (2018), ch. 4.
A saga can be coordinated in two ways: through choreography and through orchestration. The implementation in Symfony 8 builds on Symfony Messenger.
14.02 Compensating transactions#
A compensating transaction is a semantic reversal of the effect of a previous step. Unlike a technical rollback of a database transaction (which “erases” the changes as if they had never happened), a compensation is a full-fledged domain operation. It has its own side effects: notifications, audit records, status updates. The system does not return to its original state bit by bit, but to a state that, from the domain's point of view, corresponds to the state before the compensated step.
Online store actions and their compensations:
| Action | Compensation | Note |
|---|---|---|
ChargeCustomer |
RefundCustomer |
Includes notifying the customer |
ReserveStock |
ReleaseStock |
Releases the reservation, does not delete it |
CreateShipment |
CancelShipment |
Only until the moment of dispatch |
A compensation is not an exact inverse command. While
ChargeCustomer takes the money, the compensating RefundCustomer returns
it and, on top of that, sends the customer a notification, writes a record
to the audit log, and may update internal metrics. Every compensation is a separate
command with its own logic, validation, and side effects.
When a process cannot be a saga
Not every multi-step process tolerates being split into compensatable steps. Garcia-Molina and Salem give a counterexample that still works as a test today: a money transfer between accounts. The first step debits the amount and holds it in a local variable; the last one credits it. In between, the money is nowhere in the database. Such an intermediate state is not incomplete but unreadable for the domain: an audit run between the steps will not find all the funds.
The difference between an “incomplete” and an “unreadable” intermediate state is a usable design criterion. An order with a captured payment and unreserved goods is incomplete: the domain has a name for that state, and an operator knows how to deal with it. Money that is in no account and in no record has no name. If no understandable state in the Ubiquitous Language can be written for the saga's intermediate state, the pattern does not fit in this form.
The same paper also offers a way out. If the debited amount is stored in the database as funds in transit, the intermediate state gets a name, and the transfer can be a saga. Transactions that need to see all the money then have to account for this record, which is why the authors recommend designing it from the start rather than bolting it on later. That is how the Aggregate Design chapter handles the transfer. When the domain does not want to name such a state, the steps belong in one transaction on one aggregate.
14.03 Choreography#
In choreography, there is no central coordinator. Each Bounded Context reacts to events published by other contexts and performs its step of the process based on them. No service knows about the whole flow: each knows only its own part and the events it should react to.
In the online store, a choreographed saga runs like this: the Ordering context
publishes the OrderPlaced event (across the boundary as OrderPlacedIntegrationEvent). The Payment context reacts to it, charges
the payment, and publishes PaymentSucceeded. The Warehouse context listens for
the PaymentSucceeded event, reserves the goods, and publishes
StockReserved. The Shipping context reacts to StockReserved
and creates a shipment, publishing ShipmentCreated. The whole flow emerges
from the reactions of the individual contexts to the events of the others – without central
control.
For brevity, handlers 2 and 3, as well as the Process Manager later in the chapter, consume the domain
events of other contexts directly (PaymentSucceeded, StockReserved). In production, Payment
and Warehouse would publish them as integration events through an outbox, just as Ordering
publishes OrderPlacedIntegrationEvent in the
Outbox Pattern chapter.
The main advantage of choreography is loose coupling between
contexts. Each one reacts only to the events that reach it and knows nothing about
the others. Adding a new context (for example Loyalty, which awards points for an order)
requires no change to existing code: a new handler listening for
OrderPlacedIntegrationEvent is enough. As long as the sequence of steps is known in advance and runs linearly, choreography
is sufficient.
14.04 Limits of choreography#
In processes with five or more contexts, or with conditional branching, choreography runs into four problems that are invisible at a smaller scale.
1. Invisible process flow
With choreography, the whole domain process is not described in any single place. The flow is scattered across dozens of handlers in different contexts. Nobody has an overview of which steps follow one another, where the process branches, and what the alternative paths are on failure. The result is called distributed spaghetti.
2. Violating the Open-Closed Principle
A new process step often requires changing an existing context. Inserting a fraud check
(Fraud Detection) between payment and the warehouse means changing the handler in Warehouse:
instead of PaymentSucceeded, it has to listen for the FraudCheckPassed event. Existing code
changes because of a new step, and that violates the Open-Closed Principle. With orchestration,
adding the step to the central Process Manager would be enough, without touching the existing contexts.
3. Hard-to-diagnose failures
When the process “gets stuck,” the cause is hard to find. Each context knows only its own step;
nobody knows the overall state of the process. An operator has to go through the logs of all
contexts by hand, correlate events by orderId, and reconstruct exactly where
the process failed. There is no central dashboard that would show:
“Order #42 – payment OK, warehouse FAILED, shipment NOT STARTED.”
With thousands of orders a day, that kind of investigation is unsustainable.
4. Missing timeout management
The Payment context charges the payment, but Warehouse never reacts: the handler crashed, the message
got lost in the queue. Nobody finds out that the process is stuck. None of the contexts knows
the time limits of the whole process, and choreography has no natural place for a global timeout –
for example, for the rule that the process from OrderPlaced to ShipmentCreated may take
at most 30 minutes.
A complex process therefore needs a central place that knows the whole flow, drives the steps, detects failures, and triggers compensations. This role is filled by the orchestrator – the Process Manager.
14.05 Orchestration – the Process Manager#
In orchestration, a single class drives the whole domain process: the Process Manager. It works
as a state machine with defined states and transitions. In the online store, this role is filled by
OrderProcessManager: it receives events from all contexts (Payment, Warehouse, Shipping)
and uses them to decide which command to issue as the next step. The complete flow from OrderPlaced
to ShipOrder is visible in one place.
The diagram shows the state machine of the order process. Green arrows mark successful transitions, red ones mark failures, and the orange path leads through compensation:
The order passes through three states: the factory already puts it into Confirmed
(placeWithItems() from the Outbox Pattern chapter
receives a complete order, so it leaves Draft immediately);
from there, MarkOrderPaid moves it to Paid and ShipOrder to Shipped. The saga itself does not change
the aggregate's state; it only sends commands and waits for events.
This is where you find out whether the process has been thought through: if a single command is missing, the saga runs
to Completed and the order stays half-finished. Nothing crashes anywhere; the states quietly drift apart.
That is why a process test checks the aggregate's state as well, not only the saga's state.
Unlike choreography, the whole domain process is described in a single place, so a developer
can see the complete flow from order to dispatch. When debugging, checking the saga's state
in the database is enough to see which step the process is stuck at. Extending it with a new
step (for example Fraud Detection between payment and the warehouse) means a new state in the enum,
a new method for FraudCheckPassed, and a change to onPaymentSucceeded, which issues a command
for the fraud check instead of reserving stock. The whole change stays
in the Process Manager and its enum of states. Neither the Warehouse nor the Payment context is modified.
Step events
Each step announces its result with an immutable event. Apart from eventId, the event carries only primitives,
because it travels between contexts, and the receiver should not need to know another context's value objects.
1<?php2 3declare(strict_types=1);4 5// --- src/Payment/Domain/Event/ ---6namespace App\Payment\Domain\Event;7 8use Symfony\Component\Uid\Uuid;9 10// Every step event carries its own identity. Without it, the saga idempotence11// from section 14.06 cannot be switched on – the guard has nothing to hold on to,12// and a repeated delivery performs the transition a second time.13final readonly class PaymentSucceeded14{15 public function __construct(16 public Uuid $eventId,17 public string $orderId,18 public string $transactionId = '',19 ) {}20}21 22final readonly class PaymentFailed23{24 public function __construct(25 public Uuid $eventId,26 public string $orderId,27 public string $failureReason,28 ) {}29}30 31final readonly class RefundSucceeded32{33 public function __construct(34 public Uuid $eventId,35 public string $orderId,36 public string $refundId = '',37 ) {}38}39 40final readonly class RefundFailed41{42 public function __construct(43 public Uuid $eventId,44 public string $orderId,45 public string $failureReason,46 ) {}47}48 49// --- src/Warehouse/Domain/Event/ ---50namespace App\Warehouse\Domain\Event;51 52use Symfony\Component\Uid\Uuid;53 54final readonly class StockReserved55{56 public function __construct(57 public Uuid $eventId,58 public string $orderId,59 public string $reservationId = '',60 ) {}61}62 63final readonly class StockReservationFailed64{65 public function __construct(66 public Uuid $eventId,67 public string $orderId,68 public string $failureReason,69 ) {}70}71 72// --- src/Shipping/Domain/Event/ ---73namespace App\Shipping\Domain\Event;74 75use Symfony\Component\Uid\Uuid;76 77final readonly class ShipmentCreated78{79 public function __construct(80 public Uuid $eventId,81 public string $orderId,82 public string $shipmentId = '',83 ) {}84}
All of them carry orderId, the correlation key the Process Manager uses to
find its saga. Without it, the event could not be matched to a running process.
Step handlers live in other contexts
The Process Manager only sends out commands. They are always executed by a handler in the context that
owns the step – and that handler knows nothing about the saga's existence. The listing shows one of them; ReserveStockHandler
and CreateShipmentHandler have the same shape, only with a different aggregate and a different resulting event:
1<?php2 3declare(strict_types=1);4 5namespace App\Payment\Application\Handler;6 7use App\Payment\Application\Command\ChargeCustomer;8use App\Payment\Domain\Event\PaymentFailed;9use App\Payment\Domain\Event\PaymentSucceeded;10use App\Payment\Domain\PaymentGateway;11use Symfony\Component\DependencyInjection\Attribute\Target;12use Symfony\Component\Messenger\Attribute\AsMessageHandler;13use Symfony\Component\Messenger\MessageBusInterface;14use Symfony\Component\Uid\Uuid;15 16#[AsMessageHandler(bus: 'command.bus')]17final readonly class ChargeCustomerHandler18{19 public function __construct(20 private PaymentGateway $gateway,21 #[Target('event.bus')]22 private MessageBusInterface $eventBus,23 ) {}24 25 public function __invoke(ChargeCustomer $command): void26 {27 // The handler does not know about the saga. It only executes the step and reports28 // the result; the Process Manager decides what happens next.29 try {30 $transactionId = $this->gateway->charge(31 $command->customerId,32 $command->amountCents,33 );34 } catch (\RuntimeException $e) {35 $this->eventBus->dispatch(new PaymentFailed(36 eventId: Uuid::v7(),37 orderId: $command->orderId,38 failureReason: $e->getMessage(),39 ));40 41 return;42 }43 44 $this->eventBus->dispatch(new PaymentSucceeded(45 eventId: Uuid::v7(),46 orderId: $command->orderId,47 transactionId: $transactionId,48 ));49 }50}
Failure is reported with an event, not an exception. An exception would end up in Messenger's retry loop,
and the saga would never learn about the failure. It would hang in the AwaitingPayment state
until a timeout shut it down.
PaymentGateway is a port to the payment gateway; the same applies to the other steps with StockService
and ShippingService. The domain knows only the interface; the concrete adapter comes from infrastructure:
1<?php2 3declare(strict_types=1);4 5namespace App\Payment\Domain;6 7interface PaymentGateway8{9 /**10 * @return string transaction identifier11 * @throws \RuntimeException when the payment does not go through12 */13 public function charge(string $customerId, int $amountCents): string;14 15 public function refund(string $transactionId, int $amountCents): string;16}
The examples do not depend on a concrete adapter: behind the interface there can be an HTTP client for the payment
gateway, or, in tests and while getting the examples running, a few lines in memory. That is exactly why the interface
exists. It is a simplified slice with primitives that is enough for the saga. A port with domain
types (Money, PaymentToken, PaymentId) is shown in the chapter
DDD in Practice – Where It Hurts. For the compensation branches, an adapter with a switch that makes the step always fail is enough.
1<?php2 3declare(strict_types=1);4 5namespace App\Payment\Infrastructure;6 7use App\Payment\Domain\PaymentGateway;8use Symfony\Component\Uid\Uuid;9 10final readonly class InMemoryPaymentGateway implements PaymentGateway11{12 // A switch for trying out the compensation branch by hand; the container supplies13 // the value (wiring a little further down). In a production adapter, the gateway's response replaces it.14 public function __construct(15 private bool $alwaysFails = false,16 ) {}17 18 public function charge(string $customerId, int $amountCents): string19 {20 if ($this->alwaysFails) {21 throw new \RuntimeException('Payment declined.');22 }23 24 return (string) Uuid::v7();25 }26 27 public function refund(string $transactionId, int $amountCents): string28 {29 return (string) Uuid::v7();30 }31}
StockService and ShippingService have the same structure. The listing is here because without them,
the saga stops after the first payment, and the STOCK_FAILS=1 compensation branch cannot run at all:
1<?php2 3declare(strict_types=1);4 5// --- src/Warehouse/Domain/StockService.php ---6namespace App\Warehouse\Domain;7 8interface StockService9{10 /** @throws \RuntimeException when the goods are out of stock */11 public function reserve(string $orderId): void;12 13 public function release(string $orderId): void;14}15 16// --- src/Shipping/Domain/ShippingService.php ---17namespace App\Shipping\Domain;18 19interface ShippingService20{21 /** @return string shipment identifier */22 public function create(string $orderId): string;23 24 public function cancel(string $shipmentId): void;25}26 27// --- src/Warehouse/Infrastructure/InMemoryStockService.php ---28namespace App\Warehouse\Infrastructure;29 30use App\Warehouse\Domain\StockService;31 32final readonly class InMemoryStockService implements StockService33{34 public function __construct(private bool $alwaysFails = false) {}35 36 public function reserve(string $orderId): void37 {38 if ($this->alwaysFails) {39 throw new \RuntimeException('Out of stock.');40 }41 }42 43 public function release(string $orderId): void44 {45 }46}47 48// --- src/Shipping/Infrastructure/InMemoryShippingService.php ---49namespace App\Shipping\Infrastructure;50 51use App\Shipping\Domain\ShippingService;52use Symfony\Component\Uid\Uuid;53 54final readonly class InMemoryShippingService implements ShippingService55{56 public function create(string $orderId): string57 {58 // The interface returns a string, not a value object: the identifier59 // travels in an event across the context boundary. ShipmentId is built60 // from it only by ShipOrderHandler in Ordering.61 return (string) Uuid::v7();62 }63 64 public function cancel(string $shipmentId): void65 {66 }67}
The container wiring belongs in services.yaml; without it, the switches default to false,
and the compensation branch never runs, whatever you put in the environment:
1parameters:2 # Defaults for when .env does not define the variables – they are written3 # to the file only in the Practical Examples chapter. Without them, the container4 # fails with “Environment variable not found.”5 env(PAYMENT_FAILS): '0'6 env(STOCK_FAILS): '0'7 8services:9 App\Payment\Infrastructure\InMemoryPaymentGateway:10 arguments: { $alwaysFails: '%env(bool:PAYMENT_FAILS)%' }11 12 App\Warehouse\Infrastructure\InMemoryStockService:13 arguments: { $alwaysFails: '%env(bool:STOCK_FAILS)%' }14 15 App\Warehouse\Domain\StockService: '@App\Warehouse\Infrastructure\InMemoryStockService'16 App\Shipping\Domain\ShippingService: '@App\Shipping\Infrastructure\InMemoryShippingService'
The remaining step handlers have the same structure as ChargeCustomerHandler: they perform the operation
and issue an event. The ones that only change the aggregate's state are even shorter:
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Application\Handler;6 7use App\Ordering\Application\Command\MarkOrderPaid;8use App\Ordering\Domain\Repository\OrderRepository;9use App\Ordering\Domain\ValueObject\OrderId;10use Doctrine\ORM\EntityManagerInterface;11use Symfony\Component\DependencyInjection\Attribute\Target;12use Symfony\Component\Messenger\Attribute\AsMessageHandler;13use Symfony\Component\Messenger\MessageBusInterface;14 15#[AsMessageHandler(bus: 'command.bus')]16final readonly class MarkOrderPaidHandler17{18 public function __construct(19 private OrderRepository $orders,20 private EntityManagerInterface $em,21 #[Target('event.bus')]22 private MessageBusInterface $eventBus,23 ) {}24 25 public function __invoke(MarkOrderPaid $command): void26 {27 $order = $this->orders->get(OrderId::fromString($command->orderId));28 $order->markPaid();29 $this->em->flush();30 31 // markPaid() records OrderPaid. Without this step, the event would32 // stay in the aggregate, and projections would not know about the state change.33 // Dispatching inside the transaction is fine here: event.bus is34 // synchronous, and nothing leaves the process.35 // If the event were headed for a broker, it would belong in the outbox.36 foreach ($order->releaseEvents() as $event) {37 $this->eventBus->dispatch($event);38 }39 }40}41 42// ShipOrderHandler is identical, it only calls43// $order->ship(ShipmentId::fromString($command->shipmentId));
The commands themselves are plain DTOs. They carry primitives because they travel through an asynchronous
transport: whatever is serialized into the queue must be rebuildable without loss. A value
object can manage that if it has a public constructor and public properties. CancelOrder
from the authorization chapter carries OrderId for exactly this reason. A string is more resilient
to change, though: a renamed field in the VO breaks every message that was waiting in the queue from the previous
version of the application.
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Application\Command;6 7final readonly class MarkOrderPaid8{9 public function __construct(public string $orderId) {}10}11 12final readonly class ShipOrder13{14 public function __construct(15 public string $orderId,16 public string $shipmentId,17 ) {}18}
Commands for other contexts have the same shape and are complemented by the compensations from section 14.02:
1<?php2 3declare(strict_types=1);4 5// --- src/Warehouse/Application/Command/ReserveStock.php + ReleaseStock.php ---6namespace App\Warehouse\Application\Command;7 8final readonly class ReserveStock9{10 public function __construct(public string $orderId) {}11}12 13final readonly class ReleaseStock14{15 public function __construct(public string $orderId) {}16}17 18// --- src/Shipping/Application/Command/CreateShipment.php + CancelShipment.php ---19namespace App\Shipping\Application\Command;20 21final readonly class CreateShipment22{23 public function __construct(public string $orderId) {}24}25 26final readonly class CancelShipment27{28 // A shipment is cancelled by its own identity, not by the order. The saga29 // stores shipmentId from ShipmentCreated – nobody else can know it30 // at that moment.31 public function __construct(32 public string $orderId,33 public string $shipmentId,34 ) {}35}
The remaining five handlers sit in their own contexts and differ from ChargeCustomerHandler only in
the service they call and the name of the event. Two are listed, chosen because they show both cases: a step
that reports its result with an event, and a compensation that reports nothing. None of them can be left out
– a missing handler shows up only as
No handler for message in the dead-letter queue, while the process keeps running. That is the kind of
bug nobody looks for until the states drift apart.
1<?php2 3declare(strict_types=1);4 5namespace App\Warehouse\Application\Handler;6 7use App\Warehouse\Application\Command\ReleaseStock;8use App\Warehouse\Application\Command\ReserveStock;9use App\Warehouse\Domain\Event\StockReservationFailed;10use App\Warehouse\Domain\Event\StockReserved;11use App\Warehouse\Domain\StockService;12use Symfony\Component\DependencyInjection\Attribute\Target;13use Symfony\Component\Messenger\Attribute\AsMessageHandler;14use Symfony\Component\Messenger\MessageBusInterface;15use Symfony\Component\Uid\Uuid;16 17#[AsMessageHandler(bus: 'command.bus')]18final readonly class ReserveStockHandler19{20 public function __construct(21 private StockService $stock,22 #[Target('event.bus')]23 private MessageBusInterface $eventBus,24 ) {}25 26 public function __invoke(ReserveStock $command): void27 {28 try {29 $this->stock->reserve($command->orderId);30 } catch (\RuntimeException $e) {31 $this->eventBus->dispatch(new StockReservationFailed(32 eventId: Uuid::v7(),33 orderId: $command->orderId,34 failureReason: $e->getMessage(),35 ));36 37 return;38 }39 40 $this->eventBus->dispatch(new StockReserved(41 eventId: Uuid::v7(),42 orderId: $command->orderId,43 ));44 }45}46 47#[AsMessageHandler(bus: 'command.bus')]48final readonly class ReleaseStockHandler49{50 public function __construct(private StockService $stock) {}51 52 public function __invoke(ReleaseStock $command): void53 {54 // The compensation issues no event: nobody is waiting for the reservation to be released.55 $this->stock->release($command->orderId);56 }57}
CreateShipmentHandler in the Shipping context calls ShippingService::create() and reports
success with a ShipmentCreated event carrying the shipment identifier from the service. CancelShipmentHandler is
shorter by comparison: it calls cancel($command->shipmentId) and issues nothing. If it issued
ShipmentCreated, the Process Manager in the Compensating state would answer it with another
CancelShipment, creating an endless loop of command and event.
RefundCustomerHandler is the counterpart of ChargeCustomerHandler: it calls
PaymentGateway::refund() and, depending on the result, issues either RefundSucceeded or RefundFailed.
CancelOrderHandler has its own listing in the authorization chapter,
and that is exactly the one you need. It has to recognize the system identity and release
the lock – otherwise the compensation hits OrderLockedBySagaException, ends up in the dead-letter queue,
and the order stays paid, uncancelled, and locked forever. A version that is “like
MarkOrderPaidHandler, only calling cancel()” is not enough for the saga.
How much logic a Process Manager may have
CQRS Journey answers strictly: a Process Manager only routes messages and translates between
types; domain logic belongs in aggregates. The OrderProcessManager in the example crosses
this line. It decides when to compensate, with which command, and how long to wait for
a response.
The book follows Richardson's looser interpretation and names the deviation. An orchestrator may know the order of steps, the transition conditions, and the time limits, because that is the logic of the process. It does not belong to any of the aggregates the process coordinates. The rules of a single aggregate, on the other hand, do not belong in the orchestrator: calculating a price, checking stock availability, verifying a credit limit. They stay in the domain, and the Process Manager sends a command for them. A practical test: if the saga class contains a condition on domain data that an aggregate could answer, that logic sits in the wrong layer.
14.06 Persisting saga state#
A Process Manager needs persistent state storage to survive
a worker restart, a new deployment of the application, and horizontal scaling to several instances.
Without persistence, a worker crash between the OrderPlaced and
PaymentSucceeded steps would wipe out the information about where the process is.
The saga would “hang” forever, and nobody would finish or compensate it. That is why saga state
is stored in the database as a Doctrine entity.
The entity lives in the Application layer: process state is an application concern, not part of the domain model. It carries Doctrine attributes directly, just like the domain entities throughout the book (see Mapping choice: attributes as the default approach). Those who insist on strict layering (Hexagonal Architecture) move the mapping to Infrastructure.
Persisting the state is a precondition for recovery after a failure. When a worker crashes in the middle of
processing a PaymentSucceeded message and does not manage to acknowledge it, Messenger delivers
the same message again after the restart, and the Process Manager loads the saga's state from the database.
If the worker crashed before the save, the saga is still in AwaitingPayment; if it crashed after it,
the saga is already in AwaitingStockReservation. Either way, the context is not lost.
That alone is not enough, though. The onPaymentSucceeded() method shown above has no guard against
repeated delivery, so after a redelivery it performs the transition and the ReserveStock command a second time. Recovery without
duplicates comes only with the idempotent transition from the subsection
Multi-worker Process Manager – what falls apart, which records processed
events and discards the second delivery. The findStale() method in the repository then makes it possible
to periodically detect stuck sagas that have not moved forward for longer than a set threshold
and to trigger compensation or escalation for them.
Multi-worker Process Manager – what falls apart
An optimistic lock resolves a conflict on one saga instance. Production brings
more complex situations: the same message (e.g., PaymentSucceeded for the same order)
arrives at several worker instances at the same time (supervisor with numprocs > 1),
or different events of the same saga arrive in the wrong order (Kafka partition
balancing, RabbitMQ multiple consumers). The consequences:
- A race to create the saga. The first
OrderPlacedfor the sameorderIdreaches two workers at once. Both see that the saga does not exist yet, and both callOrderSaga::start. A UNIQUE constraint on(saga_type, correlation_id)rejects one write; the other stays. Without the constraint, two parallel sagas for the same order come into existence and compete for the state. - Out-of-order events.
PaymentSucceededarrives beforeOrderPlaced, while the saga is not yet in theAwaitingPaymentstate. The Process Manager either discards it (a domain error) or parks it in a pending queue for processing later (at the cost of a more complex state machine). - Compensation races. The saga moves to
Compensatingand sendsRefundCustomer, and at the same time a lateStockReservedarrives from another worker. It can switch the saga's state fromCompensatingback toAwaitingShipment, butRefundCustomeris already running – the customer gets a refund, and the process still continues toward dispatch.
The defense against all three:
The guard belongs in every step, not only in the payment. OrderSaga therefore gets similar
applyStockReserved() and applyShipmentCreated() methods; they differ only in the expected state and the target
of the transition. Without them, a repeatedly delivered StockReserved produces a second and a third shipment.
The saga remembers only the one whose ShipmentCreated arrives first and moves to Completed.
The other two events end at the terminal-state guard, and nobody cancels their shipments.
Meanwhile, the order ends up shipped and the dead-letter queue stays empty – nothing gives it away.
The other half of the defense belongs in the aggregate. cancel(), markPaid(), and ship()
in the canonical version from Aggregate Design end silently on a repeated
delivery. Without that branch, a repeated MarkOrderPaid would end up in the DLQ after three
retries with InvalidOrderStateTransitionException (a transition from paid to paid). The data would not
be corrupted, but nobody would find out. An excerpt as a reminder:
1public function markPaid(): void2{3 // A repeated delivery of the command is not the caller's mistake; there is4 // nothing left to do. The transport guarantees at-least-once, not exactly-once.5 if ($this->status === OrderStatus::Paid) {6 return;7 }8 9 if ($this->status !== OrderStatus::Confirmed) {10 throw InvalidOrderStateTransitionException::cannotTransition(11 $this->status->value,12 OrderStatus::Paid->value,13 );14 }15 16 $this->status = OrderStatus::Paid;17 $this->record(new OrderPaid($this->id, new \DateTimeImmutable()));18}19 20// ship() has the same branch for OrderStatus::Shipped.
Three building blocks work together here:
- A UNIQUE constraint on
(saga_type, correlation_id)prevents the saga from being created twice. The second INSERT throwsUniqueConstraintViolationException; the handler catches it, resets the EntityManager, and finishes without sending a second command. processedEventIdsin the entity holds the identifiers of events that have already been processed. When the same event arrives a second time, the call stops at the guard. This is an “inbox per saga,” a counterpart of the Idempotent Inbox from the Outbox Pattern chapter.- The state machine guard rejects an event that arrived out of order, and either discards it or parks it in a pending events column for processing later.
The solution has two limitations. The in_array check on a JSON column
is not atomic: two workers can pass the guard at the same time, because each works with
its own copy loaded before the write. The duplicate write is caught only by the optimistic lock,
and one of the workers gets an OptimisticLockException. The guard thus filters out ordinary
redeliveries; concurrency is handled only by the row version. The second limitation is growth: processedEventIds
never shrinks. For a saga with dozens of steps, that does not matter. In long-running processes
with thousands of events, though, the column bloats. The fix is to empty it once the saga finishes,
or to keep only the last N identifiers.
The guard also opens a window of its own. save() writes the state and the processed eventId before
the commands go out. If the worker crashes between the write and the dispatch, the redelivery stops
at the guard, and neither MarkOrderPaid nor ReserveStock goes out anymore. The saga then sits
in AwaitingStockReservation until stuck saga detection catches it.
The only way to close the window is to write the saga state and the outgoing commands in one transaction, for example
through the Outbox.
Distributed deadlock between sagas
The classic deadlock of two aggregates through a Doctrine pessimistic lock: saga A holds
a lock on Order#1 and requests Inventory#42; saga B holds a lock on Inventory#42
and requests Order#1. The PostgreSQL deadlock detector aborts one of the transactions after about
1 s (the default deadlock_timeout), but until then both workers are stalled.
With eventual consistency (Vernon's “eventual consistency outside the aggregate boundary,” see Aggregate Design), a database deadlock cannot occur: each saga step is a separate transaction on one aggregate. A different kind is possible, though: a logical cyclic deadlock within the sagas themselves.
An example: during compensation, the OrderProcess saga waits for RefundSucceeded. The
RefundProcess saga (for cancellations) emits it only after OrderCancelled, and OrderProcess
sends that only once its compensation finishes. Each saga waits for an event that only the other
one emits, and neither finishes.
Recovering from an inconsistent saga state
A saga can end up in an inconsistent state even without a bug in its own code: a deployment in the middle of a transaction, an OOM kill halfway through a compensation step, a schema migration that changed the shape of the stored JSON. An operator needs three tools.
The first is read-only inspection. The app:saga:show <id> command prints the current state,
pending events, processed event IDs, and the number of attempts, plus a link to the saga
in Grafana. The second is a manual transition: app:saga:force-transition <id> <to>
with a mandatory --reason="..." updates the status, writes an audit log entry, and invalidates pending
events. It belongs exclusively to operators, and every use of it signals a bug in the saga or
an unhandled domain scenario. The third tool is a replay from the starting event: for an idempotent
saga, deleting the state and replaying all of its events from the outbox or the event store is enough.
The precondition is knowing the correct initial event (typically the ID of the OrderPlaced event).
Saga isolation: ACD without the I
A database transaction provides ACID. A saga provides only ACD: atomicity through compensations, consistency, and durability. Isolation is missing: every committed step is immediately visible to all concurrent processes, long before the whole saga finishes. Another process working on the same order or stock can read the half-finished state and overwrite it. The anomalies known from databases appear: a lost update (the cancellation saga overwrites a change the order saga is in the middle of making) and a dirty read (a process reads a payment that a compensation refunds a moment later).
Richardson describes six countermeasures for these anomalies;
the book examines four. The first two work with the data. A semantic lock is an application-level lock: the record
the saga is working on carries an in-progress flag (in Richardson's terms, a *_PENDING state), and other processes must
respect it. Commutative updates are operations designed so that order does not
matter – crediting and debiting an amount commute, while setting an absolute
balance does not.
The other two work with the course of the saga. A pessimistic view reorders the steps: the change whose dirty read does the most damage (such as crediting an account) is moved after the pivot transaction (see When compensation fails). With reread value, a step rereads the value before writing and verifies that it has not changed since the first read; otherwise it stops or retries the saga. The remaining version file and by value are not covered here.
The semantic lock is the most common of them:
The missing pieces are two simple types:
1<?php2 3declare(strict_types=1);4 5// --- src/Ordering/Application/Command/ReleaseOrderLock.php ---6namespace App\Ordering\Application\Command;7 8final readonly class ReleaseOrderLock9{10 public function __construct(public string $orderId) {}11}12 13// --- src/Ordering/Domain/Exception/OrderLockedBySagaException.php ---14namespace App\Ordering\Domain\Exception;15 16use App\Ordering\Domain\ValueObject\OrderId;17 18final class OrderLockedBySagaException extends \DomainException19{20 public function __construct(public readonly OrderId $orderId)21 {22 parent::__construct(sprintf(23 'Order "%s" is locked by a running process.',24 $orderId->value,25 ));26 }27}
The handler is short but load-bearing: without it, the order stays locked even after the process completes successfully, and the customer can never cancel it.
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Application\Handler;6 7use App\Ordering\Application\Command\ReleaseOrderLock;8use App\Ordering\Domain\Repository\OrderRepository;9use App\Ordering\Domain\ValueObject\OrderId;10use Doctrine\ORM\EntityManagerInterface;11use Symfony\Component\Messenger\Attribute\AsMessageHandler;12 13#[AsMessageHandler(bus: 'command.bus')]14final readonly class ReleaseOrderLockHandler15{16 public function __construct(17 private OrderRepository $orders,18 private EntityManagerInterface $em,19 ) {}20 21 public function __invoke(ReleaseOrderLock $command): void22 {23 $order = $this->orders->get(OrderId::fromString($command->orderId));24 $order->releaseSagaLock();25 26 // No event. Releasing the lock is not a domain change anyone27 // would be waiting for – only the end of the process's exclusive access.28 $this->em->flush();29 }30}
A lock is worth something only if someone releases it on failure as well; otherwise the order stays
blocked forever. That is why the release belongs in every terminal branch of the saga, not only
in the successful one. In the book's examples, the finish() method in the Process Manager does this, and in branches
ending with a cancellation, CancelOrderHandler does it itself, because the command arrives under the system
identity.
The lock alone is not enough, though. That is why OrderProcessManager also subscribes to OrderCancelled
and, on a cancellation, triggers compensation of the completed steps. Each of the three mechanisms covers a different part
of the same problem:
- The lock prevents cancellation in the window while the process runs. Without it, a user could cancel the order
in the middle of the saga, the saga would still charge the payment and create a shipment – and the
MarkOrderPaidandShipOrdercommands would then end up in the DLQ one after another, without anyone noticing. - Reacting to
OrderCancelledcovers cancellations outside that window and the case where the order is cancelled by another process. - The guard on
CompensatinginonStockReserved()andonShipmentCreated()handles a late success: the reservation or the shipment arrives only after compensation began, so it is released again right away. A check for a terminal state is not enough on its own, becauseCompensatingis not terminal.
You only see that all three are needed at runtime. Without them, the saga runs to Completed
on top of a cancelled order, and the difference shows up only when someone reads the dead-letter queue.
Choosing between the lock and a full reaction is a domain decision: may a customer cancel an order whose payment is already in progress? The answer “no, try again in a moment” is acceptable and cheaper.
That choice has a consequence, though. When the chapters of this book are put together,
every order is created already locked (placeWithItems() calls lockForSaga()), and the lock
is released only by the saga, once the order is shipped or cancelled. The customer thus
never gets to cancel their own order: while the process is running, the button is not offered, and once it
finishes, it is too late. In the integrated application, the whole flow from the authorization chapter is then
used only by the system actor.
For an example online store, that is defensible; for a real one, usually not. To let the customer
cancel, you either apply the lock only from the step that is hard to reverse (typically creating
the shipment, not charging the payment), or leave it out and rely on the saga's reaction
to OrderCancelled.
Instead of throwing an exception, conflicting requests can also be queued and executed after the lock is released; for most domains, though, rejection with an exception and a retry on the client side is enough.
Citation: Richardson, C., Microservices Patterns (2018), ch. 4.
14.07 Implementation in Symfony Messenger#
The Process Manager and its state are connected by Symfony Messenger, an asynchronous message bus that delivers events and commands between contexts. The basic bus configuration is described in the Symfony Messenger as the foundation of CQRS section of the CQRS chapter. Specific to sagas are separate transports for events and commands and retry strategies, without which long-running processes lose messages during ordinary outages.
The whole flow: the Ordering context publishes the integration event
OrderPlacedIntegrationEvent through the outbox. Following the routing, Messenger
sends it to the async_events transport. A worker listening on this transport
picks up the message and passes it to OrderProcessManager, which handles it in the
onOrderPlaced() method. That method saves the saga state and dispatches the
ChargeCustomer command to the command bus. Messenger routes this command to the
async_commands transport, where a handler in the Payment context picks it up. After successful
processing, Payment publishes PaymentSucceeded – and the cycle repeats
for the next step of the process.
More on asynchronous message processing, transport configuration, and retry strategies is in the Asynchronous processing section of the CQRS chapter.
14.08 Timeouts and deadlines#
The PaymentSucceeded event may never arrive: a network outage, an unavailable payment
gateway, a message lost in the queue. In a distributed system, a missing response is always
expected. Without an explicit timeout, the saga stays in the AwaitingPayment state forever,
and the order is never completed or cancelled. The solution is a timeout check, a delayed command that, once
the set time has elapsed, checks whether the saga has moved on. If not, it ends the saga
or triggers compensation – depending on whether a step that needs reversing has already happened.
The timeout is scheduled in the Process Manager on every transition to a state in which the saga
is waiting for something. Not just once at the start of the process: if only the first step were watched,
a saga stuck in the AwaitingStockReservation state would never alert anyone.
For this, Messenger offers DelayStamp, which holds a message in the transport for the given
time and only then delivers it to a worker:
The full listing of OrderProcessManager in 14.05 does not have this method;
it is an add-on. Without it, the saga runs without watchdogs; with it, it also sends out CheckSagaTimeout,
which is why the unit test in 14.12 filters it out with the steps() method.
A scheduleTimeout() call belongs in every method that moves the saga into a waiting
state. The onPaymentSucceeded() method thus schedules a check for
AwaitingStockReservation. Checks scheduled for a state the saga has meanwhile
left are discarded by the handler at its very first condition. That is why scheduling is never cancelled anywhere.
The AwaitingShipment state is missing from the constant on purpose. Stock reservation is the pivot
transaction in this process (see When compensation fails), so past it
there is no more compensation, and elapsed time should trigger not a compensation but an escalation
to an operator. That is handled by the stuck saga detection from section 14.11.
14.09 Compensation strategies in practice#
There are two basic strategies for a failed saga step. The choice depends on whether the error is transient (a network outage, temporary unavailability of a service) or permanent (insufficient funds in the account, goods sold out).
Forward recovery (retry)
For transient errors, a retry is enough, meaning a new attempt at the same step.
The name has a catch: for Garcia-Molina and Salem, forward recovery means
a restart from a save-point without compensations, which is something else. The book uses the term
in its present-day, narrower sense. Symfony Messenger offers a built-in retry strategy
with exponential backoff, configured in
section 14.07. The worker automatically retries failed
messages according to the max_retries, delay, and multiplier settings.
Backward recovery (compensation)
For permanent errors (failures with a domain cause), compensation takes over:
returning the system to a consistent state through compensating actions in
the reverse order of the completed steps. Compensation is
semantic, not technical: instead of DELETE FROM payments, a new
domain command, RefundCustomer, is sent, which creates a new transaction (a refund). Every compensating
action is a full-fledged domain operation with its own rules and events.
When compensation fails
The onStockReservationFailed method from section 14.05 dispatches
RefundCustomer and moves the saga to the Compensating state. The saga stays there, because
the refund is an asynchronous command: it may move to the terminal Failed only after
the RefundSucceeded confirmation arrives. Moving to Failed right after the dispatch
would close the saga before the refund happened; if the refund failed, nobody would go looking for
the customer's money. The state “compensation sent, waiting for confirmation”
is referred to as compensation pending.
Richardson (Microservices Patterns, 2018, ch. 4) divides saga steps into three groups:
- Compensatable transactions – steps before the pivot; each has a defined
compensation (
ChargeCustomer↔RefundCustomer). - Pivot transaction – the decision point. Once it commits, the saga no longer backs out and runs forward to the end. In this process, the pivot is the stock reservation.
- Retriable transactions – steps after the pivot (
CreateShipment,ShipOrder). They have no compensation, must not fail for domain reasons, and are retried until they succeed.
The classification describes the failure of a step inside the saga. An order cancellation from outside is a different
scenario, which is why CancelShipment appears in the table of compensations in section 14.02.
If the cancellation arrives before Shipping announces the shipment, the saga is already in the
Compensating state, and onShipmentCreated() cancels the resulting shipment. Once the shipment is created, the saga
ends in Completed, and cancelling an order that has already shipped is a return of goods (a withdrawal from the contract), not a compensation.
Compensations themselves belong in the third category. RefundCustomer has no
domain reason to fail – money the system has taken, it must be able to give back. A failure
is always technical: an unavailable payment gateway, a timeout, a network error. The strategy
follows from that: a retry with exponential backoff (retry_strategy from
section 14.07); once the attempts are exhausted, the message ends up in the
failure transport, the system sends an alert, and the order goes to the manual intervention
queue. A saga hanging in Compensating is also caught by the stuck saga detection from
section 14.11.
More on the Dead Letter Queue, retry strategies, and error handling in Messenger is in the Error handling and the dead letter queue section of the CQRS chapter.
14.10 Parallel steps#
So far, the steps have run serially, one after another. Some of them, however, do not depend on each other and can run at the same time: after a successful payment, the system can both reserve the goods in stock and generate an invoice. The result of one operation does not affect the other, so parallel processing shortens the total duration of the saga.
The saga sends both commands at once and moves to the AwaitingStockAndInvoice state.
In its context, it keeps two flags (stockReserved and invoiceCreated). Only when
both are set does it continue with the next step, creating the shipment. This pattern is called
a synchronization barrier. The AwaitingStockAndInvoice state
is not yet in the OrderSagaStatus enum from section 14.05; the parallel variant
adds it to the enum.
14.11 Monitoring and observability#
Without monitoring, a message gets lost in the queue, the saga's state freezes, and nobody notices anything until a customer complains. Operations therefore needs to know which saga instances are running right now, which have got stuck, and which have failed. Two tools provide this visibility: correlation IDs for tracing and stuck saga detection.
Correlation ID
Every message in one saga carries the same business correlation key, here
orderId. It makes it possible to filter all messages for a specific order in the log
and follow the whole course of the process from start to finish.
A technical correlation ID has a different scope. It is created
with a request or a triggering message and passes into the messages derived from them.
The orderId key, by contrast, ties together the whole saga instance, including scheduled
timeouts and manual interventions.
Technically, correlation is handled with a custom stamp (e.g., CorrelationIdStamp)
that the saga attaches to the envelope on dispatch; the logging middleware reads it
from the stamp instead of relying on a specific field of the message. The envelope thus carries
the correlation even for messages that have no orderId.
Detecting stuck sagas
Even with the best design, a message occasionally gets lost, a worker crashes, or an external service stops responding. That is why a cron/scheduled command is needed that regularly checks whether any saga has stayed in an intermediate state for too long:
Details on implementing middleware in Symfony Messenger are in the Middleware in CQRS section of the CQRS chapter.
14.12 Testing sagas#
A bug in the transition logic or in the compensations shows up only in production: a captured payment without delivered goods, duplicated shipments, and the like. Saga tests center on unit tests of the state machine; integration tests with Doctrine and testing asynchronous flows through Messenger are covered in the Testing DDD chapter.
Unit tests of the state machine
The most important level: a unit test verifies the Process Manager itself, without infrastructure. The message bus is replaced by a spy that records the dispatched commands, and the database by an in-memory repository:
More patterns for testing domain logic, aggregates, and event handlers are in the Testing DDD chapter.
Frequently asked questions
What is the difference between a saga and a Process Manager?
In this book, a saga is the general term for a long-running transaction across several services, split into a series of local transactions linked by compensations. A Process Manager is an orchestrating component with its own state that drives such a saga: it sends commands and reacts to incoming events. The two axes (saga/Process Manager vs. choreography/orchestration) are orthogonal – a saga can be choreographed or orchestrated, while a Process Manager is always an orchestrator. This is, however, one of three conventions that coexist in the literature, so with an outside source it pays to check which one it uses. Analysis in the Which convention the book uses section.
Choreography or orchestration – when to choose which?
Choreography, where services react to events published by others, suits short processes with a known linear sequence of steps, where the coupling between services is loose and global state is not critical. Orchestration through a Process Manager fits better where the sequence is not known in advance, where the process branches, or where time limits and a central overview of the run state are needed. The commonly cited “two to three steps” threshold is a heuristic, not a rule. Decision criteria in the Limits of choreography section.
How do I implement compensating transactions in Symfony?
A compensation is a separate operation or command handler that semantically reverses the effect of a previously completed step – for example, RefundCustomer as the counterpart of ChargeCustomer. In a saga built on Messenger, compensation is triggered when an incoming event signals the failure of one of the later steps. Compensating commands must be idempotent and tolerate the situation where the compensated step never happened. Not every operation can be technically reversed, so sometimes the compensation takes a different form. A practical example in the Compensation strategies in practice section.
How do I make a saga idempotent when events are delivered more than once?
Messenger can deliver the same message more than once, whether a worker fails or the message is repackaged onto a retry queue. The handler therefore has to ignore repeated processing safely. There are two standard solutions: the event identifier (not the transport ID of the message) stored among the processed IDs, or a saga state machine that checks at every step whether it is already in the “completed” state. Both techniques prevent duplicate publishing of commands as well as duplicate compensations. A detailed analysis in the Pattern: idempotent state transitions + UNIQUE constraint section.
Should a saga be served through the Command Bus or the Event Bus?
Both, with clearly divided roles. Events on the Event Bus trigger the saga's reactions – they report that something happened, and the saga follows up on them. Commands on the Command Bus are issued by the saga itself to drive the next steps. The typical loop looks like this: incoming event → Process Manager → outgoing command → handler → new event. The roles are not interchangeable: an event commands nothing, and a command announces nothing. See the Implementation in Symfony Messenger section.