Advanced: Long-lived Parent
View as MarkdownKeep a fixed pool of worker Steps running while the Flow accepts more requests.
The Init Step publishes the initial requests to RequestChannel and starts N HandleRequest Step executions. Each worker takes the oldest message and moves to the HandleSubFlow Step. That Step starts ExampleSubFlow and waits for it. When the child completes, the Step loops back to the HandleRequest Step. If the Stop RPC has set Stopped to true, it completes gracefully instead. Stopped has no value until the Stop RPC sets it, and only that RPC writes it. A Stop that arrives before Init finishes is therefore kept.
SendRequest checks the Channel size before it publishes. When the Channel reaches the buffer threshold, it returns false. The caller can then back off and retry, and the parent is not overloaded.
Core implementation
DEFAULT_CONCURRENCY = 10
MAX_BUFFERED_REQUESTS = 100
class LongLiveInit(Step[ParentInput]):
def __init__(self, request_channel: Channel[str]) -> None:
self.request_channel = request_channel
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)
concurrency = input.concurrency if input.concurrency > 0 else DEFAULT_CONCURRENCY
return go_to_many(
*(StepMovement.of(LongLiveHandleRequest, None) for _ in range(concurrency))
)
class LongLiveHandleRequest(Step[None]):
def __init__(self, request_channel: Channel[str]) -> None:
self.request_channel = request_channel
def get_step_type(self) -> str:
return "HandleRequest"
def wait_for(self, context: Context, input: None) -> Wait:
return Wait.until(self.request_channel.for_one())
Example: examples/python/dex_examples/patterns/parallel-subflows/advanced_long_live_parent_flow.py
const (
DefaultConcurrency = 10
MaxBufferedRequests = 100
)
var (
LongLiveRequestChannel = dex.DefineChannel[string]("RequestChannel")
Stopped = dex.DefineAttribute[bool]("Stopped")
)
type AdvancedLongLiveParentFlow struct {
dex.FlowDefaults
exampleFlow *ExampleSubFlow
}
func NewAdvancedLongLiveParentFlow(exampleFlow *ExampleSubFlow) *AdvancedLongLiveParentFlow {
return &AdvancedLongLiveParentFlow{exampleFlow: exampleFlow}
}
func (flow *AdvancedLongLiveParentFlow) GetSteps() []dex.StepDef {
return []dex.StepDef{
dex.DefineStartStep(longLiveInit{}),
dex.DefineStep(longLiveHandleRequest{}),
dex.DefineStep(longLiveHandleSubFlow{exampleFlow: flow.exampleFlow}),
}
}
func (flow *AdvancedLongLiveParentFlow) GetRPCs() []dex.RPCDef {
return []dex.RPCDef{
dex.DefineRPC(flow.SendRequest, nil),
Example: examples/go/patterns/parallel-subflows/advanced_long_live_parent_flow.go
public class AdvancedLongLiveParentFlow 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<Boolean> stopped = Attribute.define("Stopped", Boolean.class);
private final InitStep initStep = new InitStep();
private final HandleRequest handleRequestStep = new HandleRequest();
private final HandleSubFlow handleSubFlowStep;
public AdvancedLongLiveParentFlow(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, stopped);
}
@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 LongLiveInit implements Step<ParentInput> {
public readonly inputCodec = parentInputCodec;
public getStepType(): string {
return "Init";
}
public execute(context: Context, input: ParentInput): StepDecision {
for (const request of input.requests) requestChannel.publish(context, request);
const concurrency = input.concurrency > 0 ? input.concurrency : DEFAULT_CONCURRENCY;
return goToMany(
...Array.from({ length: concurrency }, () =>
StepMovement.of(LongLiveHandleRequest, undefined),
),
);
}
}
class LongLiveHandleRequest implements Step<void> {
public readonly inputCodec = voidCodec;
public getStepType(): string {
return "HandleRequest";
}
public waitFor(_context: Context, _input: void): Wait {
Example: examples/typescript/src/patterns/parallel-subflows/parallel-subflows.ts
const DEFAULT_CONCURRENCY: usize = 10;
const MAX_BUFFERED_REQUESTS: usize = 100;
static REQUEST_CHANNEL: LazyLock<Channel<String>> =
LazyLock::new(|| Channel::new("RequestChannel"));
static STOPPED: LazyLock<Attribute<bool>> = LazyLock::new(|| Attribute::new("Stopped"));
pub(super) const SEND_LONG_LIVE_REQUEST: Rpc<String, bool> = Rpc::new("SendLongLiveRequest");
pub(super) const STOP_LONG_LIVE_FLOW: Rpc<(), ()> = Rpc::new("StopLongLiveFlow");
#[derive(Default)]
pub struct AdvancedLongLiveParentFlow {
init: LongLiveInit,
handle_request: LongLiveHandleRequest,
handle_sub_flow: LongLiveHandleSubFlow,
}
impl AdvancedLongLiveParentFlow {
fn send_request(
&self,
context: &mut Context,
request: String,
) -> HandlerResult<RpcResult<bool>> {
if REQUEST_CHANNEL.size(context)? >= MAX_BUFFERED_REQUESTS {
return Ok(RpcResult::new(false));
}
REQUEST_CHANNEL.publish(context, request)?;
Ok(RpcResult::new(true))
}
Example: examples/rust/src/patterns/parallel_subflows/flow.rs
Close the intake
The runnable examples above show the basic variant: a later Step starts each child, and a Stop RPC ends the workers after their children finish. They have no closable intake, shared admission lock, or returned-request reply. A parent that closes its intake for good also ends its idle workers and hands back its queued requests:
- A close RPC marks the intake closed and publishes a close message. From then on, the admission RPC rejects new requests, so callers can resubmit to a new parent run.
- Both RPCs and the worker's
ExecuteinHandleRequestdeclare the sameintakeClosedlock. - Each worker owns the request it consumed. Under that lock it only commits its next move: to
HandleChild, which holds no lock and starts the child, or, after the close, toReturnRequest, which holds no lock and sends the returned request back through an idempotent path keyed by the request, such as a reply to its submitter, then takes the next request. The RPCs take the lock, so no worker calls another system or Flow while holding it. A queued request is never dropped or handed back twice. - A close Step waits for the close message and completes gracefully.
- Channel conditions still win over the graceful completion condition, so after the close, workers keep taking and returning queued requests. Once the queue is empty, idle workers wake through the graceful completion condition and end their branch. Workers with a running child finish it first.
- The admission RPC checks the Channel size for its limit. Every RPC receives Channel sizes, so the parent keeps no separate waiting counter.
- The graceful completion condition needs SDK and server support; see Graceful completion requests. Without it, the close Step publishes one wake message per worker, and each worker also waits for that wake Channel, declared after the request Channel.
These steps describe the closable-intake variant. Its extra Steps, such as CloseIntake, are not in the graph above.
sendRequestholds theintakeClosedlock. It accepts a request while the intake is open and the current queue length is below the limit. It queues the request in theRequestsChannel.- Each worker in
HandleRequestwaits for a queued request or for a graceful completion request. - A worker that took a request holds the
intakeClosedlock and commits its move toHandleChild, which starts the child without the lock. After the close, it moves toReturnRequestinstead, which sends the returned request without the lock and then waits for the next one. - A worker whose wait ended through the graceful completion request, with no request consumed, ends its branch.
closeIntakeholds theintakeClosedlock, marks the intake closed, and publishes a close message.CloseIntakereceives it and completes the Flow gracefully.