---
title: "Child Flows with Business Identity"
description: "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."
canonical_url: "https://docs.superdurable.io/design-patterns/subflows/child-flows-with-business-identity/"
source: "docs/content/design-patterns/subflows/child-flows-with-business-identity.mdx"
locale: "en"
language: "python"
---

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

# Child Flows with Business Identity

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

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.

**Flow graph: OrderFulfillmentFlow**

**Steps**

1. `StartShipments` (start Step): Checks the order, registers its shipment numbers, then starts one branch per shipment. Next: the Flow fails, the Flow completes, or `StartShipment`. Writes `shipmentRecords`; locks `shipmentRecordsLock`.
2. `AwaitShipment`: Reads the claimed shipment run at each interval until it ends. Next: `AwaitShipment` again, or `RecordShipmentEnd`.
3. `ClaimShipment`: Claims the started run and merges a report that arrived before the claim. Next: the Flow completes, or `AwaitShipment`. Reads `pendingShipmentReports`; writes `pendingShipmentReports`, `shipmentRecords`; locks `shipmentRecordsLock`.
4. `RecordShipmentEnd`: Records how the claimed shipment run ended. Next: the Flow completes. Writes `shipmentRecords`; locks `shipmentRecordsLock`.
5. `StartShipment`: Starts the shipment as a top-level Flow named by its shipment number. Next: `ClaimShipment`.

**RPCs**

- `record_shipment_outcome`: Reads `pendingShipmentReports`, `shipmentRecords`; writes `pendingShipmentReports`, `shipmentRecords`; locks `shipmentRecordsLock`.

Example: [examples/python/dex_examples/patterns/child-flows-business-identity/order_fulfillment_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/child-flows-business-identity/order_fulfillment_flow.py)

**Flow graph: ShipmentFlow**

**Steps**

1. `DeliverShipment` (start Step): Waits for the carrier, then commits the delivered outcome. Next: `ReportShipmentOutcome`. Writes `shipmentOutcome`.
2. `ReportShipmentOutcome`: Reports the committed outcome to the order that started this shipment. Next: the Flow completes.

Example: [examples/python/dex_examples/patterns/child-flows-business-identity/order_fulfillment_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/child-flows-business-identity/order_fulfillment_flow.py)

## 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](https://docs.superdurable.io/design-patterns/subflows/child-flows-with-business-identity.md#production-checklist) covers the edge cases the example handles.

**Python**

```python
# 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,
                ),
            )
        except FlowAlreadyStartedError:
            # Another request owns this shipment number; this order does not track it.
            return go_to(ClaimShipment, StartedShipment(tracked=tracked, rejected=True))
        return go_to(
            ClaimShipment,
            StartedShipment(tracked=dataclasses.replace(tracked, shipment_run_id=run_id)),
        )


# dex:group group-id:start group-label:"Start shipments"
# dex:explanation text:"Claims the started run and merges a report that arrived before the claim."
class ClaimShipment(Step[StartedShipment]):
    """Records the claimed run, or the rejection, and merges a pending report of that run."""

    def get_step_options(self) -> StepOptions:
        """Takes the records lock, so the claim never races a report."""
        return StepOptions(
            execute_lock_attributes=(SHIPMENT_RECORDS_LOCK.lock(),),
            execute_load_attribute_maps=(PENDING_SHIPMENT_REPORTS,),
        )

    def execute(self, context: Context, started: StartedShipment) -> StepDecision:
        number = started.tracked.shipment.shipment_number
        pending: dict[str, ShipmentReport] | None = PENDING_SHIPMENT_REPORTS.get(context, number)
        # The claim or the rejection settles every early report of this shipment.
        if pending is not None:
            PENDING_SHIPMENT_REPORTS.delete(context, number)
        if started.rejected:
            SHIPMENT_RECORDS.set(context, number, ShipmentRecord(status=SHIPMENT_REJECTED))
            return graceful_complete()
        run_id = started.tracked.shipment_run_id
        # Claim the run: reports and reads of any other run of this number are ignored.
        report = (pending or {}).get(run_id)
        outcome = report.outcome if report is not None else ""
        SHIPMENT_RECORDS.set(
            context,
            number,
            ShipmentRecord(status=SHIPMENT_STARTED, run_id=run_id, outcome=outcome),
        )
        return go_to(AwaitShipment, started.tracked)


# dex:group group-id:track group-label:"Track shipment"
# dex:explanation text:"Reads the claimed shipment run at each interval until it ends."
class AwaitShipment(Step[TrackedShipment]):
    """Reads the claimed shipment run at each interval until it ends.

    It takes no lock: a report must never wait for the reads or their retries.
    """

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

    def wait_for(self, context: Context, tracked: TrackedShipment) -> Wait:
        return Wait.until(
            Timer.by_duration(timedelta(seconds=tracked.reconcile_interval_seconds))
        )

    async def execute(  # type: ignore[override]
        self, context: AsyncContext, tracked: TrackedShipment
    ) -> StepDecision:
        number = tracked.shipment.shipment_number
        reading = await reconcile_shipment(
            self.client_provider(), number, tracked.shipment_run_id
        )
        if reading.status == FlowStatus.RUNNING.value:
            return go_to(AwaitShipment, tracked)
        return go_to(
            RecordShipmentEnd,
            EndedShipment(
                shipment_number=number,
                shipment_run_id=tracked.shipment_run_id,
                reading=reading,
            ),
        )


# dex:group group-id:track group-label:"Track shipment"
# dex:explanation text:"Records how the claimed shipment run ended."
class RecordShipmentEnd(Step[EndedShipment]):
    """Merges the terminal status, and the read outcome when no report filled it."""

    def get_step_options(self) -> StepOptions:
        """Takes the same lock as the report RPC and loads the records."""
        return StepOptions(
            execute_lock_attributes=(SHIPMENT_RECORDS_LOCK.lock(),),
            execute_load_attribute_maps=(SHIPMENT_RECORDS,),
        )

    def execute(self, context: Context, ended: EndedShipment) -> StepDecision:
        # Merge with the record, which may already hold the reported outcome.
        record, _ = load_shipment_record(context, ended.shipment_number)
        SHIPMENT_RECORDS.set(
            context,
            ended.shipment_number,
            ShipmentRecord(
                status=ended.reading.status,
                run_id=ended.shipment_run_id,
                outcome=record.outcome or ended.reading.outcome,
            ),
        )
        return graceful_complete()

async def reconcile_shipment(client: AsyncClient, number: str, run_id: str) -> ShipmentRecord:
    """Reads the claimed run of a shipment: its status first, then its outcome.

    Returns a "running" record while that run runs, and an "unavailable" record
    when that run no longer exists or another run replaced it. Keeps an outcome
    only when the run is still the claimed one after the read. Any other failure
    raises, so the Step retries.
    """
    info, found = await describe_claimed_run(client, number, run_id)
    if info is None or not found:
        return ShipmentRecord(status=SHIPMENT_UNAVAILABLE)
    if info.status is FlowStatus.RUNNING:
        return ShipmentRecord(status=info.status.value)
    try:
        values = await client.get_attributes(number, SHIPMENT_OUTCOME)
    except FlowNotFoundError:
        return ShipmentRecord(status=info.status.value)
    # The Attribute read targets the latest run, so confirm it is still the claimed one.
    _, still_claimed = await describe_claimed_run(client, number, run_id)
    if not still_claimed:
        return ShipmentRecord(status=info.status.value)
    # An unset outcome Attribute leaves the outcome empty: the shipment ended without one.
    return ShipmentRecord(
        status=info.status.value, outcome=values.get(SHIPMENT_OUTCOME, "")
    )
```

