---
title: "Workflow DSL"
description: "Define workflows at runtime as data, usually JSON, store them, and run every one with a single interpreter Flow."
canonical_url: "https://docs.superdurable.io/design-patterns/workflow-dsl/"
source: "docs/content/design-patterns/workflow-dsl.mdx"
locale: "en"
language: "python"
---

> Index of every page for AI agents: https://docs.superdurable.io/llms.txt

# Workflow DSL

Code on this page is in Python. Other languages: [Go](https://docs.superdurable.io/design-patterns/workflow-dsl.go.md) · [Java](https://docs.superdurable.io/design-patterns/workflow-dsl.java.md) · [TypeScript](https://docs.superdurable.io/design-patterns/workflow-dsl.typescript.md) · [Rust](https://docs.superdurable.io/design-patterns/workflow-dsl.rust.md)

Define workflows at runtime as data, usually JSON, store them, and run every one with a single interpreter Flow.
Use this pattern when every workflow is built from the same set of actions and external conditions.

Operators, customers, partners, or another system can define a workflow. The definition follows a serializable schema and lives in your application's versioned definition store. Users can edit, copy, import, and export these documents. Adding a workflow means adding a JSON document. It requires no code change or release.

For example, a seller can define one purchase workflow that charges a buyer after confirmation and another that sends a sample first. Both definitions use the same interpreter.

**Flow graph: DealDSLFlow**

**Steps**

1. `InitializeDeal` (start Step): Load the deal definition and enter its initial state. Next: `WaitForDealCondition`. Writes `DealBuyerID`, `DealDefinition`, `DealItemID`, `DealProcessID`, `DealStateData`.
2. `EvaluateDealTransition`: Wait for the transition condition, then enter the next state or complete. Next: the Flow completes, or `WaitForDealCondition`. Reads `DealDefinition`, `DealStateData`; writes `DealPendingCondition`.
3. `ExecuteDealAction`: Run one action of the current state, then the next action or the transition. Next: `ExecuteDealAction` again, or `EvaluateDealTransition`. Reads `DealDefinition`.
4. `WaitForDealCondition`: Wait for the state's precondition, then run its actions or evaluate its transition. Next: `ExecuteDealAction`, or `EvaluateDealTransition`. Reads `DealDefinition`; writes `DealCurrentState`, `DealPendingCondition`.

**RPCs**

- `send_condition_message`: Publishes to `DealConditionMessages`.

Example: [examples/python/dex_examples/products/deal_dsl/deal_dsl_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/deal_dsl/deal_dsl_flow.py)

<a id="how-it-works"></a>

## How it works

1. **Save and validate the definition.** At the application boundary, check the definition on save and before starting a Flow. Check that every referenced state, action, and condition name exists and that each condition name belongs to one wait. Reject an invalid definition before it can start a Flow.
2. **Start the purchase.** The start Step saves the whole definition in an Attribute and initializes a shared state data map. The run advances one position at a time. After startup, each Step input carries only the position, such as the state name and action index.
3. **Wait for the buyer.** Before entering a state, wait for its condition if it has one. The RPC checks the condition name against the definition and publishes to one `ChannelMap` keyed by condition name. The persistence schema declares the map in code, and each definition supplies its keys at runtime. Each wait takes one message. The interpreter merges that message into the shared state data map.
4. **Run one action.** For a charge or a delivery, run the registered handler or script in one Step's `Execute`. Treat a script like any external call and give it retries and an idempotency key. Give it a timeout too when it can block without observing cancellation. Merge the result into the shared map. Each action has its own checkpoint, so retrying it leaves earlier completed actions intact.
5. **Choose what happens next.** The transition Step can wait for another condition and merges its message into the same map. It reads the map to choose the next state. The interpreter uses `GoTo` to advance through these four Step types until the purchase reaches a state with no next transition.
6. **Record progress.** The definition decides what progress means, such as the current state, current step, or a custom stage. Write it to Attributes so the Client can read it. Use [Attribute Sync](https://docs.superdurable.io/design-patterns/data-storage/entity-flow-attribute-sync.md) when progress must be searchable. The Flow graph shows the interpreter Steps. The Attributes show where a particular purchase is in its workflow.

<a id="example"></a>

## Example

The wait Step takes one message from the `ChannelMap` using the condition name as the key. It merges the message into the shared state data. The action Step runs one action, then routes to the next action or the transition. Each tab links to the full runnable example.

**Python**

```python
class WaitForDealCondition(Step[StateStepInput]):
    def __init__(self, flow: "DealDSLFlow") -> None:
        self.flow = flow

    def wait_for(self, context: Context, input: StateStepInput) -> Wait:
        state = self.flow.definition.get(context).state(input.state_name)
        if state.pre_condition is None:
            return Wait.skip_immediately()
        self.flow.pending_condition.set(context, state.pre_condition.name)
        return Wait.until(self.flow.condition_messages.for_one(state.pre_condition.name))

    def execute(self, context: Context, input: StateStepInput) -> StepDecision:
        state = self.flow.definition.get(context).state(input.state_name)
        if state.pre_condition is not None:
            self.flow.merge_condition(context, state.pre_condition.name)
            self.flow.pending_condition.delete(context)
        self.flow.current_state.set(context, state.name)
        if state.actions:
            return go_to(ExecuteDealAction, ActionStepInput(state.name, 0))
        return go_to(EvaluateDealTransition, input)


# dex:group group-id:actions group-label:"Actions"
# dex:explanation text:"Run one action of the current state, then the next action or the transition."
class ExecuteDealAction(Step[ActionStepInput]):
    def __init__(self, flow: "DealDSLFlow") -> None:
        self.flow = flow

    def execute(self, context: Context, input: ActionStepInput) -> StepDecision:
        state = self.flow.definition.get(context).state(input.state_name)
        if input.action_index < 0 or input.action_index >= len(state.actions):
            raise ValueError(f"invalid action index {input.action_index}")
        # The execution ID stays stable on retries and changes when the same action runs again.
        idempotency_key = f"{context.flow_id}/{context.step_execution_id}"
        self.flow.execute_action(
            context, state.actions[input.action_index], idempotency_key
        )
        next_index = input.action_index + 1
        if next_index < len(state.actions):
            return go_to(ExecuteDealAction, ActionStepInput(state.name, next_index))
        return go_to(EvaluateDealTransition, StateStepInput(state.name))
```

Example: [examples/python/dex_examples/products/deal_dsl/deal_dsl_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/deal_dsl/deal_dsl_flow.py)

<a id="definition-versions"></a>

## Definition versions

| Approach                   | What a run uses                                                                                                                            | What edits change                                                                                                                                                                |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Snapshot at start          | The start Step stores the full definition in an Attribute. Later Steps read that copy. This is what Deal DSL does.                         | New versions apply to newly started Flows. Running Flows keep their original definition.                                                                                         |
| Read the latest definition | Read from the store in `Execute` on each state entry or transition evaluation. Treat the read as an external call that can fail and retry. | Edits reach running Flows. A state can be renamed or removed, and an awaited condition can disappear. Define compatibility rules or migrate the saved position between versions. |

<a id="parallel-branches"></a>

## Parallel branches

If a state can open several branches, start them with `GoToMany` and keep each branch's position in its own Step input. Bring them together at a Join. Use an Attribute lock for concurrent writes to shared state, or let each branch write its own data and merge it after the Join. See [Parallel Steps](https://docs.superdurable.io/design-patterns/parallel.md) and [Critical Section](https://docs.superdurable.io/design-patterns/parallel/critical-section.md).

<a id="next"></a>

## Next

- [Parallel Steps](https://docs.superdurable.io/design-patterns/parallel.md)
- [Deal DSL](https://docs.superdurable.io/use-cases/deal-dsl.md)
