---
title: "Cancel a Case with Its Child Flows"
description: "Use this pattern when canceling a Flow must also stop the child Flows it started."
canonical_url: "https://docs.superdurable.io/design-patterns/subflows/cancel-case/"
source: "docs/content/design-patterns/subflows/cancel-case.mdx"
locale: "en"
language: "python"
---

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

# Cancel a Case with Its Child Flows

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

Use this pattern when canceling a Flow must also stop the child Flows it started.

An example is a loan application that runs its credit check as a child Flow. When the applicant withdraws, the application closes. The credit check must stop too.

A SubFlow keeps running when its parent completes, fails, times out, or is stopped. The parent must stop each child before it closes.

**Flow graph: LoanApplicationFlow**

**Steps**

1. `RunCreditCheck` (start Step): Run the credit check child Flow, or stop it when the application is canceled. Next: the Flow fails, or `AwaitUnderwriterDecision`. Reads `applicationCanceled`; writes `stoppedCreditCheckFlowId`.
2. `AwaitUnderwriterDecision`: Wait for the underwriter's decision or a cancellation. Next: the Flow fails, or the Flow completes. Reads `applicationCanceled`, `underwriterDecided`.

**RPCs**

- `cancel_application`: Publishes to `applicationCanceled`.
- `decide_application`: Publishes to `underwriterDecided`.

Example: [examples/python/dex_examples/patterns/cancel-case/loan_application_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/cancel-case/loan_application_flow.py)

## How it works