Example: [examples/python/dex_examples/patterns/child-flows-business-identity/order_fulfillment_flow.py](https://github.com/superdurable/dex/tree/main/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.

**Python**

```python
# 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,
                ),
            ),
        )


# dex:group group-id:report group-label:"Report"
# dex:explanation text:"Reports the committed outcome to the order that started this shipment."
class ReportShipmentOutcome(Step[PendingReport]):
    """Sends the committed outcome to the order's RPC."""

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

    def get_step_options(self) -> StepOptions:
        """Keeps the report SYNC, like the Step that stores the outcome."""
        return StepOptions(execute_durability=StepDurability.SYNC)

    async def execute(  # type: ignore[override]
        self, context: AsyncContext, pending: PendingReport
    ) -> StepDecision:
        try:
            await self.client_provider().invoke_rpc(
                self.order_flow_provider().record_shipment_outcome,
                pending.order_flow_id,
                pending.report,
                options=RPCInvokeOptions(
                    request_id=f"report:{pending.report.shipment_number}:{pending.report.shipment_run_id}",
                ),
            )
        except (FlowNotFoundError, FlowNotActiveOrNotFoundError):
            # A closed order ends the attempts; the outcome stays readable through the Client.
            pass
        return graceful_complete(pending.report.outcome)
```

Example: [examples/python/dex_examples/patterns/child-flows-business-identity/order_fulfillment_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/child-flows-business-identity/order_fulfillment_flow.py)

<a id="records"></a>

## 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](https://docs.superdurable.io/design-patterns/subflows/child-flows-with-business-identity.md#production-checklist) lists which reports it accepts.

**Python**

```python
@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](https://github.com/superdurable/dex/tree/main/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.

<a id="lookup"></a>

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

**Python**

```python
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](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/child-flows-business-identity/controller.py)

Try the routes in the [examples playground](https://github.com/superdurable/dex/tree/main/examples/playground). Its shipment fields default to the second shipment of the current order.

<a id="choose"></a>

## Choose this or a SubFlow

Choose a [SubFlow](https://docs.superdurable.io/concepts/primitives/subflow.md) 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.

<a id="production-checklist"></a>

## 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

- [Durable Timer](https://docs.superdurable.io/design-patterns/durable-timer.md)
- [Cancel a Case with Its Child Flows](https://docs.superdurable.io/design-patterns/subflows/cancel-case.md)
- [Wait for Half](https://docs.superdurable.io/design-patterns/subflows/wait-for-half.md)
- [Child Flows with their own identity](https://docs.superdurable.io/concepts/flow.md#child-flows)
