Applicability
When to Use
✓When a business process spans multiple services
✓When you need ACID-like guarantees across systems
✓When failure in one step should undo previous steps
Overview
How It Works
The Saga pattern manages distributed transactions by breaking them into a series of local transactions, each handled by a different MCP server. If any step fails, compensating transactions undo the previous steps. The orchestrating agent manages the saga lifecycle.
For example, creating an order involves: (1) reserve inventory in Shopify, (2) charge payment in Stripe, (3) create shipping label. If charging fails, the agent runs the compensating action to release the reserved inventory. Each step and its compensation are defined as a pair.
Implementation
Code Example
typescript
class Saga {
steps = [];
completedSteps = [];
addStep(execute, compensate) {
this.steps.push({ execute, compensate });
}
async run() {
for (const step of this.steps) {
try {
const result = await step.execute();
this.completedSteps.push({ ...step, result });
} catch (error) {
await this.rollback();
throw error;
}
}
}
async rollback() {
for (const step of this.completedSteps.reverse()) {
await step.compensate(step.result);
}
}
}
// Usage
const orderSaga = new Saga();
orderSaga.addStep(
() => shopify.reserveInventory({ productId, quantity }),
(reservation) => shopify.releaseInventory({ reservationId: reservation.id })
);
orderSaga.addStep(
() => stripe.createCharge({ amount, customer }),
(charge) => stripe.refund({ chargeId: charge.id })
);
await orderSaga.run();Quick Info
Categoryorchestration
ComplexityHard