Await Parallel Steps
View as MarkdownContinue only after every parallel branch has finished. Use it when a later Step needs the results of all branches, such as combining them into one reply.
How the Join works
InitStep forks one round of the parallel-complete Join. The fork starts one DoWork execution per item and the Await Step in the same decision. All of them get one round token: the round key and the branch count. Each DoWork sleeps for a random short time, then ends its branch and reports its index. Await waits in WaitFor for every branch of the round.
A Join is a named ChannelMap of branch results. It counts the results that branches report, rather than watching the branch Steps. Results are durable, so a result reported before Await starts waiting still counts. Results count only toward their own round. The join Step's wait is an ordinary condition, so it combines with a Timer.
When the work runs in child Flows, a SubFlow wait with AllOf is the native join.
Core implementation
@dataclass(frozen=True)
class WorkItem:
index: int
round: JoinRound
def build_work_item(index: int) -> Callable[[JoinRound], StepMovement[WorkItem]]:
return lambda join_round: StepMovement.of(DoWork, WorkItem(index, join_round))
class DoWork(Step[WorkItem]):
def __init__(self, work_completed: Join[int]) -> None:
self.work_completed = work_completed
async def execute( # type: ignore[override]
self, context: AsyncContext, input: WorkItem
) -> StepDecision:
await asyncio.sleep(random.uniform(0.05, 0.5))
return self.work_completed.end_branch(context, input.round, input.index)
class Await(Step[JoinRound]):
def __init__(self, work_completed: Join[int]) -> None:
self.work_completed = work_completed
def wait_for(self, context: Context, input: JoinRound) -> Wait:
return Wait.until(self.work_completed.for_all_branches(input))
def execute(self, context: Context, input: JoinRound) -> StepDecision:
return graceful_complete(
len(self.work_completed.branch_results(context, input))
)
class InitStep(Step[int]):
def __init__(self, work_completed: Join[int]) -> None:
self.work_completed = work_completed
def execute(self, context: Context, input: int) -> StepDecision:
return go_to_many(
*self.work_completed.fork(
context,
[build_work_item(index) for index in range(input)],
lambda join_round: StepMovement.of(Await, join_round),
)
)
Example: examples/python/dex_examples/patterns/parallel/await_parallel_steps_flow.py
var WorkCompletedJoin = dex.DefineJoin[int]("parallel-complete")
type awaitInit struct{ dex.StepDefaultsNoWaitFor[int] }
func (awaitInit) GetStepType() string { return "Init" }
func (awaitInit) Execute(ctx dex.Context, count int) (*dex.StepDecision, error) {
branchBuilders := make([]func(dex.JoinRound) dex.StepMovement, 0, count)
for index := range count {
branchBuilders = append(branchBuilders, func(round dex.JoinRound) dex.StepMovement {
return dex.MovementOf(awaitWork{}, WorkItem{Index: index, Round: round})
})
}
movements, err := WorkCompletedJoin.Fork(ctx, branchBuilders, func(round dex.JoinRound) dex.StepMovement {
return dex.MovementOf(awaitStep{}, round)
})
if err != nil {
return nil, err
}
return dex.GoToMany(movements...), nil
}
// WorkItem is the input of one DoWork branch.
type WorkItem struct {
Index int `json:"index"`
Round dex.JoinRound `json:"round"`
}
type awaitWork struct {
dex.StepDefaultsNoWaitFor[WorkItem]
public final Join<Integer> workCompleted = Join.define("parallel-complete", Integer.class);
/** One worker: its index and the Join round it reports to. */
public record WorkItem(int index, JoinRound round) {
}
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 List<Function<JoinRound, StepMovement<?>>> workers =
new ArrayList<Function<JoinRound, StepMovement<?>>>();
for (int index = 0; index < count; index++) {
final int workIndex = index;
workers.add(round -> StepMovement.of(DoWork.class, new WorkItem(workIndex, round)));
}
return StepDecision.goToMany(workCompleted.fork(
context, workers, round -> StepMovement.of(Await.class, round)));
}
}
final class DoWork implements Step<WorkItem> {
@Override
public Class<WorkItem> getInputType() {
return WorkItem.class;
}
Example: examples/java/src/main/java/io/superdurable/dex/patterns/parallel/AwaitParallelStepsFlow.java
const workCompleted = new Join("parallel-complete", doubleCodec);
interface WorkItem {
readonly index: number;
readonly round: JoinRound;
}
class AwaitDoWork implements Step<WorkItem> {
public getStepType(): string {
return "DoWork";
}
public async execute(context: Context, item: WorkItem): Promise<StepDecision> {
await new Promise<void>((resolve) => {
setTimeout(resolve, 50 + Math.floor(Math.random() * 450));
});
return workCompleted.endBranch(context, item.round, item.index);
}
}
class Await implements Step<JoinRound> {
public readonly inputCodec = joinRoundCodec;
public getStepType(): string {
return "Await";
}
public waitFor(_context: Context, round: JoinRound): Wait {
return Wait.until(workCompleted.forAllBranches(round));
}
public execute(context: Context, round: JoinRound): StepDecision {
return gracefulComplete(workCompleted.branchResults(context, round).length);
}
}
class AwaitInit implements Step<number> {
public readonly inputCodec = doubleCodec;
public getStepType(): string {
return "Init";
}
public execute(context: Context, count: number): StepDecision {
return goToMany(
...workCompleted.fork(
context,
Array.from({ length: count }, (_, index) => (round: JoinRound) =>
StepMovement.of(AwaitDoWork, { index, round }),
),
(round) => StepMovement.of(Await, round),
),
);
}
}
Example: examples/typescript/src/patterns/parallel/parallel-step-flows.ts
#[derive(Default)]
struct AwaitInit;
impl Step for AwaitInit {
type Input = usize;
fn step_type(&self) -> &'static str {
"InitStep"
}
fn execute(&self, context: &mut Context, count: usize) -> HandlerResult<StepDecision> {
let branches = (0..count)
.map(|index| {
Box::new(move |round: &JoinRound| {
StepMovement::to(
&AwaitWork,
WorkItem {
index,
round: round.clone(),
},
)
}) as Box<dyn FnOnce(&JoinRound) -> StepMovement>
})
.collect();
let movements =
COMPLETE.fork(context, branches, |round| StepMovement::to(&Await, round))?;
Ok(StepDecision::go_to_many(movements))
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct WorkItem {
pub index: usize,
pub round: JoinRound,
Example: examples/rust/src/patterns/parallel/parallel_step_flows.rs
Rules and pitfalls
- Start the join Step in the same fork as the branches. With the implicit round key, fork a Join at most once in one Step method. Explicit round keys and RPC forks are in the Join reference.
- Each branch reports exactly one result per round, on every exit path that leaves the Flow open. That includes the Step that a failure route goes to. A branch that never reports leaves the join waiting forever. A branch that reports twice counts twice.
- A branch of several Steps passes the round token to its last Step, and only that Step reports.
- Only the join Step waits for its round; branches move on.
- A canceled branch stays silent, so cancel the join together with the branches it waits for, or wait for the join and a Timer with
AnyOf. - Read a round's pending results through the Join's ChannelMap, for example in an RPC. Never publish to it directly.
- A join Step canceled after its wait consumed results follows the canceled Step rule for those results.
Wait for some branches
The join Step can also wait for the first branch or for n branches. Then it either cancels the other branches or lets them run on.
To cancel them, the join Step returns a decision that cancels its sibling Steps. Fork starts the branches and the join together, so the siblings are the Steps that fork started. They do not include later Steps of a multi-Step branch, and an RPC fork needs a cancel by Step type; see the Join reference. Each branch handles its Step's cancellation signal as in First-Win Parallel Steps. A cancelling join's round is never reset, because its canceled branches never report. In a loop, the next round forks a new round directly.
When the other branches run on, their results arrive later. In a loop, the next round's split Step resets the previous round first: its WaitFor waits for the remaining results, and its Execute can read them. Then it forks the next round. Without a reset, late results stay pending until the Flow closes.
The Join reference has the edge cases. The Workflow Patterns evaluation links runnable examples of both shapes.