---
title: "Wait for Half"
description: "Start N SubFlows, wait for half to finish, then stop the unfinished children."
canonical_url: "https://docs.superdurable.io/design-patterns/subflows/wait-for-half/"
source: "docs/content/design-patterns/subflows/wait-for-half.mdx"
locale: "en"
language: "python"
---

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

# Wait for Half

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

Start N SubFlows, wait for half to finish, then stop the unfinished children.

**Flow graph: WaitForHalfParentFlow**

**Steps**

1. `WaitForHalfInit` (start Step): Start one child Flow Step per request and the half-way wait. Next: the Flow completes, `SubFlowStep`, or `WaitSubFlows`.
2. `SubFlowStep`: Run one child Flow, or stop it once half of them finished. Next: the Flow completes. Writes `ChildStopOutcomes`; publishes to `SubFlowCompletedCh`.
3. `WaitSubFlows`: Wait for half of the child Flows, then stop the rest. Next: the Flow completes. Publishes to `AllDoneCh`.

Example: [examples/python/dex_examples/patterns/parallel-subflows/wait_for_half_parent_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/parallel-subflows/wait_for_half_parent_flow.py)

Each child runs in its own `SubFlowStep` execution. A completed child publishes one message to `SubFlowCompletedCh`. `WaitSubFlows` waits for half of those messages, then publishes one `AllDoneCh` message for every possible unfinished child.

Once half of the children have finished, each waiting `SubFlowStep` consumes one `AllDoneCh` message and tries to stop its child. The Step records the outcome in `ChildStopOutcomes`, keyed by the child Flow ID, then completes gracefully. A successful stop records `stopped`. A typed error for a missing, inactive, or closing Flow prompts a state read. The Step records the terminal status and any stored result for a closed child. A running, closing, or missing child is recorded as `unknown` for a later read. Other errors trigger a Step retry.

## Core implementation

**Python**

```python
@dataclass(frozen=True)
class ChildStopOutcome:
    status: str
    result: str | None = None


CHILD_STOP_OUTCOMES = AttributeMap("ChildStopOutcomes", ChildStopOutcome)


class WaitForHalfInit(Step[list[str]]):
    def execute(self, context: Context, requests: list[str]) -> StepDecision:
        if not requests:
            return graceful_complete()
        return go_to_many(
            StepMovement.of(WaitSubFlows, len(requests)),
            *(StepMovement.of(SubFlowStep, request) for request in requests),
        )


class SubFlowStep(Step[str]):
    def __init__(
        self,
        client_provider: Callable[[], AsyncClient],
        example_subflow: ExampleSubFlow,
        subflow_completed_ch: Channel[bool],
        all_done_ch: Channel[bool],
    ) -> None:
        self.client_provider = client_provider
        self.example_subflow = example_subflow
        self.subflow_completed_ch = subflow_completed_ch
        self.all_done_ch = all_done_ch

    def wait_for(self, context: Context, request: str) -> Wait:
        return Wait.any_of(SubFlow.run(self.example_subflow, request), self.all_done_ch.for_one())

    async def execute(self, context: AsyncContext, request: str) -> StepDecision:
        if SubFlow.get_condition_results(context).status is not FlowStatus.RUNNING:
            self.subflow_completed_ch.publish(context, True)
            return graceful_complete()
        client = self.client_provider()
        child_flow_id = SubFlow.get_flow_id(context)
        try:
            await client.stop_flow(child_flow_id)
        except (FlowNotFoundError, FlowNotActiveOrNotFoundError, FlowClosingError):
            outcome = await self._read_child_stop_outcome(client, child_flow_id)
        else:
            outcome = ChildStopOutcome("stopped")
        CHILD_STOP_OUTCOMES.set(context, child_flow_id, outcome)
        return graceful_complete()

    @staticmethod
    async def _read_child_stop_outcome(
        client: AsyncClient, child_flow_id: str
    ) -> ChildStopOutcome:
        try:
            info = await client.describe_flow(child_flow_id)
        except FlowNotFoundError:
            return ChildStopOutcome("unknown")
        if info.status is FlowStatus.RUNNING:
            return ChildStopOutcome("unknown")
        result = await client.wait_for_flow(child_flow_id)
        return ChildStopOutcome(
            result.status.value,
            result.single_output(str) if result.completions else None,
        )


class WaitSubFlows(Step[int]):
    def __init__(
        self, subflow_completed_ch: Channel[bool], all_done_ch: Channel[bool]
    ) -> None:
        self.subflow_completed_ch = subflow_completed_ch
        self.all_done_ch = all_done_ch

    def wait_for(self, context: Context, total: int) -> Wait:
        return Wait.until(self.subflow_completed_ch.for_n((total + 1) // 2))

    def execute(self, context: Context, total: int) -> StepDecision:
        for _ in range(total - (total + 1) // 2):
            self.all_done_ch.publish(context, True)
        return graceful_complete()


class WaitForHalfParentFlow(Flow[list[str]]):
    subflow_completed_ch = Channel("SubFlowCompletedCh", bool)
    all_done_ch = Channel("AllDoneCh", bool)

    def __init__(
        self,
        client_provider: Callable[[], AsyncClient],
        example_subflow: ExampleSubFlow,
    ) -> None:
        self.init = WaitForHalfInit()
        self.subflow = SubFlowStep(client_provider, example_subflow, self.subflow_completed_ch, self.all_done_ch)
        self.wait_subflows = WaitSubFlows(self.subflow_completed_ch, self.all_done_ch)

    def get_steps(self) -> StepList[list[str]]:
        return StepList.start_step(self.init).other_steps(self.subflow, self.wait_subflows)

    def get_persistence_schema(self) -> PersistenceSchema:
        return PersistenceSchema.of(
            self.subflow_completed_ch, self.all_done_ch, CHILD_STOP_OUTCOMES
        )
```

Example: [examples/python/dex_examples/patterns/parallel-subflows/wait_for_half_parent_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/parallel-subflows/wait_for_half_parent_flow.py)

<a id="late-finishers"></a>

## Children that finish at the threshold

When the report counts every child or a follow-up action depends on how each child ended, the Step reads the child after every stop and records how it ended. When the parent needs only the quorum, it stops the remaining children and moves on without this read. A child can finish at the same moment its stop message arrives, and a Channel condition wins over a SubFlow condition when both are ready, so the Step may stop a child that already ended. After a successful stop, or a refused one such as "not found", "not active", or "closing", read the child through the Client. Record a closed child's terminal status and stored result, so the report counts every child that finished. Read a child that is still running or closing again later. A child that is not found is recorded by business policy, such as "unavailable". Return any other stop or read error so the Step retries. Record every child, finished or stopped, in one record keyed by its SubFlow ID. The example is simplified: it does not read the child's terminal state after a successful stop.

When each child needs its own business identity, start it as a [top-level Flow](https://docs.superdurable.io/concepts/flow.md#child-flows) instead. The quorum Step stops each child that has not reported and, when the parent needs its outcome, reconciles it by the rules on that page. Normal reports and reconciled outcomes go into one record, keyed by the child Flow ID.

## Next

- [Long-lived parent](https://docs.superdurable.io/design-patterns/subflows/long-lived-parent.md)
- [Basic parent Flow](https://docs.superdurable.io/design-patterns/subflows/basic.md)
