Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 33 ยท Workflows

Compensation, Rollback and Long-Running Workflows

How Medusa workflows undo work with compensation functions, why steps must be idempotent, how async steps and retries work, and which workflow engine to use.

A database transaction can undo changes inside one database. A commerce operation cannot rely on that alone: it may create a product in one module, charge a card at an outside provider and send a request to a warehouse system. None of those share a transaction. Medusa workflows use the saga pattern instead: each step can supply a compensation function that reverses its own effect, and when a later step fails the engine runs the compensations of the completed steps in reverse order.

This lesson explains compensation, how to design steps so retries are safe, how async steps let a workflow wait for something slow, and what the workflow engine modules do. Real Medusa code is read-only; the stand-ins are a saga runner and an async step with retries.

How rollback works

Think of each step as a pair: do something, and know how to take it back. If step 3 fails, the engine does not roll back step 3 (it never finished); it compensates step 2, then step 1.

flowchart LR
    A["Step 1<br/>done"] --> B["Step 2<br/>done"] --> C["Step 3<br/>fails"]
    C -. "compensate" .-> B2["Undo step 2"]
    B2 -. "compensate" .-> A2["Undo step 1"]

Compensation runs backwards, newest completed step first.

In real Medusa the compensation function is the third argument to createStep. It receives the compensation input you passed as the second argument of StepResponse (Workflows and Steps). This is read-only, real code:

TypeScript
import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
import { Modules } from "@medusajs/framework/utils"

export const createCouponStep = createStep(
  "create-coupon",
  async (input: { code: string }, { container }) => {
    const promotion = container.resolve(Modules.PROMOTION)
    const [created] = await promotion.createPromotions([
      {
        code: input.code,
        type: "standard",
        application_method: {
          type: "percentage",
          target_type: "order",
          value: 10,
          currency_code: "usd",
        },
      },
    ])
    return new StepResponse(created, created.id)
  },
  async (createdId, { container }) => {
    if (!createdId) {
      return
    }
    const promotion = container.resolve(Modules.PROMOTION)
    await promotion.deletePromotions(createdId)
  }
)

The compensation receives createdId, not the whole object. If the step failed before it could return a StepResponse, there is nothing to compensate, which is why you guard against a missing value.

What compensation can and cannot do

  • It can delete rows you created, restore values you changed (store the old value as compensation input), or cancel a pending reservation.
  • It cannot truly un-send an email or un-charge a card the customer already saw. For those, design a forward action: refund instead of "uncharge", or send a correction. Place irreversible steps last in the workflow so that everything before them can still be undone.
  • Compensation can itself fail. Log and monitor it; an undo that silently fails leaves orphaned data.

Design steps to be idempotent

Retries, timeouts and crashes mean a step can run more than once for the same logical work. A step is idempotent when running it twice has the same effect as running it once. The general idea, with payment examples, is in Idempotency. In a workflow step that usually means:

  • Use a natural key (an order id, an external reference) and "create if missing" instead of a blind insert.
  • Pass an idempotency key to outside APIs, such as a payment provider.
  • Compare before changing: only update a field whose current value differs.
  • Make compensation safe to run on something already gone: deleting a missing row should not throw.

Failure behavior at the call site

When a step throws, the engine runs compensations and then the run promise rejects with the original error. For a more controlled flow:

TypeScript
const { result, errors } = await createCouponWorkflow(req.scope).run({
  input: { code: "SPRING10" },
  throwOnError: false,
})

if (errors.length) {
  // errors[0].error is the original exception
  return res.status(409).json({ message: "Could not create the coupon" })
}

Inside a step you may also throw a MedusaError with a type such as NOT_FOUND or INVALID_DATA, so API routes return a meaningful status code (Custom API Routes and Middleware).

Retries, timeouts and async steps

