Skip to main content

First-Win Parallel Steps

View as Markdown

Run several Steps at the same time, keep the first result, and cancel the rest. Use it when the first acceptable result is enough, such as the fastest of several quote services.

How it works

InitStep starts several DoWork executions. Each one sleeps for a random short time, so any of them can finish first. The first decision that Dex commits keeps its result and cancels the sibling DoWork executions.

Each branch is its own Step execution, with its own retries, failure route, and durable result. Use separate Steps or child Flows when Dex must retry, cancel, or record results for individual branches. With in-process concurrency inside one Execute, such as Promise.any, asyncio tasks, or threads, Dex retries the whole Execute, so all its calls run again together. It fits idempotent reads that succeed or retry together.

Core implementation

Each DoWork completes and cancels its sibling DoWork executions in one decision.

first_win_parallel_steps_flow.pyPython
class DoWork(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(DoWork)


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

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

Rules and pitfalls

  • The cancellation selector cancels only sibling executions of the same Step type. Other branches keep running.
  • Each losing execution watches its Step's cancellation signal. It passes the signal to calls that accept cancellation. Otherwise it uses short call timeouts and checks the signal between calls.
  • Cancellation is cooperative, and it does not reverse an external effect that already happened. Withdraw a reservation that already took effect with a separate, bounded, idempotent call. A reservation that must be released uses an expiring lease or a durable compensation branch keyed by the business ID.

Next