Saga Pattern
A pattern for managing distributed transactions
A pattern for managing distributed transactions
The Saga pattern manages distributed transactions that span multiple services in a microservices environment. Traditional 2PC (Two-Phase Commit) has performance and availability problems in distributed environments, so Saga guarantees Eventual Consistency through Compensating Transactions.
A Saga consists of a series of local transactions. Each local transaction updates its own database and publishes an event/message to trigger the next transaction. If a failure occurs midway, the compensating transactions of the previous transactions are executed in reverse order to restore the state.
There are two implementation approaches. Choreography: each service publishes/subscribes to events and cooperates autonomously. There is no central control point, so coupling is loose, but it is hard to understand the flow. Orchestration: a central orchestrator directs each step. The flow is clear, but the orchestrator can become a single point of failure.
Example - Order Saga: 1) Create order β 2) Deduct inventory β 3) Process payment β 4) Reserve shipping. If payment fails at step 3: compensate step 2 (restore inventory) β compensate step 1 (cancel order). Each service must know its own compensation logic.
// Saga Orchestration ν¨ν΄ ꡬν (TypeScript)
interface SagaStep<T> {
name: string;
execute: (context: T) => Promise<T>;
compensate: (context: T) => Promise<T>;
}
class SagaOrchestrator<T> {
private steps: SagaStep<T>[] = [];
private executedSteps: SagaStep<T>[] = [];
addStep(step: SagaStep<T>): this {
this.steps.push(step);
return this;
}
async execute(initialContext: T): Promise<T> {
let context = initialContext;
for (const step of this.steps) {
try {
console.log(`Executing: ${step.name}`);
context = await step.execute(context);
this.executedSteps.push(step);
} catch (error) {
console.error(`Failed at: ${step.name}`, error);
await this.rollback(context);
throw new SagaError(step.name, error);
}
}
return context;
}
private async rollback(context: T): Promise<void> {
// μμμΌλ‘ 보μ νΈλμμ
μ€ν
for (const step of [...this.executedSteps].reverse()) {
try {
console.log(`Compensating: ${step.name}`);
await step.compensate(context);
} catch (error) {
console.error(`Compensation failed: ${step.name}`, error);
// 보μ μ€ν¨ μ μλ¦Ό/μλ κ°μ
νμ
}
}
}
}
// μ£Όλ¬Έ Saga μ μ
interface OrderContext {
orderId: string;
customerId: string;
items: Array<{ productId: string; quantity: number }>;
totalAmount: number;
inventoryReserved?: boolean;
paymentId?: string;
shippingId?: string;
}
const orderSaga = new SagaOrchestrator<OrderContext>()
.addStep({
name: 'CreateOrder',
execute: async (ctx) => {
const order = await orderService.create({
customerId: ctx.customerId,
items: ctx.items,
status: 'PENDING'
});
return { ...ctx, orderId: order.id };
},
compensate: async (ctx) => {
await orderService.cancel(ctx.orderId);
return ctx;
}
})
.addStep({
name: 'ReserveInventory',
execute: async (ctx) => {
await inventoryService.reserve(ctx.orderId, ctx.items);
return { ...ctx, inventoryReserved: true };
},
compensate: async (ctx) => {
if (ctx.inventoryReserved) {
await inventoryService.release(ctx.orderId);
}
return ctx;
}
})
.addStep({
name: 'ProcessPayment',
execute: async (ctx) => {
const payment = await paymentService.charge({
orderId: ctx.orderId,
customerId: ctx.customerId,
amount: ctx.totalAmount
});
return { ...ctx, paymentId: payment.id };
},
compensate: async (ctx) => {
if (ctx.paymentId) {
await paymentService.refund(ctx.paymentId);
}
return ctx;
}
})
.addStep({
name: 'ScheduleShipping',
execute: async (ctx) => {
const shipping = await shippingService.schedule(ctx.orderId);
await orderService.updateStatus(ctx.orderId, 'CONFIRMED');
return { ...ctx, shippingId: shipping.id };
},
compensate: async (ctx) => {
if (ctx.shippingId) {
await shippingService.cancel(ctx.shippingId);
}
return ctx;
}
});
// μ¬μ©
async function placeOrder(orderData: Omit<OrderContext, 'orderId'>) {
try {
const result = await orderSaga.execute(orderData as OrderContext);
return { success: true, orderId: result.orderId };
} catch (error) {
if (error instanceof SagaError) {
return { success: false, failedAt: error.step, error: error.message };
}
throw error;
}
}
In microservice design:
"Order processing spans three services: inventory, payment, and shipping. 2PC is too slow in a distributed environment and carries the risk of failure propagation, so we implement it with the Saga pattern. Each service has its own DB, and on failure we roll back with compensating transactions."
In a technical interview:
"When should we use Choreography vs Orchestration?" - "If the number of services is small and the flow is simple, Choreography is a good fit. It flows naturally through events between services. If there is complex business logic or many conditional branches, Orchestration is easier to manage."
In incident response:
"What if a compensating transaction also fails?" - "You need a retry mechanism and a Dead Letter Queue. If it still fails after a set number of retries, send it to the DLQ, notify the operations team, and handle it manually. Guaranteeing idempotency is key."
Take a mock interview on this topic β WIA SOOM AI Interview Β· Start for free