Skip to main content

Child Flows with Business Identity

View as Markdown

Use this pattern when each child job has its own business number. People and other systems look the child up, retry it, or stop it by that number.

An example is an order that ships as several parcels. Each shipment has a shipment number. The carrier, the support team, and the order all find the shipment by that number. The order still needs to know how each shipment ended.

The order starts each shipment as its own top-level Flow. The shipment number is its Flow ID.

How it works

  1. StartShipments starts one branch per shipment.
  2. StartShipment starts a ShipmentFlow through the Client. Its Flow ID is the shipment number. The shipment gets its own Flow timeout. StartShipment passes the run ID that the start returns to the next Step.
  3. ClaimShipment records that run ID as the claimed run. It also merges a report that arrived before the claim.
  4. The shipment delivers. DeliverShipment stores its outcome in the shipmentOutcome Attribute.
  5. ReportShipmentOutcome calls the order's report RPC with its own run ID. The RPC is RecordShipmentOutcome in Go, record_shipment_outcome in Python, and recordShipmentOutcome in Java, TypeScript, and Rust. It fills the outcome in the shipment's record.
  6. AwaitShipment reads that run at each interval. A running shipment is read again later. For a closed shipment, RecordShipmentEnd records the terminal status, and the read outcome when no report filled it.

The report RPC and the Steps that write the records share one lock. An RPC never waits for a lock: it fails while a Step holds it. A Step's lock stays held through its retries and backoff. So the Steps that call the Client, StartShipment and AwaitShipment, take no lock. Each hands its result to a short locked Step that only writes the records.

A shipment that fails or times out on its own never reports, because its report Step never runs. The interval read in step 6 covers it. A child can also route its terminal failure to a recovery Step, or its timeout to a timeout handler, that reports to the parent. Keep each shipment's Flow timeout longer than its retry budget.

The Production checklist covers the edge cases the example handles.

order_fulfillment_flow.pyPython
# dex:group group-id:start group-label:"Start shipments"
# dex:explanation text:"Starts the shipment as a top-level Flow named by its shipment number."
class StartShipment(Step[TrackedShipment]):
"""Starts ShipmentFlow with the shipment number as its Flow ID.

It takes no lock: a report must never wait for the start call or its retries.
"""

def __init__(
self,
client_provider: Callable[[], AsyncClient],
shipment_flow: ShipmentFlow,
) -> None:
self.client_provider = client_provider
self.shipment_flow = shipment_flow

