---
title: "Drain External Channels"
description: "Handle Channel messages that clients publish, and complete the Flow as soon as the Channel is empty. Use this pattern when messages come from outside the Worker, possibly in bursts: the Flow runs only while there is work, and the next message starts it again."
canonical_url: "https://docs.superdurable.io/design-patterns/drain-external-channels/"
source: "docs/content/design-patterns/draining-channel-for-external-publishing.mdx"
locale: "en"
language: "python"
---

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

# Drain External Channels

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

Handle Channel messages that clients publish, and complete the Flow as soon as the Channel is empty. Use this pattern when messages come from outside the Worker, possibly in bursts: the Flow runs only while there is work, and the next message starts it again.

**Flow graph: DrainingExternalChannelFlow**

**Steps**

1. `ProcessMessage` (start Step): Process one queued message, then complete once no message waits. Next: `ProcessMessage` again. Reads `queueChannel`.

**RPCs**

- `publish_external_channel_message`: Publishes to `queueChannel`.

Example: [examples/python/dex_examples/patterns/drain-channels/external_publishing/draining_channel_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/drain-channels/external_publishing/draining_channel_flow.py)

<a id="how-it-works"></a>

## How it works

<a id="problem-and-approach"></a>

<a id="step-graph"></a>

A Client calls an RPC that appends each message to the Channel. The RPC only validates the message and publishes it. It writes no Attribute that a Step reads or locks, such as a counter or a per-entity status. **ProcessMessage** owns that state, so the publishing RPC does not contend for the consumer's Attribute locks.

**ProcessMessage** handles one message and returns a `ForceCompleteIfChannelsEmpty` decision. Dex checks the Channel and records the close decision atomically. If the Channel is empty, the Flow completes. Otherwise Dex takes the fallback movement back to **ProcessMessage**. See [ForceCompleteIfChannelsEmpty](https://docs.superdurable.io/reference/go/step-decisions.md#forcecompleteifchannelsempty).

<a id="close-safely"></a>

## Close safely

Close with this atomic decision while publishers can still submit work. A size check followed by a plain completion can leave a message that arrived between the two unprocessed. If you close admission first, close it under a lock that the publishing RPC also takes, and finish all accepted messages before completing.

On the fallback, the Attributes the Step already wrote stay saved. A final status written there, such as `closed`, then stays while the Flow keeps handling messages. Write a final status only once the close is certain, or reset it on the fallback path. When the close answers a request, such as an end command, pass that request to the fallback Step in its input or an Attribute, so the Flow still closes after the late messages are handled.

## Core implementation

**Python**

```python
# dex:group group-id:messages group-label:"Messages"
# dex:explanation text:"Process one queued message, then complete once no message waits."
class ProcessMessage(Step[str]):
    def __init__(self, queue_channel: Channel[str]) -> None:
        self.queue_channel = queue_channel

    def wait_for(self, context: Context, input: str) -> Wait:
        if input is None:
            return Wait.until(self.queue_channel.for_one())
        return Wait.skip_immediately()

    def execute(self, context: Context, input: str) -> StepDecision:
        if input is not None:
            print(f"DrainingExternalChannelFlow process message: {input}")
        else:
            values = self.queue_channel.results(context)
            if not values:
                raise RuntimeError("No channel message found")
            value = values[0]
            if value is None:
                raise RuntimeError("No channel message value found")
            print(f"DrainingExternalChannelFlow process message: {value}")

        return force_complete_if_channels_empty(
            None,
            StepMovement.of(ProcessMessage, None),
            self.queue_channel,
        )


class DrainingExternalChannelFlow(Flow[str]):
    QUEUE_CHANNEL = "queueChannel"

    queue_channel = Channel(QUEUE_CHANNEL, str)

    def __init__(self) -> None:
        self.process_message = ProcessMessage(self.queue_channel)

    def get_steps(self) -> StepList[str]:
        return StepList.start_step(self.process_message)

    def get_persistence_schema(self) -> PersistenceSchema:
        return PersistenceSchema.of(self.queue_channel)

    @rpc
    def publish_external_channel_message(
        self, context: Context, input: str
    ) -> RPCResult[str]:
        self.queue_channel.publish(context, input)
        return RPCResult(input)
```

Example: [examples/python/dex_examples/patterns/drain-channels/external_publishing/draining_channel_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/drain-channels/external_publishing/draining_channel_flow.py)

## Controller

Each entity has one stable Flow ID and at most one active run. The run handles messages in the order their publications commit.

The controller first starts a run with the entity's Flow ID and the message as its start input. The start allows reuse of a closed Flow ID, uses a request ID fixed per message, and ignores the already-started error for that request ID. When a different start request owns the active run, the controller calls the publishing RPC on that run, with a request ID derived from the message ID where the SDK offers one. If that run closed before the publish, the controller starts again. After a few attempts, it returns HTTP 409 with the message ID: the outcome is unknown, and the caller sends the message again with the same ID. It returns any other error to its caller. [What Dex Server does](https://docs.superdurable.io/reference/go/start-flow-options.md#start-request-server-behavior) explains how a retried start resolves.

A success response means the run accepted the message, not that a Step handled it. When the caller must confirm each message was handled, the consuming Step records the message'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/client-apis.md#confirm-message-handled).

**Python**

```python
# Bounds how often a message that lost a start race is published again.
START_OR_PUBLISH_ATTEMPTS = 3


def pattern_start_options(message_id: str) -> StartFlowOptions:
    """Restarts a closed Flow ID.

    A retried start returns the original run while that run is still the latest
    run for the Flow ID and its start request ID matches.
    """
    return replace(
        start_options(),
        id_reuse_policy=IdReusePolicy.ALLOW_IF_NOT_RUNNING,
        request_id=f"start:{message_id}",
        ignore_already_started=True,
    )


def create_draining_channel_blueprint(app_state: ExampleApp) -> Blueprint:
    blueprint = Blueprint(
        "pattern_drain_external",
        __name__,
        url_prefix="/patterns/drain-channels/external-publishing",
    )

    @blueprint.get("/start-or-publish")
    async def start_or_publish_draining_channel() -> tuple[str, int]:
        flow_id = required_query("workflowId")
        message_id = optional_query("messageId", "") or str(uuid.uuid4())
        message = f"message {message_id}"
        for _ in range(START_OR_PUBLISH_ATTEMPTS):
            try:
                run_id = await app_state.client.start_flow(
                    app_state.drain_external,
                    flow_id,
                    message,
                    pattern_start_options(message_id),
                )
                return (
                    f"Accepted message {message_id} as the start input of runId {run_id}",
                    200,
                )
            except FlowAlreadyStartedError:
                # A different start request owns the active run: publish this message to that run.
                pass
            try:
                await app_state.client.invoke_rpc(
                    app_state.drain_external.publish_external_channel_message,
                    flow_id,
                    message,
                    options=RPCInvokeOptions(request_id=f"publish:{message_id}"),
                )
                return f"Accepted message {message_id}", 200
            except FlowNotActiveOrNotFoundError:
                # That run closed before the publish: start again.
                continue
        return (
            f"message {message_id} is unconfirmed; send it again with the same messageId",
            409,
        )

    return blueprint
```

Example: [examples/python/dex_examples/patterns/drain-channels/external_publishing/controller.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/drain-channels/external_publishing/controller.py)

## Next

- [Channel](https://docs.superdurable.io/concepts/primitives/channel.md)
- [RPC](https://docs.superdurable.io/concepts/primitives/rpc.md)
- [Drain Channels](https://docs.superdurable.io/design-patterns.md#drain-channels)
