Dynamic Parallel Steps
View as MarkdownRun the same Step type once per item, at the same time. Use it when the number of branches is known only at runtime, such as one branch per line of an order.
How it works
InitStep builds one DoWork movement per input item. Dex runs those executions concurrently. Each one sleeps for a random short time, so they finish in any order.
Pass each branch the key of its item, so every result maps back to its input. The active Step executions of one Flow run are limited, and waiting Steps count too. Batch a fan-out that can grow large, or split it across SubFlows.
Core implementation
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)
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/dynamic_parallel_steps_flow.py
type dynamicInit struct {
dex.StepDefaultsNoWaitFor[[]string]
}
func (dynamicInit) GetStepType() string { return "Init" }
func (dynamicInit) Execute(_ dex.Context, items []string) (*dex.StepDecision, error) {
movements := make([]dex.StepMovement, 0, len(items))
for _, item := range items {
movements = append(movements, dex.MovementOf(dynamicWork{}, item))
}
return dex.GoToMany(movements...), nil
}
type dynamicWork struct {
dex.StepDefaultsNoWaitFor[string]
}
func (dynamicWork) GetStepType() string { return "DoWork" }
func (dynamicWork) Execute(_ dex.Context, item string) (*dex.StepDecision, error) {
time.Sleep(time.Duration(50+rand.Intn(450)) * time.Millisecond)
return dex.GracefulComplete(item), 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);
}
}
Example: examples/java/src/main/java/io/superdurable/dex/patterns/parallel/DynamicParallelStepsFlow.java
class DynamicDoWork 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 gracefulComplete(input);
}
}
class DynamicInit 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(DynamicDoWork, index),
),
);
}
}
Example: examples/typescript/src/patterns/parallel/parallel-step-flows.ts
#[derive(Default)]
struct DynamicInit;
impl Step for DynamicInit {
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(&DynamicWork, index)),
))
}
}
#[derive(Default)]
struct DynamicWork;
impl Step for DynamicWork {
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))
}
}
Example: examples/rust/src/patterns/parallel/parallel_step_flows.rs