- A cancel RPC publishes the reason to a cancel Channel.
- The Step that starts the SubFlow waits with `AnyOf` for the SubFlow or the cancel Channel.
- When the child completes first, `Execute` reads its result and moves on. Any other end of the child, such as a failure or a timeout, fails the parent with `ForceFail`.
- When the cancel message wins, `Execute` reads the child Flow ID with `SubFlowID`. It stops the child with the Client `StopFlow` and closes the parent with `ForceFail`.
- Every later Step that waits also waits for the cancel Channel. A cancel that arrives after the child finished still closes the case.
- A pending cancel wins over a normal completion in every wait. In the wait on the SubFlow, a ready Channel always wins over a ready SubFlow. In a wait on two Channels, the first declared Channel wins, so declare the cancel Channel before the decision Channel.
- A fallback or deadline Timer can win, and a withdrawal can still commit after it, before the Timer branch runs. Make the Timer branch handle a withdrawal that may still be queued, for example by waiting on the cancel Channel in its next Step. Or close a reply window with an Attribute lock, as in [Decision with Deadline](https://docs.superdurable.io/design-patterns/external-interaction/decision-with-deadline.md#close-the-response-window).
- A cancel that arrives after the last Step consumed its decision message, or after the Flow closed, cannot change the outcome.
- Once the decision is final, close the Flow without consuming the cancel Channel. A close that drains the cancel Channel and falls back to a cancel path would let a late cancel override the decision.

In the example:

1. The applicant withdraws through the `cancelApplication` RPC. It publishes the reason to the `ApplicationCanceled` Channel.
2. `RunCreditCheck` starts the credit check as a child Flow with a 7-day timeout. It waits for a withdrawal or for the credit check to finish.
3. When the applicant withdraws first, `RunCreditCheck` stops the credit check and fails the application with the reason.
4. When the credit check completes first, the application moves to `AwaitUnderwriterDecision` with the report. When the credit check fails or times out, the application fails.
5. `AwaitUnderwriterDecision` waits for a withdrawal or the underwriter's decision. It declares the withdrawal Channel first, so a withdrawal that is ready together with a decision wins. A withdrawal fails the application. A decision completes it.

## Stopping the child

- `Execute` can be retried, and the child can finish at the same moment. Treat "not found", "not active", and "closing" from `StopFlow` as already stopped.
- The Worker needs a Client to call `StopFlow`. Pass a Client provider to the Flow constructor.
- Record the stopped child Flow ID in an Attribute when operators or tests need to find it.

## Limits

This pattern stops children only when the cancellation arrives through the cancel Channel. Other ways the parent closes leave the children running:

- a Client `StopFlow` on the parent;
- the parent's Flow timeout;
- a `ForceFail` or `ForceComplete` from another Step of the parent.

Set a Flow timeout on every child, so a child that is never stopped still ends. The example gives the credit check a 7-day timeout. Clients that cancel a case call the cancel RPC, not `StopFlow`.

## Several children

One cancel message satisfies one wait. When several Steps each hold a child at the same time, each Step needs its own cancel message.

- Use a ChannelMap with one key per Step. The cancel RPC publishes to every key, and each Step waits on its own key.
- Or have the cancel RPC publish one message per waiting Step to a single Channel.

Every Step that holds a child must stop its own child before anything closes the Flow. Closing the Flow from the first Step that sees a cancel message would break this: its `ForceFail` cancels the other Steps before they stop their children.

## Example

`LoanApplicationFlow` starts with the applicant ID. `RunCreditCheck` starts `CreditCheckFlow` with a 7-day Flow timeout and waits for it or the `cancelApplication` RPC. `AwaitUnderwriterDecision` waits for the `decideApplication` RPC or a later cancellation. When a cancellation stops the credit check, the Flow stores the child Flow ID in the `stoppedCreditCheckFlowId` Attribute.

**Python**

```python
class RunCreditCheck(Step[LoanApplication]):
    """Waits for its child Flow or a cancellation, whichever comes first."""

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

    def wait_for(self, context: Context, application: LoanApplication) -> Wait:
        request = CreditCheckRequest(
            applicant_id=application.applicant_id,
            report_delay_seconds=application.credit_report_delay_seconds,
        )
        # The cancel condition comes first: it wins when both are ready.
        return Wait.any_of(
            APPLICATION_CANCELED.for_one(),
            SubFlow.run(
                self.credit_check_flow,
                request,
                SubFlowOptions(
                    timeout=CREDIT_CHECK_TIMEOUT,
                    reuse_policy=SubFlowReusePolicy.RESTART_IF_PREVIOUS_EXITS_ABNORMALLY,
                ),
            ),
        )

    async def execute(  # type: ignore[override]
        self, context: AsyncContext, application: LoanApplication
    ) -> StepDecision:
        reasons = APPLICATION_CANCELED.results(context)
        if reasons:
            child_flow_id = SubFlow.get_flow_id(context)
            await self.stop_credit_check(child_flow_id)
            STOPPED_CREDIT_CHECK_FLOW_ID.set(context, child_flow_id)
            return force_fail(APPLICATION_CANCELED_PREFIX + reasons[0])
        result = SubFlow.get_condition_results(context)
        if result.status is not FlowStatus.COMPLETED:
            return force_fail(f"credit check ended with status {result.status.value}")
        return go_to(AwaitUnderwriterDecision, result.single_output(str))

    async def stop_credit_check(self, child_flow_id: str) -> None:
        """Cancels the child; a missing or already closed child counts as stopped."""
        try:
            await self.client_provider().stop_flow(
                child_flow_id,
                StopFlowOptions(type=StopType.CANCEL, reason="loan application canceled"),
            )
        except (FlowNotFoundError, FlowNotActiveOrNotFoundError, FlowClosingError):
            return


class AwaitUnderwriterDecision(Step[str]):
    """Also waits for the cancel Channel, so a late cancellation still closes the application."""

    def wait_for(self, context: Context, report: str) -> Wait:
        return Wait.any_of(APPLICATION_CANCELED.for_one(), UNDERWRITER_DECIDED.for_one())

    def execute(self, context: Context, report: str) -> StepDecision:
        reasons = APPLICATION_CANCELED.results(context)
        if reasons:
            return force_fail(APPLICATION_CANCELED_PREFIX + reasons[0])
        decisions = UNDERWRITER_DECIDED.results(context)
        return graceful_complete(f"{decisions[0]} after {report}")
```

Example: [examples/python/dex_examples/patterns/cancel-case/loan_application_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/cancel-case/loan_application_flow.py)

## Next

- [Child Flows with Business Identity](https://docs.superdurable.io/design-patterns/subflows/child-flows-with-business-identity.md)
- [Durable Timer](https://docs.superdurable.io/design-patterns/durable-timer.md)
- [SubFlow](https://docs.superdurable.io/concepts/primitives/subflow.md)
- [Channel](https://docs.superdurable.io/concepts/primitives/channel.md)
- [SubFlows](https://docs.superdurable.io/design-patterns/subflows.md)
- [Workflow Patterns evaluation: WCP-20 Cancel Case](https://docs.superdurable.io/correctness-and-expressiveness/workflow-patterns.md#wcp-20)
