---
title: "Order Processing"
description: "Charge a buyer, wait for the seller to approve the shipment, then ship. If shipping keeps failing, refund the buyer."
canonical_url: "https://docs.superdurable.io/examples/order-processing/"
source: "docs/content/use-cases/order-processing.mdx"
locale: "en"
language: "python"
---

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

# Order Processing

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

Charge a buyer, wait for the seller to approve the shipment, then ship. If shipping keeps failing, refund the buyer.

**SDKs:** Python · Go · TypeScript · Java · Rust

**Shows:** [Reminder](https://docs.superdurable.io/design-patterns/durable-timer/reminder.md), [Execute Failure Recovery](https://docs.superdurable.io/design-patterns/failure-handling/execute-failure-recovery.md), and [Wait for Step Completion](https://docs.superdurable.io/design-patterns/responsive-update/wait-for-step-completion.md).

**Flow graph: OrderProcessingFlow**

**Steps**

1. `Charge` (start Step): Charge the customer for the order. Next: `Ship`. Writes `order-status`.
2. `Refund`: Refund the order when shipping keeps failing. Next: the Flow completes. Writes `order-status`.
3. `Ship`: Wait for seller approval, remind after 24 hours, then ship the order. Next: `Ship` again, the Flow completes, or `Refund` if it keeps failing. Writes `order-status`.

**RPCs**

- `approve`: Publishes to `seller-ok`.
- `describe`: Reads `order-status`.

Example: [examples/python/dex_examples/products/order-processing/order_processing_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/order-processing/order_processing_flow.py)

## Flow design

<a id="how-the-flow-works"></a>

- **Charge** charges the buyer and sets the **order-status** Attribute to `charged`.
- **Ship** waits for the seller's approval on the **seller-ok** Channel or for a 24-hour Timer. When the Timer fires first, Ship sends a reminder and waits again. After approval, it ships the item, sets **order-status** to `shipped`, and completes the Flow with the output `shipped:<order ID>`.
- **Refund** runs when Ship's retries run out. It refunds the buyer, sets **order-status** to `refunded`, and completes the Flow with `refunded:<order ID>`. In the graph, ⚠ on a Step marks a failure route; select the Step to see where it goes.

The **approve** RPC publishes the approval to **seller-ok**. The **describe** RPC returns **order-status**.

## Core implementation

<a id="the-flow"></a>

<a id="2-flow-steps-and-rpcs"></a>

The charge, shipment, and refund calls carry an idempotency key built from the order ID, which is also the Flow ID: `charge-<order ID>`, `ship-<order ID>`, and `refund-<order ID>`. A Step that is cut off can run again with the same key, so the payment and shipping services can drop the repeat. See [Idempotency keys](https://docs.superdurable.io/concepts/step.md#idempotency-keys). A real reminder email needs a key too, because a Step that was cut off can run again. The example passes none.

Each Step's Execute has a 3-second retry budget to keep the demo short; the code comments suggest one hour in production. Ship's failure route moves to Refund, which has its own short retry.

The Flow receives its services in its constructor ([What a Flow contains](https://docs.superdurable.io/concepts/flow.md#implement-a-flow)). **order-status** is indexed, so you can search Flows by status. The `dex:group` and `dex:explanation` comments label the Steps in the graph above.

**Python**

```python
order_status = Attribute(
    "order-status",
    str,
    AttributeIndex(IndexType.KEYWORD, "keyword1"),
)
seller_ok = Channel[str]("seller-ok", str)


# dex:group group-id:payment group-label:"Payment"
# dex:explanation text:"Charge the customer for the order."
class Charge(Step[OrderRequest]):
    def __init__(self, service: MyDependencyService) -> None:
        self.service = service

    def get_step_options(self) -> StepOptions:
        return StepOptions(
            execute_retry=RetryPolicy(
                # One hour in production; 3 seconds keeps the demo short.
                total_duration=timedelta(seconds=3),
            )
        )

    def execute(self, context: Context, input: OrderRequest) -> StepDecision:
        self.service.charge_user(
            input.email,
            input.customer_id,
            input.amount,
            idempotency_key=f"charge-{input.order_id}",
        )
        order_status.set(context, "charged")
        return go_to(Ship, input)


# dex:group group-id:shipping group-label:"Shipping"
# dex:explanation text:"Wait for seller approval, remind after 24 hours, then ship the order."
class Ship(Step[OrderRequest]):
    def __init__(self, service: MyDependencyService) -> None:
        self.service = service

    def get_step_options(self) -> StepOptions:
        return StepOptions(
            execute_retry=RetryPolicy(
                # One hour in production; 3 seconds keeps the demo short.
                total_duration=timedelta(seconds=3),
            )
        ).on_execute_failure_proceed_to(
            Refund,
            StepOptions(
                execute_retry=RetryPolicy(
                    # One hour in production; 3 seconds keeps the demo short.
                    total_duration=timedelta(seconds=3),
                )
            ),
        )

    def wait_for(self, context: Context, input: OrderRequest) -> Wait:
        return Wait.any_of(
            seller_ok.for_one(),
            Timer.by_duration(timedelta(hours=24)),
        )

    def execute(self, context: Context, input: OrderRequest) -> StepDecision:
        if context.has_timer_fired():
            self.service.send_email(
                input.email,
                "Reminder: approve shipment",
                "Please approve or provide a tracking number.",
            )
            return go_to(Ship, input)
        self.service.ship_item(
            input.order_id,
            input.test_fail_at_shipping,
            idempotency_key=f"ship-{input.order_id}",
        )
        order_status.set(context, "shipped")
        return graceful_complete(f"shipped:{input.order_id}")


# dex:group group-id:refund group-label:"Refund"
# dex:explanation text:"Refund the order when shipping keeps failing."
class Refund(Step[OrderRequest]):
    def __init__(self, service: MyDependencyService) -> None:
        self.service = service

    def execute(self, context: Context, input: OrderRequest) -> StepDecision:
        self.service.update_external_system(
            f"refund {input.order_id}", idempotency_key=f"refund-{input.order_id}"
        )
        order_status.set(context, "refunded")
        return graceful_complete(f"refunded:{input.order_id}")


class OrderProcessingFlow(Flow[OrderRequest]):
    def __init__(self, service: MyDependencyService) -> None:
        self.service = service
        self.refund = Refund(service)
        self.ship = Ship(service)
        self.charge = Charge(service)

    def get_steps(self) -> StepList[OrderRequest]:
        return StepList.start_step(self.charge).other_steps(self.ship, self.refund)

    def get_persistence_schema(self) -> PersistenceSchema:
        return PersistenceSchema.of(order_status, seller_ok)

    @rpc
    def approve(self, context: Context, _note: str) -> RPCResult[str]:
        seller_ok.publish(context, "approved")
        return RPCResult("ok")

    @rpc
    def describe(self, context: Context) -> RPCResult[str]:
        return RPCResult(order_status.get(context))
```

Example: [examples/python/dex_examples/products/order-processing/order_processing_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/order-processing/order_processing_flow.py)

<a id="http-handlers"></a>

## The HTTP handlers

<a id="3-worker-and-client"></a>

<a id="4-controller"></a>

The examples application runs the Worker and these handlers in one process. **start** starts the Flow and returns once Charge completes, using the Client's wait-for-Step-completion API. **approve** and **describe** call the RPCs of the same names.

**Python**

```python
    @blueprint.get("/start")
    async def start() -> Response:
        flow_id = new_flow_id("order-processing")
        request = OrderRequest(
            flow_id,
            "buyer@example.com",
            "customer-1",
            42,
            optional_query("testFailAtShipping", "") == "true",
        )
        run_id = await app_state.client.start_flow(
            app_state.order_processing,
            flow_id,
            request,
            start_options(),
        )
        await app_state.client.wait_for_step_completion(
            flow_id,
            CHARGE_STEP,
            WaitForStepCompletionOptions(),
        )
        return started_flow(flow_id, run_id)

    @blueprint.get("/approve")
    async def approve() -> Response:
        output = await app_state.client.invoke_rpc(
            app_state.order_processing.approve,
            _required_flow_id(),
            optional_query("notes", ""),
        )
        return jsonify(output)

    @blueprint.get("/describe")
    async def describe() -> Response:
        flow_id = _required_flow_id()
        status = await app_state.client.invoke_rpc(
            app_state.order_processing.describe,
            flow_id,
        )
        return jsonify({"flowID": flow_id, "status": status})

    return blueprint


def _required_flow_id() -> str:
    """Reads the Flow ID from flowId, or from its alias workflowId."""
    return optional_query("workflowId", "") or required_query("flowId")
```

Example: [examples/python/dex_examples/products/order-processing/controller.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/order-processing/controller.py)

<a id="run-it"></a>

## Run it

<a id="1-start-dex"></a>

<a id="5-run"></a>

Start the examples of one language as in [Run an example from the playground](https://docs.superdurable.io/install.md#run-an-example-from-the-playground). Then start an order:

```bash
curl -s 'http://127.0.0.1:8080/products/order-processing/start'
```

Copy `flowID` from the response. In Dex Web, at the address `dexcli dev` prints, such as `http://127.0.0.1:8802`, the Flow waits in Ship. Approve the shipment, replacing `FLOW_ID`:

```bash
curl -s "http://127.0.0.1:8080/products/order-processing/approve?flowId=FLOW_ID"
```

The call publishes the approval to **seller-ok**. Ship then ships the item and the Flow completes; watch it in Dex Web. You can make the same calls from the [examples playground](https://github.com/superdurable/dex/tree/main/examples/playground): choose **Order processing**.

<a id="try-the-refund-path"></a>

### Try the refund path

Start an order whose shipping always fails:

```bash
curl -s 'http://127.0.0.1:8080/products/order-processing/start?testFailAtShipping=true'
```

Copy the new `flowID` and approve it as before. Ship then fails until its 3-second retry budget runs out, and Refund runs. Wait in Dex Web until Refund completes, or repeat this call until the status is **refunded**:

```bash
curl -s "http://127.0.0.1:8080/products/order-processing/describe?flowId=FLOW_ID"
```

In Dex Web, **Events** → **Graph** shows Charge, Ship, and then Refund.

<a id="dex-web"></a>

## See the run in Dex Web

<a id="6-dex-web"></a>

Open an approved run and select **Events**. **Timeline** shows the charge, approval, and shipment in order; select an event to read its input and output. **Graph** shows how the Steps connect.

[![Dex Web Timeline showing the approved order through charging and shipping](https://docs.superdurable.io/img/use-cases/order-processing-timeline.png)](https://docs.superdurable.io/img/use-cases/order-processing-timeline.png)

[![Dex Web Graph showing the approved order through charging and shipping](https://docs.superdurable.io/img/use-cases/order-processing-graph.png)](https://docs.superdurable.io/img/use-cases/order-processing-graph.png)

## Next

- [Subscription and Billing Lifecycle](https://docs.superdurable.io/examples/subscription-and-billing-lifecycle.md): the next example.
- [Concepts](https://docs.superdurable.io/concepts.md): the Flow, Step, Channel, and Timer this example uses.
- [Application](https://docs.superdurable.io/concepts/application.md): add a Worker and a Client to your own service.
- [Examples](https://docs.superdurable.io/examples.md): more examples.
