First-Win Parallel Steps
View as MarkdownRun 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.
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
type firstWinInit struct{ dex.StepDefaultsNoWaitFor[int] }
func (firstWinInit) GetStepType() string { return "Init" }
func (firstWinInit) Execute(_ dex.Context, count int) (*dex.StepDecision, error) {
movements := make([]dex.StepMovement, 0, count)
for index := 0; index < count; index++ {
movements = append(movements, dex.MovementOf(firstWinWork{}, index))
}
return dex.GoToMany(movements...), nil
}
type firstWinWork struct{ dex.StepDefaultsNoWaitFor[int] }
func (firstWinWork) GetStepType() string { return "DoWork" }
func (firstWinWork) Execute(_ dex.Context, index int) (*dex.StepDecision, error) {
time.Sleep(time.Duration(50+rand.Intn(450)) * time.Millisecond)
return dex.GracefulComplete(index).CancelSiblingSteps(firstWinWork{}), nil
}
final class InitStep implements Step<Integer> {
@Override
public Class<Integer> getInputType() {
return Integer.class;
}
@Override
public StepDecision execute(final Context context, final Integer count) {
final StepMovement<?>[] movements = new StepMovement<?>[count];
for (int index = 0; index < count; index++) {
movements[index] = StepMovement.of(DoWork.class, index);
}
return StepDecision.goToMany(movements);
}
}
final class DoWork implements Step<Integer> {
@Override
public Class<Integer> getInputType() {
return Integer.class;
}
@Override
public StepDecision execute(final Context context, final Integer input) {
try {
Thread.sleep(ThreadLocalRandom.current().nextInt(50, 500));
} catch (final InterruptedException error) {
Thread.currentThread().interrupt();
throw new IllegalStateException(error);
}
return StepDecision.gracefulComplete(input)
.withCancelingSiblingSteps(DoWork.class);
}
}
Example: examples/java/src/main/java/io/superdurable/dex/patterns/parallel/FirstWinParallelStepsFlow.java
class FirstWinDoWork implements Step<number> {
public readonly inputCodec = doubleCodec;
public getStepType(): string {
return "DoWork";
}
public async execute(_context: Context, input: number): Promise<StepDecision> {
await new Promise<void>((resolve) => {
setTimeout(resolve, 50 + Math.floor(Math.random() * 450));
});
return withCancelingSiblingSteps(gracefulComplete(input), FirstWinDoWork);
}
}
class FirstWinInit implements Step<number> {
public readonly inputCodec = doubleCodec;
public getStepType(): string {
return "Init";
}
public execute(_context: Context, count: number): StepDecision {
return goToMany(
...Array.from({ length: count }, (_, index) =>
StepMovement.of(FirstWinDoWork, index),
),
);
}
}
Example: examples/typescript/src/patterns/parallel/parallel-step-flows.ts
#[derive(Default)]
struct FirstWinInit;
impl Step for FirstWinInit {
type Input = usize;
fn step_type(&self) -> &'static str {
"InitStep"
}
fn execute(&self, _: &mut Context, count: usize) -> HandlerResult<StepDecision> {
Ok(StepDecision::go_to_many(
(0..count).map(|index| StepMovement::to(&FirstWinWork, index)),
))
}
}
#[derive(Default)]
struct FirstWinWork;
impl Step for FirstWinWork {
type Input = usize;
fn step_type(&self) -> &'static str {
"DoWork"
}
fn execute(&self, _: &mut Context, input: usize) -> HandlerResult<StepDecision> {
thread::sleep(Duration::from_millis(fastrand::u64(50..500)));
Ok(StepDecision::graceful_complete(input).cancel_sibling_step(&FirstWinWork))
}
}
Example: examples/rust/src/patterns/parallel/parallel_step_flows.rs
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.