Skip to main content

Cancel a Case with Its Child Flows

View as Markdown

Use this pattern when canceling a Flow must also stop the child Flows it started. A SubFlow keeps running when its parent completes, fails, times out, or is stopped, so the parent must stop each child before it closes.

How it works

The example is a loan application that runs its credit check as a child Flow. When the applicant withdraws, the application closes and the credit check stops.

  1. A cancel RPC publishes the reason to a cancel Channel. Here cancelApplication publishes to ApplicationCanceled.
  2. The Step that starts the SubFlow waits with AnyOf for the SubFlow or the cancel Channel. RunCreditCheck starts the credit check with a 7-day Flow timeout.
  3. When the child completes first, Execute reads its result and moves on to AwaitUnderwriterDecision. Any other end of the child, such as a failure or a timeout, fails the parent with ForceFail.
  4. 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.
  5. Every later Step that waits also waits for the cancel Channel. So a cancel that arrives after the child finished still closes the case. AwaitUnderwriterDecision fails the application on a cancel and completes it on the underwriter's decision.

Core implementation

In RunCreditCheck, notice that the cancel Channel wins over the child's SubFlow condition when both are ready, whatever their order, and that stopCreditCheck treats a child that is already gone as stopped.

loan_application_flow.pyPython
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]

Example: examples/python/dex_examples/patterns/cancel-case/loan_application_flow.py

Late and competing cancels

  • A pending cancel wins over a normal completion in every wait. Declare the cancel Channel before the decision Channel, because among ready Channels the first declared one wins. A ready Channel already wins over a ready SubFlow; see the AnyOf order in Condition results.
  • A fallback or deadline Timer can win, and a cancel can still commit after it, before the Timer branch runs. Make the Timer branch handle a cancel 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 Response Window.
  • Once the decision is final, close the Flow without consuming the cancel Channel. A cancel that arrives after the last Step consumed its decision message, or after the Flow closed, cannot change the outcome. A close that drains the cancel Channel and falls back to a cancel path would let a late cancel override the decision.

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. The example uses stoppedCreditCheckFlowId.

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. If the first Step that sees a cancel message closes the Flow, its ForceFail cancels the other Steps before they stop their children.

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.

So clients cancel a case through the cancel RPC, not StopFlow. When a child must end by a limit known at start, set its Flow timeout, so a child that is never stopped still ends.

Next