Explain the Saga Pattern and its two coordination styles.
Topic: microservices, Data Management. Level: Hard.
Answer
A Saga models a distributed transaction as a sequence of **local transactions**, each in one service. After each local commit the service publishes an event/command triggering the next step. If a step fails, the Saga runs **compensating transactions** to undo prior steps (semantic rollback — you can't roll back a committed local tx, so you issue a counter-action like "refund"). Two styles: **choreography** (services react to events) and **orchestration** (a central Saga orchestrator drives steps and compensations). Sagas provide atomicity-of-outcome and eventual consistency, not isolation, so guard against anomalies with idempotency and semantic locks.
```java
// Orchestrated Saga with compensation
class CreateOrderSaga {
void execute(Order o) {
try {
payment.charge(o); // step 1
try {
inventory.reserve(o); // step 2
shipping.schedule(o); // step 3
} catch (Exception e) {
payment.refund(o); // compensate step 1
inventory.release(o); // compensate step 2
throw e;
}
} catch (Exception e) {
order.markFailed(o);
}
}
}
```