Architecture Expert
Saga Pattern — distributed transakce without 2PC¶
SagaTransactionsMicroservices 3 min read
Implementace Saga patternu pro konzistenci dat napříč mikroservisami. Choreografie vs orchestrace.
Problém distribuovaných transakcí¶
V monolitu is enough DB transakce. V mikroservisách má every service own DB — klasické transakce nefungují. Saga je sekvence lokálních transakcí s kompenzačními akcemi.
Choreografie vs Orchestrace¶
Choreografie: Služby komunikují via events, no centrální koordinátor.
Orchestrace: Centrální Saga orchestrátor řídí sekvenci kroků.
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¶
- Choreografie — simpler sagy (2-4 kroky)
- Orchestrace — more complex sagy (5+ kroků)
- Nástroje: Temporal, Camunda, AWS Step Functions
Summary¶
Saga pattern requires pečlivý návrh kompenzačních akcí a idempotentních operací. Pro komplexní workflows we recommend orchestraci s Temporal.
Need Help with Implementation?¶
Our team has experience designing and implementing modern architectures. We’re happy to help.