Skip to main content

Order Processing

View as Markdown

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, Execute Failure Recovery, and Wait for Step Completion.

Flow design

  • 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

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. 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). 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.

order_processing_flow.pyPython
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:

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:

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

The HTTP handlers

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.

controller.pyPython
    @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

Run it

Start the examples of one language as in Run an example from the playground. Then start an order:

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:

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: choose Order processing.

Try the refund path

Start an order whose shipping always fails:

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:

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.

See the run in Dex Web

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

Dex Web Graph showing the approved order through charging and shipping

Next