---
title: "Advanced: Short-lived Parent"
description: "Drain the queued requests, then complete the parent without losing a request that arrives at the end."
canonical_url: "https://docs.superdurable.io/design-patterns/subflows/short-lived-parent/"
source: "docs/content/design-patterns/subflows/short-lived-parent.mdx"
locale: "en"
language: "python"
---

> Index of every page for AI agents: https://docs.superdurable.io/llms.txt

# Advanced: Short-lived Parent

Code on this page is in Python. Other languages: [Go](https://docs.superdurable.io/design-patterns/subflows/short-lived-parent.go.md) · [Java](https://docs.superdurable.io/design-patterns/subflows/short-lived-parent.java.md) · [TypeScript](https://docs.superdurable.io/design-patterns/subflows/short-lived-parent.typescript.md) · [Rust](https://docs.superdurable.io/design-patterns/subflows/short-lived-parent.rust.md)

Drain the queued requests, then complete the parent without losing a request that arrives at the end.

**Flow graph: AdvancedShortLiveParentFlow**

**Steps**

1. `Init` (start Step): Queue the requests and start the request handlers. Next: `HandleRequest`. Writes `CurrSubFlowNum`; publishes to `RequestChannel`.
2. `HandleRequest`: Take the next queued request and count it as running. Next: `HandleSubFlow`. Reads `CurrSubFlowNum`, `RequestChannel`; locks `CurrSubFlowNum`; writes `CurrSubFlowNum`.
3. `HandleSubFlow`: Run a child Flow for the request, then complete once no work remains. Next: `HandleRequest`. Reads `CurrSubFlowNum`; locks `CurrSubFlowNum`; writes `CurrSubFlowNum`.

**RPCs**

- `send_request`: Reads `RequestChannel`; publishes to `RequestChannel`.

Example: [examples/python/dex_examples/patterns/parallel-subflows/advanced_short_live_parent_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/parallel-subflows/advanced_short_live_parent_flow.py)

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

**Python**

```python
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],
        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 "HandleRequest"

    def get_step_options(self) -> StepOptions:
        return StepOptions(execute_lock_attributes=(self.curr_subflow_num.lock(),))

    def wait_for(self, context: Context, input: None) -> Wait:
        return Wait.until(self.request_channel.for_one())

    def execute(self, context: Context, input: None) -> StepDecision:
        request = self.request_channel.results(context)[0]
        self.curr_subflow_num.set(context, (self.curr_subflow_num.get(context) or 0) + 1)
        return go_to(ShortLiveHandleSubFlow, request)


class ShortLiveHandleSubFlow(Step[str]):
    def __init__(
        self,
        example_subflow: ExampleSubFlow,
        request_channel: Channel[str],
        curr_subflow_num: Attribute[int],
    ) -> None:
        self.example_subflow = example_subflow
        self.request_channel = request_channel
        self.curr_subflow_num = curr_subflow_num

    def get_step_type(self) -> str:
        return "HandleSubFlow"

    def get_step_options(self) -> StepOptions:
        return StepOptions(execute_lock_attributes=(self.curr_subflow_num.lock(),))

    def wait_for(self, context: Context, request: str) -> Wait:
        return Wait.until(SubFlow.run(self.example_subflow, request))

    def execute(self, context: Context, request: str) -> StepDecision:
        current = (self.curr_subflow_num.get(context) or 0) - 1
        self.curr_subflow_num.set(context, current)
        if current == 0:
            return force_complete_if_channels_empty(
                None,
                StepMovement.of(ShortLiveHandleRequest, None),
                self.request_channel,
            )
        return go_to(ShortLiveHandleRequest, None)


class AdvancedShortLiveParentFlow(Flow[ParentInput]):
    request_channel = Channel("RequestChannel", str)
    curr_subflow_num = Attribute("CurrSubFlowNum", int)

    def __init__(self, example_subflow: ExampleSubFlow) -> None:
        self.init = ShortLiveInit(self.request_channel, self.curr_subflow_num)
        self.handle_request = ShortLiveHandleRequest(
            self.request_channel, self.curr_subflow_num
        )
        self.handle_subflow = ShortLiveHandleSubFlow(
            example_subflow, self.request_channel, self.curr_subflow_num
        )

    def get_steps(self) -> StepList[ParentInput]:
        return StepList.start_step(self.init).other_steps(
            self.handle_request, self.handle_subflow
        )

    def get_persistence_schema(self) -> PersistenceSchema:
        return PersistenceSchema.of(self.request_channel, self.curr_subflow_num)

    @rpc
    def send_request(self, context: Context, request: str) -> RPCResult[bool]:
        if self.request_channel.size(context) >= MAX_BUFFERED_REQUESTS:
            return RPCResult(False)
        self.request_channel.publish(context, request)
        return RPCResult(True)
```

Example: [examples/python/dex_examples/patterns/parallel-subflows/advanced_short_live_parent_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/parallel-subflows/advanced_short_live_parent_flow.py)

<a id="early-requests"></a>

## 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](https://docs.superdurable.io/reference/server/runtime-client.md#confirm-message-handled).

These steps describe the variant with an intake gate. Its extra Step, `AdmitBatch`, is not in the graph above.

1. `AdmitBatch` takes the start batch while it holds the lock on the admission Attribute. An empty batch returns `GracefulComplete`, because the intake never opened.
2. Otherwise `AdmitBatch`, in one commit, queues each request in the `Requests` Channel, opens the intake, sets the active child count to 0, and starts the workers in `HandleRequest`.
3. `sendRequest` reads 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.

## Next

- [Multiple parents with partitioning](https://docs.superdurable.io/design-patterns/subflows/partitioning.md)
- [Step decision](https://docs.superdurable.io/reference/python/step-decisions.md#forcecompleteifchannelsempty)