async def execute( # type: ignore[override]
self, context: AsyncContext, tracked: TrackedShipment
) -> StepDecision:
number = tracked.shipment.shipment_number
try:
run_id = await self.client_provider().start_flow(
self.shipment_flow,
number,
ShipmentRequest(order_flow_id=context.flow_id, shipment=tracked.shipment),
StartFlowOptions(
timeout=SHIPMENT_TIMEOUT,
id_reuse_policy=IdReusePolicy.DISALLOW,
request_id=shipment_start_request_id(context.flow_id, tracked.shipment),
ignore_already_started=True,

Example: examples/python/dex_examples/patterns/child-flows-business-identity/order_fulfillment_flow.py

Report after the outcome commits

The shipment commits its outcome in one Step and reports in the next. Both Steps declare SYNC durability for Execute. The report Step then starts only after the outcome is stored, even when the Flow defaults to ASYNC.

The report carries the shipment's own run ID. When the Client accepts an RPC request ID, the report also carries a stable one: report:, the shipment number, :, and the run ID.

When the order has already closed, the report fails with a typed error. The shipment ends its attempts there. Its outcome stays readable through the Client.

order_fulfillment_flow.pyPython
# dex:group group-id:deliver group-label:"Deliver"
# dex:explanation text:"Waits for the carrier, then commits the delivered outcome."
class DeliverShipment(Step[ShipmentRequest]):
"""Waits for the simulated carrier, then stores the outcome."""

def get_step_options(self) -> StepOptions:
"""Stores the outcome before the report Step starts, even when the Flow defaults to ASYNC."""
return StepOptions(execute_durability=StepDurability.SYNC)

def wait_for(self, context: Context, request: ShipmentRequest) -> Wait:
return Wait.until(
Timer.by_duration(timedelta(seconds=request.shipment.delivery_delay_seconds))
)

def execute(self, context: Context, request: ShipmentRequest) -> StepDecision:
outcome = "delivered to " + request.shipment.destination
SHIPMENT_OUTCOME.set(context, outcome)
return go_to(
ReportShipmentOutcome,
PendingReport(
order_flow_id=request.order_flow_id,
report=ShipmentReport(
shipment_number=request.shipment.shipment_number,
shipment_run_id=context.run_id,
outcome=outcome,
),
),
)


Example: examples/python/dex_examples/patterns/child-flows-business-identity/order_fulfillment_flow.py

One record per shipment

The order keeps one record per shipment in the shipmentRecords AttributeMap, keyed by the shipment number. The record holds the status, the claimed run ID, and the outcome as separate fields.

The report RPC fills the outcome in the shipment's record. A report can arrive before ClaimShipment records the run. The RPC then keeps it in the pendingShipmentReports AttributeMap, keyed by the shipment number. Each entry holds the first report of each run ID. ClaimShipment merges the claimed run's report. The Production checklist lists which reports it accepts.

order_fulfillment_flow.pyPython
@rpc(
lock_attributes=(SHIPMENT_RECORDS_LOCK.lock(),),
load_attribute_maps=(SHIPMENT_RECORDS, PENDING_SHIPMENT_REPORTS),
)
def record_shipment_outcome(self, context: Context, report: ShipmentReport) -> None:
"""Fills the outcome of a shipment's record.

It accepts only the run this order claimed. The first report wins, and
any other report changes nothing. Before the claim, it keeps the first
report of each run for ClaimShipment to merge.
"""
record, found = load_shipment_record(context, report.shipment_number)
# Ignore an unknown shipment and a report without a run.
if not found or not report.shipment_run_id:
return
if record.status == SHIPMENT_STARTING:
pending: dict[str, ShipmentReport] = (
PENDING_SHIPMENT_REPORTS.get(context, report.shipment_number) or {}
)
if report.shipment_run_id not in pending:
PENDING_SHIPMENT_REPORTS.set(
context,
report.shipment_number,
{**pending, report.shipment_run_id: report},
)
return
# Ignore a rejected shipment, another run, and a repeated report.
if (
not record.run_id
or record.run_id != report.shipment_run_id
or record.outcome
):
return
SHIPMENT_RECORDS.set(
context,
report.shipment_number,
dataclasses.replace(record, outcome=report.outcome),
)

Example: examples/python/dex_examples/patterns/child-flows-business-identity/order_fulfillment_flow.py

AwaitShipment describes the shipment at each interval. A running shipment is read again at the next interval, even after its report arrived. For a closed shipment, RecordShipmentEnd records its status, and its outcome when no report filled it.

The support team can cancel a shipment by its number. A shipment canceled before its outcome commits has no outcome; the order records it as canceled. A shipment canceled after its outcome commits, or after it sent its report, can still have an outcome, and the order keeps it.

Look up a shipment by its number

Any caller can find a shipment by its number, without knowing the order. The example's HTTP routes describe the Flow with that ID first. A Flow that is not a ShipmentFlow answers 404, so an order ID cannot be read or canceled as a shipment.

controller.pyPython
async def describe_shipment(number: str) -> FlowInfo | None:
"""Describes the Flow named by a shipment number.

Returns None when no ShipmentFlow has that Flow ID. Any other failure raises.
"""
try:
info = await app_state.client.describe_flow(number)
except FlowNotFoundError:
return None
return info if info.flow_type == SHIPMENT_FLOW_TYPE else None

@blueprint.get("/shipment")
async def get_shipment() -> tuple[dict[str, str], int]:
"""Looks a shipment up by its shipment number, which is its Flow ID."""
number = required_query("shipmentNumber")
info = await describe_shipment(number)
if info is None:
return {"error": f"shipment {number} not found"}, 404
values = await app_state.client.get_attributes(number, SHIPMENT_OUTCOME)
return {
"shipmentNumber": number,
"status": info.status.value,
"outcome": values.get(SHIPMENT_OUTCOME, ""),
}, 200

@blueprint.get("/cancel-shipment")
async def cancel_shipment() -> tuple[str | dict[str, str], int]:
"""Stops a shipment by its number. Its order records it at the next reconcile read."""
number = required_query("shipmentNumber")
if await describe_shipment(number) is None:
return {"error": f"shipment {number} not found"}, 404
await app_state.client.stop_flow(
number,
StopFlowOptions(type=StopType.CANCEL, reason="shipment canceled"),
)
return "canceled", 200

Example: examples/python/dex_examples/patterns/child-flows-business-identity/controller.py

Try the routes in the examples playground. Its shipment fields default to the second shipment of the current order.

Choose this or a SubFlow

Choose a SubFlow when the child exists only for its parent. Dex derives its Flow ID from the parent, and the parent waits for it with a Condition.

Choose a top-level child Flow when the child needs its own identity:

  • People or systems look it up, retry it, or stop it by its own number.
  • Something other than the parent can start it.
  • It can outlive the parent, with its own Flow timeout.

The cost is more code. The parent starts the child, claims its run, receives its report, and reads it until it ends.

Production checklist

  • Claim the child run. After the start returns, ClaimShipment records the run ID. From then on, the order accepts reports and reads of that run only. The order first registers each number as starting. Every writer of the records locks the singleton shipmentRecordsLock Attribute: StartShipments, ClaimShipment, RecordShipmentEnd, and the report RPC. The lock Attribute stores no value; it lets one writer at a time change the records.
  • Keep Client calls out of locked Steps. StartShipment and AwaitShipment call the Client and take no lock. A report that meets the lock fails with a lock conflict, and the shipment retries it. The locked Steps make no calls, so they hold the lock only briefly.
  • Accept reports only from the claimed run. A shipment that is still starting has no claimed run yet. The RPC keeps the first report of each run under the shipment number in pendingShipmentReports. A report sent under another number never hides it. ClaimShipment merges the claimed run's report, then deletes the shipment's whole entry, so the outcome is counted once. A rejection deletes the entry too. A report for an unknown or rejected number, from another run, or for a record that already has an outcome changes nothing. Otherwise the RPC fills the outcome.
  • Read the result, then confirm the run. AwaitShipment calls reconcileShipment (reconcile_shipment in Python and Rust). Its first Describe records unavailable only when the Flow is not found or its run ID differs from the claimed one. After it reads a terminal status, it reads the outcome Attribute. An unset Attribute means the shipment ended without an outcome. When the Attribute read returns FlowNotFound, the function keeps the status and skips the second Describe. The Attribute read sees the shipment's latest run. When it succeeds, the function describes the shipment again to check the run ID. When the run is gone or replaced, the function keeps the status and drops this read's outcome. Reports the order already received stay in the record.
  • Retry other read errors. Any other error fails the AwaitShipment Step, so Dex retries it. The retries hold no lock, so reports still arrive.
  • Plan for a shipment number reused later. When the shipment cannot be found, or another run of the same number replaced the claimed one, the order records unavailable. That is a business policy. The order learns the terminal status of a claimed run while the order runs and the run stays the shipment's latest run. Once another caller reopens the number, or the run's data is deleted, the order can no longer read it. A shipment number belongs to one order. When another request already used the number, the start fails with a typed already-started error. The example records that shipment as rejected and ignores reports for it. The order never waits for, counts, or stops a rejected shipment, because that run belongs to another request. Give each business attempt its own shipment number.
  • Reject duplicate numbers in one order. StartShipments checks the order before it starts anything: the reconcile interval is positive, no delivery delay is negative, and every shipment number is unique.
  • Hash the start request. The request ID of the start is a digest of the complete start request. A retried Step repeats the same start while the original run is still the shipment's latest run. When another caller reopens the number before the claim, the retry gets the already-started error, and the order records rejected. To protect unclaimed starts, every entry point that starts a shipment must disallow ID reuse.

Next