Architecture Expert
Saga Pattern — Distributed Transactions Without 2PC¶
SagaTransactionsMicroservices 3 min read
Saga pattern implementation for data consistency across microservices. Choreography vs orchestration.
The Problem of Distributed Transactions¶
In a monolith, a DB transaction is enough. In microservices, each service has its own DB — traditional transactions don’t work. A Saga is a sequence of local transactions with compensating actions.
Choreography vs Orchestration¶
Choreography: Services communicate via events, no central coordinator.
Orchestration: A central Saga orchestrator controls the sequence of steps.
class CreateOrderSaga {
steps = [
{ action: 'order.create', compensate: 'order.cancel' },
{ action: 'payment.process', compensate: 'payment.refund' },
{ action: 'inventory.reserve', compensate: 'inventory.release' },
{ action: 'order.confirm', compensate: null }
];
async execute(data) {
const completed = [];
for (const step of this.steps) {
try {
await this.invoke(step.action, data);
completed.push(step);
} catch (error) {
for (const s of completed.reverse())
if (s.compensate) await this.invoke(s.compensate, data);
throw error;
}
}
}
}
When to Use Which¶
- Choreography — simpler sagas (2-4 steps)
- Orchestration — more complex sagas (5+ steps)
- Tools: Temporal, Camunda, AWS Step Functions
Summary¶
The Saga pattern requires careful design of compensating actions and idempotent operations. For complex workflows, we recommend orchestration with Temporal.
Need Help with Implementation?¶
Our team has experience designing and implementing modern architectures. We’re happy to help.