Skip to main content

Drain External Channels

View as Markdown

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.

How it works

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.

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

draining_channel_flow.pyPython
# 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

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

controller.pyPython
# 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}"

Example: examples/python/dex_examples/patterns/drain-channels/external_publishing/controller.py

Next