Cancel a Case with Its Child Flows
View as MarkdownUse 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.
- A cancel RPC publishes the reason to a cancel Channel. Here
cancelApplicationpublishes toApplicationCanceled. - The Step that starts the SubFlow waits with
AnyOffor the SubFlow or the cancel Channel.RunCreditCheckstarts the credit check with a 7-day Flow timeout. - When the child completes first,
Executereads its result and moves on toAwaitUnderwriterDecision. Any other end of the child, such as a failure or a timeout, fails the parent withForceFail. - When the cancel message wins,
Executereads the child Flow ID withSubFlowID. It stops the child with the ClientStopFlowand closes the parent withForceFail. - Every later Step that waits also waits for the cancel Channel. So a cancel that arrives after the child finished still closes the case.
AwaitUnderwriterDecisionfails 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.
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
// RunCreditCheck waits for its child Flow or a cancellation, whichever comes first.
type RunCreditCheck struct {
dex.StepDefaults
getClient func() *dex.Client
creditCheckFlow *CreditCheckFlow
}
func (step RunCreditCheck) WaitFor(_ dex.Context, application LoanApplication) (*dex.Wait, error) {
timeout := CreditCheckTimeout
request := CreditCheckRequest{
ApplicantID: application.ApplicantID,
ReportDelaySeconds: application.CreditReportDelaySeconds,
}
// The cancel condition comes first: it wins when both are ready.
return dex.AnyOf(
ApplicationCanceled.ForOne(),
dex.SubFlow(step.creditCheckFlow, request, dex.SubFlowOptions{
Timeout: &timeout,
ReusePolicy: dex.RestartSubFlowIfPreviousExitedAbnormally,
}),
), nil
}
func (step RunCreditCheck) Execute(ctx dex.Context, _ LoanApplication) (*dex.StepDecision, error) {
reasons, err := ApplicationCanceled.GetConditionResults(ctx)
if err != nil {
return nil, err
}
if len(reasons) > 0 {
childFlowID, err := dex.SubFlowID(ctx)
/** Waits for its child Flow or a cancellation, whichever comes first. */
static final class RunCreditCheck implements Step<LoanApplication> {
private final ObjectProvider<Client> clientProvider;
RunCreditCheck(final ObjectProvider<Client> clientProvider) {
this.clientProvider = clientProvider;
}
@Override
public Class<LoanApplication> getInputType() {
return LoanApplication.class;
}
@Override
public Wait waitFor(final Context context, final LoanApplication application) {
final CreditCheckRequest request = new CreditCheckRequest(
application.applicantId(), application.creditReportDelaySeconds());
// The cancel condition comes first: it wins when both are ready.
return Wait.anyOf(
applicationCanceled.forOne(),
SubFlow.run(CreditCheckFlow.class, request, SubFlowOptions.newBuilder()
.timeout(CREDIT_CHECK_TIMEOUT)
.reusePolicy(SubFlowReusePolicy.RESTART_IF_PREVIOUS_EXITS_ABNORMALLY)
.build()));
}
@Override
public StepDecision execute(final Context context, final LoanApplication application) {
final List<String> reasons = applicationCanceled.getConditionResults(context);
if (!reasons.isEmpty()) {
Example: examples/java/src/main/java/io/superdurable/dex/patterns/cancelcase/LoanApplicationFlow.java
/** Waits for its child Flow or a cancellation, whichever comes first. */
class RunCreditCheck implements Step<LoanApplication> {
public constructor(
private readonly getClient: () => Client,
private readonly creditCheckFlow: CreditCheckFlow,
) {}
public getStepType(): string {
return "RunCreditCheck";
}
public waitFor(_context: Context, application: LoanApplication): Wait {
// The cancel condition comes first: it wins when both are ready.
return Wait.anyOf(
applicationCanceled.forOne(),
SubFlow.run(
this.creditCheckFlow,
{
applicantId: application.applicantId,
reportDelaySeconds: application.creditReportDelaySeconds,
},
{
timeoutMs: CREDIT_CHECK_TIMEOUT_MS,
reusePolicy: SubFlowReusePolicy.RESTART_IF_PREVIOUS_EXITS_ABNORMALLY,
},
),
);
}
public async execute(context: Context, _application: LoanApplication): Promise<StepDecision> {
Example: examples/typescript/src/patterns/cancel-case/loan-application-flow.ts
/// Waits for its child Flow or a cancellation, whichever comes first.
#[derive(Default)]
pub struct RunCreditCheck {
client: Option<Arc<Client>>,
}
impl RunCreditCheck {
/// Cancels the child; a missing or already closed child counts as stopped.
fn stop_credit_check(&self, child_flow_id: &str) -> HandlerResult<()> {
let client = self
.client
.as_ref()
.ok_or_else(|| HandlerError::new("ClientUnavailable", "the Dex Client is not ready"))?;
match client.stop_flow(
child_flow_id,
StopFlowOptions::cancel().reason("loan application canceled"),
) {
Ok(())
| Err(
SdkError::FlowNotFound { .. }
| SdkError::FlowNotActiveOrNotFound { .. }
| SdkError::FlowClosing { .. },
) => Ok(()),
Err(error) => Err(HandlerError::from_error(error)),
}
}
}
impl Step for RunCreditCheck {
type Input = LoanApplication;
Example: examples/rust/src/control_patterns/cancel_case/flow.rs
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
Executecan be retried, and the child can finish at the same moment. Treat "not found", "not active", and "closing" fromStopFlowas 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
StopFlowon the parent; - the parent's Flow timeout;
- a
ForceFailorForceCompletefrom 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.