Steps can be configured when they are created or with .config() on a step you reuse. Common options include maxRetries (retry a failing step before giving up), a retry interval, a timeout, and async: true. The exact option names are read-only reference material here, so check the version you install; the concepts are stable:

  • Retries help with transient failures such as a flaky network. They are safe only for idempotent steps.
  • Timeouts stop a step that never finishes.
  • Async steps do not complete when their function returns. The workflow pauses and waits until something outside reports success or failure. That makes long-running workflows possible: "wait for the supplier to confirm" or "wait for the customer to verify an email" can span minutes or days.

An outside actor resolves an async step through the Workflow Engine module with setStepSuccess or setStepFailure, passing the workflow id, transaction id and step id that identify the paused step. This is real code and read-only:

TypeScript
import { Modules, TransactionHandlerType } from "@medusajs/framework/utils"
import { StepResponse } from "@medusajs/framework/workflows-sdk"

const engine = container.resolve(Modules.WORKFLOW_ENGINE)

await engine.setStepSuccess({
  idempotencyKey: {
    action: TransactionHandlerType.INVOKE,
    transactionId,
    stepId: "wait-for-supplier",
    workflowId: "reorder-stock",
  },
  stepResponse: new StepResponse({ confirmed: true }),
})

setStepFailure works the same way and triggers compensation of the earlier steps. Start such a workflow with a known transactionId so you can find it later, for example the id of the purchase order.

Workflow engine modules

Which engine runs your workflows is configured in medusa-config.ts:

Engine Where state lives Use it for
In-memory (default) The server process Local development, tests, short workflows
Redis Redis Production, multiple instances, async steps that must survive restarts

With the in-memory engine, a paused async workflow disappears if the process restarts. Anything that outlives a request should run on the Redis engine, and you should have Redis anyway for the event bus and cache (Security and Performance).

Stand-in 1: a saga runner

This stand-in implements the contract: run steps in order, remember what each returned as compensation input, and on failure run compensations in reverse. It also shows an idempotent compensation that tolerates a missing row.

JS A saga runner that rolls back completed steps

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second run changed stock and created a coupon, then failed at the third step. The compensations restored stock to 7 and removed the SUMMER coupon, in reverse order.

Stand-in 2: retries and an async step

This stand-in retries a flaky step and then pauses a workflow on an async step until an outside caller reports success. The retry and the outside call are deterministic, so the output is stable.

JS Retries, then waiting for setStepSuccess

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In the real engine the paused state is stored (in memory or Redis), not held by a promise. That is why a Redis-backed engine can survive a restart while this stand-in cannot.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A workflow has steps A, B and C, and C throws. What does the engine do?

    Step C never completed, so it has nothing to undo. Completed steps are compensated in reverse order, newest first.
  2. 2. Why should steps be idempotent?

    Retries and restarts mean at-least-once execution. Idempotent steps make repeated runs safe.
  3. 3. What is an async step used for?

    An async step does not finish when its function returns. An outside caller resolves it with setStepSuccess or setStepFailure, which allows long waits.
  4. 4. Which engine should you use when async workflows must survive a server restart?

    The in-memory engine keeps state in the process. The Redis engine stores it outside the process, so paused workflows continue after a restart.
  5. 5. Which action is best placed last in a workflow because it cannot be undone?

    An email cannot be unsent. Put irreversible steps last so every earlier step can still be compensated if something fails.

Summary

  • Compensation functions undo completed steps in reverse order when a later step fails; they receive the compensation input from StepResponse.
  • Irreversible effects need forward actions (refunds, corrections) and belong at the end of a workflow.
  • Make steps idempotent and compensations safe to repeat, because retries and restarts run code more than once.
  • Retries, timeouts and async steps are step configuration; setStepSuccess and setStepFailure resume a paused workflow.
  • Use the Redis workflow engine in production so state survives restarts and multiple instances.
  • The stand-ins model the saga mechanics, not Medusa's implementation.

Next: Hooks and Built-in Workflows