Advanced: Short-lived Parent
View as MarkdownDrain the queued requests, then complete the parent without losing a request that arrives at the end.
The Init Step fills RequestChannel, initializes CurrSubFlowNum, and starts N workers. CurrSubFlowNum counts the running SubFlows. The HandleRequest Step's Execute locks it and adds one. The HandleSubFlow Step's Execute takes the same lock and subtracts one.
The last active worker returns ForceCompleteIfChannelsEmpty. Dex then checks RequestChannel and completes the Flow only if the Channel is empty. If an RPC has published a request first, Dex schedules another HandleRequest Step instead. The check and the completion happen together, so no request can arrive between them. Checking the Channel size in application code cannot give this guarantee.
Core implementation
DEFAULT_CONCURRENCY = 10
MAX_BUFFERED_REQUESTS = 100
class ShortLiveInit(Step[ParentInput]):
def __init__(
self,
request_channel: Channel[str],
curr_subflow_num: Attribute[int],
) -> None:
self.request_channel = request_channel
self.curr_subflow_num = curr_subflow_num
def get_step_type(self) -> str:
return "Init"
def execute(self, context: Context, input: ParentInput) -> StepDecision:
for request in input.requests:
self.request_channel.publish(context, request)
self.curr_subflow_num.set(context, 0)
concurrency = input.concurrency if input.concurrency > 0 else DEFAULT_CONCURRENCY
return go_to_many(
*(StepMovement.of(ShortLiveHandleRequest, None) for _ in range(concurrency))
)
class ShortLiveHandleRequest(Step[None]):
def __init__(
self,
request_channel: Channel[str],
Example: examples/python/dex_examples/patterns/parallel-subflows/advanced_short_live_parent_flow.py
const (
DefaultConcurrency = 10
MaxBufferedRequests = 100
)
var (
RequestChannel = dex.DefineChannel[string]("RequestChannel")
CurrSubFlowNum = dex.DefineAttribute[int]("CurrSubFlowNum")
)
type AdvancedShortLiveParentFlow struct {
dex.FlowDefaults
exampleFlow *ExampleSubFlow
}
func NewAdvancedShortLiveParentFlow(exampleFlow *ExampleSubFlow) *AdvancedShortLiveParentFlow {
return &AdvancedShortLiveParentFlow{exampleFlow: exampleFlow}
}
func (flow *AdvancedShortLiveParentFlow) GetSteps() []dex.StepDef {
return []dex.StepDef{
dex.DefineStartStep(shortLiveInit{}),
dex.DefineStep(shortLiveHandleRequest{}),
dex.DefineStep(shortLiveHandleSubFlow{exampleFlow: flow.exampleFlow}),
}
}
func (flow *AdvancedShortLiveParentFlow) GetRPCs() []dex.RPCDef {
return []dex.RPCDef{dex.DefineRPC(flow.SendRequest, nil)}
}
Example: examples/go/patterns/parallel-subflows/advanced_short_live_parent_flow.go
public class AdvancedShortLiveParentFlow implements Flow<ParentInput> {
public static final int DEFAULT_CONCURRENCY = 10;
public static final int MAX_BUFFERED_REQUESTS = 100;
public final Channel<String> requestChannel = Channel.define("RequestChannel", String.class);
public final Attribute<Integer> currSubFlowNum = Attribute.define("CurrSubFlowNum", Integer.class);
private final InitStep initStep = new InitStep();
private final HandleRequest handleRequestStep = new HandleRequest();
private final HandleSubFlow handleSubFlowStep;
public AdvancedShortLiveParentFlow(final ExampleSubFlow exampleSubFlow) {
handleSubFlowStep = new HandleSubFlow(exampleSubFlow);
}
@Override
public StepList<ParentInput> getSteps() {
return StepList.startStep(initStep).otherSteps(handleRequestStep, handleSubFlowStep);
}
@Override
public PersistenceSchema getPersistenceSchema() {
return PersistenceSchema.of(requestChannel, currSubFlowNum);
}
@RPC
public RPCResult<Boolean> sendRequest(final Context context, final String request) {
if (requestChannel.size(context) >= MAX_BUFFERED_REQUESTS) {
return RPCResult.of(false);
}
const DEFAULT_CONCURRENCY = 10;
const MAX_BUFFERED_REQUESTS = 100;
const requestChannel = new Channel("RequestChannel", stringCodec);
class ShortLiveInit implements Step<ParentInput> {
public readonly inputCodec = parentInputCodec;
public constructor(private readonly flow: AdvancedShortLiveParentFlow) {}
public getStepType(): string {
return "Init";
}
public execute(context: Context, input: ParentInput): StepDecision {
for (const request of input.requests) requestChannel.publish(context, request);
this.flow.currSubFlowNum.set(context, 0);
const concurrency = input.concurrency > 0 ? input.concurrency : DEFAULT_CONCURRENCY;
return goToMany(
...Array.from({ length: concurrency }, () =>
StepMovement.of(ShortLiveHandleRequest, undefined),
),
);
}
}
class ShortLiveHandleRequest implements Step<void> {
public readonly inputCodec = voidCodec;
public constructor(private readonly flow: AdvancedShortLiveParentFlow) {}
Example: examples/typescript/src/patterns/parallel-subflows/parallel-subflows.ts
#[derive(Default)]
struct ShortLiveHandleSubFlow;
impl Step for ShortLiveHandleSubFlow {
type Input = String;
fn step_type(&self) -> &'static str {
"HandleSubFlowStep"
}
fn options(&self) -> StepOptions<Self::Input> {
StepOptions::new().execute_lock(CURR_SUB_FLOW_NUM.lock())
}
fn wait_for(&self, _context: &mut Context, request: String) -> HandlerResult<Wait> {
let child = ExampleSubFlow::default();
Ok(Wait::until(
SubFlow::run(&child, request).map_err(HandlerError::from_error)?,
))
}
fn execute(&self, context: &mut Context, _request: String) -> HandlerResult<StepDecision> {
let current = CURR_SUB_FLOW_NUM.get(context)?.unwrap_or(1) - 1;
CURR_SUB_FLOW_NUM.set(context, current)?;
if current == 0 {
return Ok(StepDecision::force_complete_if_channels_empty(
(),
StepMovement::to(&ShortLiveHandleRequest, ()),
[REQUEST_CHANNEL.when_empty()],
));
}
Ok(StepDecision::go_to(&ShortLiveHandleRequest, ()))
}
}
Example: examples/rust/src/patterns/parallel_subflows/flow.rs
Empty batches and early requests
The example is simplified: its RPC can publish as soon as the Flow starts, and it starts the workers even for an empty batch. A parent that must handle an empty batch adds an intake gate:
- The intake opens only when the first Step has queued the start batch. The RPC reads the gate and rejects a request before that. An empty start batch then completes at once, because no request can be waiting.
- The Steps that change the child count lock the gate's Attribute. Keep the RPC free of locks.
- The buffer limit is a soft limit. Concurrent RPCs can read the same size, and the Channel size counts only queued requests, not work already taken. A hard limit needs atomic admission, such as a locked reservation. Check the start batch against the limit where the Flow is started.
- When the caller must confirm each request was handled, the consuming Step records the request's business ID in the same commit, and the caller reads that record; see Confirm that a message was handled.
These steps describe the variant with an intake gate. Its extra Step, AdmitBatch, is not in the graph above.
AdmitBatchtakes the start batch while it holds the lock on the admission Attribute. An empty batch returnsGracefulComplete, because the intake never opened.- Otherwise
AdmitBatch, in one commit, queues each request in theRequestsChannel, opens the intake, sets the active child count to 0, and starts the workers inHandleRequest. sendRequestreads the admission Attribute without a lock. It accepts a request only while the intake is open and the current queue length is below the limit. It queues the request in the same Channel.