Saga Orchestrator With Compensation

Coordinate distributed transactions with a saga pattern and compensation functions for rollback on failure.

TypescriptResilience

Code

typescriptsnippet
1 line
interface SagaStep<T>{execute:()=>Promise<T>;compensate:(result:T)=>Promise<void>;}export class SagaOrchestrator{private steps:SagaStep<any>[]=[];private results:any[]=[];add<T>(step:SagaStep<T>):this{this.steps.push(step);return this;}async run():Promise<any[]>{for(let i=0;i<this.steps.length;i++){try{const result=await this.steps[i].execute();this.results.push(result);}catch(e){await this.compensate(i);throw e;}}return this.results;}private async compensate(failedIndex:number):Promise<void>{for(let i=failedIndex-1;i>=0;i--){try{await this.steps[i].compensate(this.results[i]);}catch(e){console.error('compensation failed for step',i,e);}}}}

How it works

Saga Orchestrator With Compensation is built around the class SagaOrchestrator.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

Emits through the .error level methods with structured payloads, so downstream transports can route by level and field.

Applying it

Output lines are prefixed (compensation failed for step), making each step’s effect easy to spot.

The surface worth importing is SagaOrchestrator; the helpers around it are private to the snippet.

Interactive Tools for This Topic

FAQ

What has to be installed first?
Nothing — the runtime itself provides everything the code touches.