Advanced: Multiple Parents with Partitioning
View as MarkdownSpread requests across several parent Flow IDs, so the total number of running SubFlows can exceed one parent's concurrency limit.
Use a stable partition key, such as a request ID hash modulo the number of parents. Every request with the same key reaches the same parent. Each parent applies its own Channel buffer limit and SubFlow concurrency limit. Adding parents adds total capacity, and no single Flow grows without limit.
Changing the number or order of parents sends some keys to a different parent. If each key must keep reaching the same parent while you scale, use a versioned parent set or consistent hashing.
Core implementation
SubmitStep first invokes the RPC of the selected parent. If that parent does not exist or is no longer running, SubmitStep starts it with the request as its initial input. The parent's Init publishes that input to RequestChannel, so the request is not lost. If another submitter starts the parent first, the start fails with FlowAlreadyStarted and SubmitStep retries. Its next execution invokes the RPC on the running parent.
async def enqueue_request(client, parent_flow, parent_id: str, request: str) -> bool:
try:
return await client.invoke_rpc(parent_flow.send_request, parent_id, request)
except FlowNotActiveOrNotFoundError:
await client.start_flow(
parent_flow,
parent_id,
ParentInput([request], DEFAULT_CONCURRENCY),
StartFlowOptions(id_reuse_policy=IdReusePolicy.ALLOW_IF_NOT_RUNNING),
)
return True
def partition(request: str, partitions: int) -> int:
hash_value = 2_166_136_261
for byte in request.encode():
hash_value ^= byte
hash_value = hash_value * 16_777_619 & 0xFFFFFFFF
return hash_value % partitions
Example: examples/python/dex_examples/patterns/parallel-subflows/submit_request_flow.py
func enqueueRequest(ctx context.Context, client *dex.Client, parentFlow *AdvancedShortLiveParentFlow, parentID string, request string) (bool, error) {
accepted, err := invokeRequest(ctx, client, parentFlow, parentID, request)
if err == nil { return accepted, nil }
var inactive *dex.FlowNotActiveOrNotFoundError
if !errors.As(err, &inactive) { return false, err }
_, err = client.StartFlow(ctx, parentFlow, parentID, ParentInput{
Requests: []string{request}, Concurrency: DefaultConcurrency,
}, dex.StartFlowOptions{IDReusePolicy: dex.IDReuseAllowIfNotRunning})
if err != nil { return false, err }
return true, nil
}
func partition(request string, partitions int) int {
hash := uint32(2_166_136_261)
for _, value := range []byte(request) {
hash ^= uint32(value)
hash *= 16_777_619
}
return int(hash) % partitions
}
Example: examples/go/patterns/parallel-subflows/submit_request_flow.go
private boolean enqueueRequest(final String parentId, final String request) {
final Client client = clientProvider.getObject();
final AdvancedShortLiveParentFlow stub =
client.newRpcStub(AdvancedShortLiveParentFlow.class, parentId);
try {
return client.invokeRPC(stub::sendRequest, request);
} catch (final FlowNotActiveOrNotFoundException inactive) {
client.startFlow(
parentFlow,
parentId,
new ParentInput(new String[] {request}, AdvancedShortLiveParentFlow.DEFAULT_CONCURRENCY),
StartFlowOptions.newBuilder().idReusePolicy(IdReusePolicy.ALLOW_IF_NOT_RUNNING).build());
return true;
}
}
private static int partition(final String request, final int partitions) {
int hash = 0x811c9dc5;
for (final byte value : request.getBytes(StandardCharsets.UTF_8)) {
hash ^= Byte.toUnsignedInt(value);
hash *= 0x01000193;
}
return Integer.remainderUnsigned(hash, partitions);
}
Example: examples/java/src/main/java/io/superdurable/dex/patterns/parallelsubflows/SubmitRequestFlow.java
async function enqueueRequest(client: Client, parentFlow: AdvancedShortLiveParentFlow, parentId: string, request: string): Promise<boolean> {
try {
return await client.invokeRPC(parentFlow.sendRequest, parentId, request);
} catch (error) {
if (!isFlowMissingOrInactive(error)) throw error;
}
await client.startFlow(
parentFlow,
parentId,
{ requests: [request], concurrency: DEFAULT_CONCURRENCY },
{ idReusePolicy: IdReusePolicy.ALLOW_IF_NOT_RUNNING },
);
return true;
}
function partition(request: string, partitions: number): number {
let hash = 2_166_136_261;
for (const byte of new TextEncoder().encode(request)) {
hash ^= byte;
hash = Math.imul(hash, 16_777_619) >>> 0;
}
return hash % partitions;
}
Example: examples/typescript/src/patterns/parallel-subflows/parallel-subflows.ts
fn enqueue_request(client: &Client, parent_id: &str, request: String) -> HandlerResult<bool> {
match client.invoke_rpc(parent_id, SEND_SHORT_LIVE_REQUEST, request.clone()) {
Ok(accepted) => Ok(accepted),
Err(SdkError::FlowNotFound { .. } | SdkError::FlowNotActiveOrNotFound { .. }) => {
let parent = AdvancedShortLiveParentFlow::default();
let input = ParentInput { requests: vec![request.clone()], concurrency: DEFAULT_CONCURRENCY };
let options = StartFlowOptions::new().id_reuse_policy(IdReusePolicy::AllowIfNotRunning);
client.start_flow_with_options(&parent, parent_id, input, options).map_err(HandlerError::from_error)?;
Ok(true)
}
Err(error) => Err(HandlerError::from_error(error)),
}
}
fn partition(request: &str, partitions: usize) -> usize {
let mut hash = 2_166_136_261_u32;
for byte in request.bytes() {
hash ^= u32::from(byte);
hash = hash.wrapping_mul(16_777_619);
}
hash as usize % partitions
}
Example: examples/rust/src/patterns/parallel_subflows/flow.rs