Saga pattern
medium 30 minA saga is a chain of local transactions, one per service, with an undo step for each.
A saga orchestrator that survives a crash
Read it, run it, change a line and run it again.
Loading editor…
The log is a list here. In production it is a database table, and the service calls cross the network. A step that started is undone even if it was refused: the undo is harmless, and it also covers a lost reply.
The same in TypeScript
interface Step<C> { name: string; execute(c: C): Promise<void>; compensate(c: C): Promise<void> }interface SagaLog { write(saga: string, event: string, step?: string): Promise<void> }// Steps are shared; the list of started steps belongs to one run.class Orchestrator<C extends { sagaId: string }> { private steps: Step<C>[] = []; private log: SagaLog; constructor(log: SagaLog) { this.log = log; } add(s: Step<C>): this { this.steps.push(s); return this; } async run(c: C): Promise<{ ok: boolean; stuck: string[] }> { const started: Step<C>[] = []; for (const s of this.steps) { await this.log.write(c.sagaId, "STARTED", s.name); started.push(s); // before the call: it may time out try { await s.execute(c); } catch { return { ok: false, stuck: await this.undo(c, started) }; } await this.log.write(c.sagaId, "DONE", s.name); } await this.log.write(c.sagaId, "COMPLETED"); return { ok: true, stuck: [] }; } private async undo(c: C, started: Step<C>[]): Promise<string[]> { await this.log.write(c.sagaId, "COMPENSATING"); const stuck: string[] = []; for (const s of [...started].reverse()) { try { await s.compensate(c); await this.log.write(c.sagaId, "UNDONE", s.name); } catch { stuck.push(s.name); // retry later, then alert a person await this.log.write(c.sagaId, "STUCK", s.name); break; // never undo an earlier step first } } return stuck; }}const step = (name: string, fail = false): Step<{ sagaId: string }> => ({ name, async execute() { if (fail) throw new Error(name); console.log("do", name); }, async compensate() { console.log("undo", name); },});const saga = new Orchestrator<{ sagaId: string }>({ async write() {} }) .add(step("CreateOrder")).add(step("ReserveInventory")).add(step("ProcessPayment", true)).add(step("ConfirmOrder"));saga.run({ sagaId: "s1" }).then(console.log);The same in Java
import java.util.*;interface SagaStep<C> { String name(); void execute(C context) throws Exception; void compensate(C context) throws Exception;}interface SagaLog { void write(String saga, String event, String step); }class SagaOrchestrator<C> { private final List<SagaStep<C>> steps; private final SagaLog log; SagaOrchestrator(List<SagaStep<C>> steps, SagaLog log) { this.steps = List.copyOf(steps); this.log = log; } /** One call per saga. Nothing about a run is kept in fields. */ boolean run(String sagaId, C context) { Deque<SagaStep<C>> started = new ArrayDeque<>(); for (SagaStep<C> step : steps) { log.write(sagaId, "STARTED", step.name()); started.push(step); try { step.execute(context); log.write(sagaId, "DONE", step.name()); } catch (Exception e) { compensate(sagaId, context, started); return false; } } log.write(sagaId, "COMPLETED", null); return true; } private void compensate(String sagaId, C context, Deque<SagaStep<C>> started) { log.write(sagaId, "COMPENSATING", null); while (!started.isEmpty()) { SagaStep<C> step = started.pop(); // newest first try { step.compensate(context); log.write(sagaId, "UNDONE", step.name()); } catch (Exception e) { log.write(sagaId, "STUCK", step.name()); // retry later, alert return; } } log.write(sagaId, "COMPENSATED", null); }}