Drain External Channels
View as MarkdownHandle 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
# 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
const QueueChannelName = "queueChannel"
var QueueChannel = dex.DefineChannel[string](QueueChannelName)
type DrainingExternalChannelFlow struct {
dex.FlowDefaults
}
func NewDrainingExternalChannelFlow() *DrainingExternalChannelFlow {
return &DrainingExternalChannelFlow{}
}
func (*DrainingExternalChannelFlow) GetSteps() []dex.StepDef {
return []dex.StepDef{
dex.DefineStartStep(processMessage{}),
}
}
func (flow *DrainingExternalChannelFlow) GetRPCs() []dex.RPCDef {
return []dex.RPCDef{dex.DefineRPC(flow.PublishExternalChannelMessage, nil)}
}
func (*DrainingExternalChannelFlow) GetPersistenceSchema() dex.PersistenceSchema {
return dex.PersistenceSchema{
Channels: []dex.ChannelDef{QueueChannel},
}
}
func (*DrainingExternalChannelFlow) PublishExternalChannelMessage(
ctx dex.Context,
Example: examples/go/patterns/drain-channels/external-publishing/workflow.go
@Component
public class DrainingExternalChannelFlow implements Flow<String> {
public static final String QUEUE_CHANNEL = "queueChannel";
public final Channel<String> queueChannel =
Channel.define(QUEUE_CHANNEL, String.class);
private final ProcessMessage processMessage = new ProcessMessage();
@Override
public StepList<String> getSteps() {
return StepList.startStep(processMessage);
}
@Override
public PersistenceSchema getPersistenceSchema() {
return PersistenceSchema.of(queueChannel);
}
@RPC
public RPCResult<String> publishExternalChannelMessage(
final Context context, final String input) {
queueChannel.publish(context, input);
return RPCResult.of(input);
}
final class ProcessMessage implements Step<String> {
@Override
public Class<String> getInputType() {
return String.class;
export const QUEUE_CHANNEL = "queueChannel";
export const queueChannel = new Channel(QUEUE_CHANNEL, stringCodec);
const optionalInputCodec = optionalCodec(stringCodec);
class ProcessMessage implements Step<string | undefined> {
public readonly inputCodec = optionalInputCodec;
public getStepType(): string {
return "ProcessMessage";
}
public waitFor(_context: Context, input: string | undefined): Wait {
if (input === undefined) {
return Wait.until(queueChannel.forOne());
}
return Wait.skipImmediately();
}
public execute(context: Context, input: string | undefined): StepDecision {
if (input !== undefined) {
console.log(`DrainingExternalChannelFlow process message: ${input}`);
} else {
const values = queueChannel.results(context);
if (values.length === 0) {
throw new Error("No channel message found");
}
const value = values[0];
if (value === undefined) {
Example: examples/typescript/src/patterns/drain-channels/external-publishing/draining-channel-flow.ts
pub(crate) static EXTERNAL_QUEUE: LazyLock<Channel<String>> =
LazyLock::new(|| Channel::new("drain-channel-queue"));
pub const PUBLISH_EXTERNAL_CHANNEL_MESSAGE: Rpc<String, String> =
Rpc::new("PublishExternalChannelMessage");
#[derive(Default)]
pub struct DrainingExternalChannelFlow {
drain: DrainChannel,
}
impl DrainingExternalChannelFlow {
fn publish_external_channel_message(
&self,
context: &mut Context,
input: String,
) -> HandlerResult<RpcResult<String>> {
EXTERNAL_QUEUE.publish(context, input.clone())?;
Ok(RpcResult::new(input))
}
}
impl Flow for DrainingExternalChannelFlow {
type StartInput = String;
fn steps(&self) -> StepList<'_, Self::StartInput> {
StepList::start(&self.drain)
}
fn persistence(&self) -> PersistenceSchema {
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.
# 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
// startOrPublishAttempts bounds how often a message that lost a start race is published again.
const startOrPublishAttempts = 3
// patternStartOptions 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.
func patternStartOptions(messageID string) sdk.StartFlowOptions {
timeout := time.Hour
requestID := "start:" + messageID
return sdk.StartFlowOptions{
Timeout: &timeout,
IDReusePolicy: sdk.IDReuseAllowIfNotRunning,
RequestID: &requestID,
AlreadyStarted: &sdk.AlreadyStartedOptions{IgnoreError: true},
}
}
func (controller *controller) startOrPublish(request *gin.Context) {
flowID, found := httputil.RequiredQuery(request, "workflowId")
if !found {
return
}
messageID := request.Query("messageId")
if messageID == "" {
messageID = uuid.NewString()
}
message := "message " + messageID
publishRequestID := "publish:" + messageID
for attempt := 0; attempt < startOrPublishAttempts; attempt++ {
runID, startErr := controller.client.StartFlow(
request.Request.Context(),
Example: examples/go/patterns/drain-channels/external-publishing/controller.go
@GetMapping("/external-publishing/start-or-publish")
ResponseEntity<String> startDrainingChannel(
@RequestParam final String workflowId,
@RequestParam(required = false) final String messageId) {
final String stableMessageId =
messageId == null || messageId.isEmpty() ? UUID.randomUUID().toString() : messageId;
final String message = "message " + stableMessageId;
final DrainingExternalChannelFlow stub = client.newRpcStub(
DrainingExternalChannelFlow.class,
workflowId);
for (int attempt = 0; attempt < START_OR_PUBLISH_ATTEMPTS; attempt++) {
try {
final String runId = client.startFlow(
drainingExternalChannelFlow,
workflowId,
message,
externalPublishingStartOptions(stableMessageId));
return ResponseEntity.ok(
"Accepted message " + stableMessageId + " as the start input of runId " + runId);
} catch (final FlowAlreadyStartedException alreadyStarted) {
// A different start request owns the active run: publish this message to that run.
}
try {
client.invokeRPC(stub::publishExternalChannelMessage, message);
return ResponseEntity.ok("Accepted message " + stableMessageId);
} catch (final FlowNotActiveOrNotFoundException inactive) {
// That run closed before the publish: start again.
}
}
return ResponseEntity.status(HttpStatus.CONFLICT).body(
"message " + stableMessageId + " is unconfirmed; send it again with the same messageId");
}
/**
* 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.
*/
private static StartFlowOptions externalPublishingStartOptions(final String messageId) {
return StartFlowOptions.newBuilder()
.timeout(Duration.ofHours(1))
.idReusePolicy(IdReusePolicy.ALLOW_IF_NOT_RUNNING)
.requestId("start:" + messageId)
.ignoreAlreadyStarted(true)
.build();
}
Example: examples/java/src/main/java/io/superdurable/dex/patterns/drainchannels/DrainChannelsController.java
/** Bounds how often a message that lost a start race is published again. */
const START_OR_PUBLISH_ATTEMPTS = 3;
/**
* 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.
*/
function externalPublishingStartOptions(messageId: string): StartFlowOptions {
return startOptions({
idReusePolicy: IdReusePolicy.ALLOW_IF_NOT_RUNNING,
requestId: `start:${messageId}`,
ignoreAlreadyStarted: true,
});
}
export function createDrainingChannelRouter(client: Client): Router {
const router = Router();
router.get("/start-or-publish", async (request, response) => {
const workflowId = String(request.query.workflowId ?? "");
const messageId = String(request.query.messageId ?? "") || randomUUID();
const message = `message ${messageId}`;
for (let attempt = 0; attempt < START_OR_PUBLISH_ATTEMPTS; attempt++) {
try {
const runId = await client.startFlow(
drainingExternalChannelFlow,
workflowId,
message,
externalPublishingStartOptions(messageId),
);
Example: examples/typescript/src/patterns/drain-channels/external-publishing/controller.ts
async fn start_or_publish(
State(client): State<SharedClient>,
Query(query): Query<StartQuery>,
) -> impl IntoResponse {
let flow_id = if query.workflow_id.is_empty() {
new_flow_id("drain-external")
} else {
query.workflow_id
};
let message_id = if query.message_id.is_empty() {
new_message_id()
} else {
query.message_id
};
match run_blocking(move || {
let flow = DrainingExternalChannelFlow::default();
let message = format!("message {message_id}");
for _ in 0..START_OR_PUBLISH_ATTEMPTS {
match client.start_flow_with_options(
&flow,
&flow_id,
message.clone(),
external_publishing_start_options(&message_id),
) {
Ok(run_id) => {
return Ok(Ok(format!(
"Accepted message {message_id} as the start input of runId {run_id}"
)));
}
// A different start request owns the active run: publish this message to that run.
Example: examples/rust/src/patterns/drain_channels/controller.rs