Course contentsShow
← AI Engineering
Lesson 1795 of 1,88643. Workflow Orchestration and State MachinesFree lesson

Compensation and Rollback Patterns

Implement compensating transactions to undo partial workflow steps when errors occur mid-process.

Compensation and Rollback Patterns

What you'll learn: How to implement compensating transactions that intelligently undo partial workflow steps when errors occur mid-process.

The Problem of Partial Failures

Imagine a multi-step AI workflow: (1) extract text from a document, (2) generate a summary with an LLM, (3) store results in a database, (4) send a notification. What happens if step 3 fails after steps 1 and 2 succeeded? You've consumed API credits and generated outputs, but your workflow is incomplete.

Unlike traditional database transactions that can simply rollback, AI workflows involve irreversible actions: API calls were made, tokens were consumed, external services were called. You can't "undo" an LLM generation.

Compensation: Undoing What Can't Be Rolled Back

Compensation patterns define inverse operations for each step that approximate an undo:

  • If you created a database record → delete it
  • If you sent a preliminary notification → send a cancellation notice
  • If you reserved a resource → release it
  • If you generated an artifact → mark it as invalid or delete it

The key insight: you don't reverse the computation itself (that's impossible), but you clean up its side effects.

Implementation Strategy

For each workflow step, define both a forward action and a compensation action. Track completed steps. When an error occurs, execute compensation actions in reverse order (last successful step first), like unwinding a stack.

Think of it like a cooking recipe: if you burn the dish at step 5, you can't un-chop the vegetables, but you can throw away what you've made, clean the pan, and start fresh.

Key Takeaway: Compensation patterns handle partial failures in AI workflows by defining cleanup operations that reverse side effects of completed steps, executed in reverse order when downstream errors occur.