---
title: "Advanced: Long-lived Parent"
description: "Keep a fixed pool of worker Steps running while the Flow accepts more requests."
canonical_url: "https://docs.superdurable.io/design-patterns/subflows/long-lived-parent/"
source: "docs/content/design-patterns/subflows/long-lived-parent.mdx"
locale: "en"
language: "python"
---

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

# Advanced: Long-lived Parent

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

Keep a fixed pool of worker Steps running while the Flow accepts more requests.

**Flow graph: AdvancedLongLiveParentFlow**

**Steps**

1. `Init` (start Step): Queue the requests and start the request handlers. Next: `HandleRequest`. Publishes to `RequestChannel`.
2. `HandleRequest`: Wait for the next queued request. Next: `HandleSubFlow`. Reads `RequestChannel`.
3. `HandleSubFlow`: Run a child Flow for the request, then take the next request. Next: the Flow completes, or `HandleRequest`. Reads `Stopped`.

**RPCs**

- `send_request`: Reads `RequestChannel`; publishes to `RequestChannel`.
- `stop`: Writes `Stopped`.

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

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

**Python**

```python
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())

    def execute(self, context: Context, input: None) -> StepDecision:
        return go_to(LongLiveHandleSubFlow, self.request_channel.results(context)[0])


class LongLiveHandleSubFlow(Step[str]):
    def __init__(
        self,
        example_subflow: ExampleSubFlow,
        stopped: Attribute[bool],
    ) -> None:
        self.example_subflow = example_subflow
        self.stopped = stopped

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

    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:
        if self.stopped.get(context):
            return graceful_complete()
        return go_to(LongLiveHandleRequest, None)


class AdvancedLongLiveParentFlow(Flow[ParentInput]):
    request_channel = Channel("RequestChannel", str)
    stopped = Attribute("Stopped", bool)

    def __init__(self, example_subflow: ExampleSubFlow) -> None:
        self.init = LongLiveInit(self.request_channel)
        self.handle_request = LongLiveHandleRequest(self.request_channel)
        self.handle_subflow = LongLiveHandleSubFlow(example_subflow, self.stopped)

    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.stopped)

    @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)

    @rpc
    def stop(self, context: Context) -> None:
        self.stopped.set(context, True)
```

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

<a id="close-the-intake"></a>

## 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 `Execute` in `HandleRequest` declare the same `intakeClosed` lock.
- 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, to `ReturnRequest`, 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](https://docs.superdurable.io/reference/go/waits.md#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.

1. `sendRequest` holds the `intakeClosed` lock. It accepts a request while the intake is open and the current queue length is below the limit. It queues the request in the `Requests` Channel.
2. Each worker in `HandleRequest` waits for a queued request or for a graceful completion request.
3. A worker that took a request holds the `intakeClosed` lock and commits its move to `HandleChild`, which starts the child without the lock. After the close, it moves to `ReturnRequest` instead, which sends the returned request without the lock and then waits for the next one.
4. A worker whose wait ended through the graceful completion request, with no request consumed, ends its branch.
5. `closeIntake` holds the `intakeClosed` lock, marks the intake closed, and publishes a close message. `CloseIntake` receives it and completes the Flow gracefully.

## Next

- [Short-lived parent](https://docs.superdurable.io/design-patterns/subflows/short-lived-parent.md)
- [Multiple parents with partitioning](https://docs.superdurable.io/design-patterns/subflows/partitioning.md)
- [Back pressure for high availability](https://docs.superdurable.io/design-patterns/subflows/back-pressure.md)
- [Channel](https://docs.superdurable.io/concepts/primitives/channel.md)
