Skip to main content

First-Win Parallel Steps

Use the first completed concurrent Step and cancel the remaining siblings.

Definition graph

FirstWinParallelStepsFlow

Valid

python · examples/python/dex_examples/patterns/parallel/first_win_parallel_steps_flow.py

InitStep starts multiple DoWorkStep executions. Each worker sleeps for a random short duration, creating a real race. The first execution to return a decision selects its sibling DoWorkStep executions for cancellation. The Flow keeps the first result and stops work that can no longer affect the outcome.

Core implementation

The cancellation selector targets sibling executions of the same Step type, not unrelated branches.

class DoWorkStep(Step[int]):
async def execute( # type: ignore[override]
self, context: AsyncContext, input: int
) -> StepDecision:
await asyncio.sleep(random.uniform(0.05, 0.5))
return graceful_complete(input).with_canceling_sibling_steps(DoWorkStep)


class InitStep(Step[int]):
def execute(self, context: Context, input: int) -> StepDecision:
return go_to_many(
*(StepMovement.of(DoWorkStep, index) for index in range(input))
)

Example: examples/python/dex_examples/patterns/parallel/first_win_parallel_steps_flow.py