Skip to content

Messaging Patterns

Mikołaj Milewski edited this page Oct 27, 2026 · 1 revision

Messaging Patterns

Stateflows has two complementary messaging patterns: a client can address a Behavior directly, while one Behavior can communicate with other Behaviors from its execution context. The APIs differ in whether the caller waits for processing and whether a notification subscription survives beyond the current process or handle lifetime.

Client to Behavior

Resolve an IBehavior handle using the application's behavior locator. The handle exposes three common patterns:

API Pattern Meaning
SendAsync Fire-and-forget event delivery Sends an event and returns a SendResult; it does not wait for a response event.
RequestAsync Request/response Sends an IRequest<TResponseEvent> and returns the corresponding response result.
WatchAsync Publish/subscribe Registers a client-side callback for notifications published by the Behavior.
using Stateflows.Common;

var sendResult = await behavior.SendAsync(new SubmitOrder(orderId));

var response = await behavior.RequestAsync<OrderStatus>(
    new GetOrderStatus(orderId));
var status = response.Response;

await using var watcher = await behavior.WatchAsync<OrderStatusChanged>(
    notification => Console.WriteLine(notification.Status));

SendAsync is fire-and-forget with respect to a request/response exchange; the returned task/result still reports the send operation. RequestAsync is appropriate when the caller needs a correlated response. A client WatchAsync is volatile: it exists only while the watch and its Behavior handle remain alive, and disposing the watcher stops it. replayNotificationsSince can request replay of notifications published after a timestamp, but does not turn a watch into a durable subscription.

Behavior to Behavior

Use IBehaviorContext inside a Behavior execution context. For example, an IBehaviorActionContext exposes the current Behavior context through its Behavior property. That IBehaviorContext provides Send, Publish, SubscribeAsync, and UnsubscribeAsync; it is not the external IBehavior handle and does not expose the client's request/response API.

using Stateflows.Common;

public sealed record InventoryReserved(string OrderId);
public sealed record OrderAccepted(string OrderId);
public sealed record ReserveInventory(string OrderId);
public sealed record RecheckOrder(string OrderId);

The following fragment belongs inside the relevant method or builder callback:

async Task HandleAsync(
    IBehaviorActionContext context,
    BehaviorId inventoryBehaviorId,
    string orderId)
{
    await context.Behavior.SubscribeAsync<InventoryReserved>(inventoryBehaviorId);
    context.Behavior.Publish(new OrderAccepted(orderId));
    context.Behavior.Send(new RecheckOrder(orderId));

    if (!context.TryLocateBehavior(inventoryBehaviorId, out var inventory))
    {
        throw new InvalidOperationException("Inventory behavior could not be located.");
    }

    var sent = await inventory.SendAsync(new ReserveInventory(orderId));
    if (sent.Status != EventStatus.Consumed)
    {
        throw new InvalidOperationException($"Inventory command failed: {sent.Status}.");
    }
}

context.Behavior.Send(...) is a self-send: it targets the executing Behavior's ID and returns no task. It does not select another Behavior. For directed communication, locate the intended recipient through IBehaviorActionContext (which implements IBehaviorLocator) and use that handle. Parent/owner contexts provide relationship-specific sends without selecting an arbitrary ID.

To receive a notification, a Behavior subscribes to its publisher by BehaviorId; the publisher then delivers notifications of the subscribed type. SubscribeAsync<TNotification> and UnsubscribeAsync<TNotification> operate on both the notification type and Behavior ID. A Behavior subscription is durable over time: it remains until explicitly removed with the matching UnsubscribeAsync, rather than ending with a client handle. Choose the publisher and subscriber IDs deliberately; the subscription is between Behavior instances.

Behaviors embedded in a behavioral group can use dedicated parent/owner context APIs when addressing their embedding or owning Behavior. Entities are the shared-data mechanism for a group; messaging is for event exchange and notifications.

Notification metadata and dispatch controls

Notification publishing APIs accept an optional header dictionary, and several common headers also have event-type attributes. Attributes define a policy for a CLR event type; headers let the publisher apply a policy to an individual publication. For a notification type, [Retain] and [TimeToLive(seconds)] are read when the notification is published. A corresponding header can provide the same policy for a particular publication. When both a TTL attribute and a TimeToLive header are present, the attribute's value takes precedence.

using System.Collections.Generic;
using Stateflows.Common;

context.Behavior.Publish(
    new OrderStatusChanged(orderId, "Shipped"),
    new Dictionary<string, EventHeader>
    {
        [nameof(Retain)] = new Retain(),
        [nameof(TimeToLive)] = new TimeToLive(300)
    });
Attribute Header Effect
[Retain] new Retain() Marks a published notification as retained. A notification store/runtime that supports retained notifications can keep the latest retained notification of each name for replay to later watchers or subscribers. This is notification history/replay, not a durable client watch. Retained-notification support and storage lifetime depend on the configured storage/runtime.
[TimeToLive(seconds)] new TimeToLive(seconds) Sets the notification's expiration lifetime in seconds for stores/runtimes that enforce notification TTL. PublishTimed/PublishRangeTimed are convenience APIs that set a TimeToLive header (60 seconds by default). TTL affects how long a notification is eligible for storage/replay or pending delivery; it is not a delay before publishing. Exact replay/expiry behavior depends on the storage/runtime.
[ImmediatePublish] new ImmediatePublish() Dispatches this notification during Behavior execution instead of buffering it until the publisher commits its state. The notification may already have reached watchers/subscribers if execution or persistence later fails, and cannot be retracted. Use for progress notifications only when that trade-off is intended.
[NoForwarding] new NoForwarding() Stops automatic forwarding of the event between a State Machine and its embedded Behaviors. Without it, a parent can forward an event to an embedded Behavior that accepts it, and an unconsumed event can bubble from an embedded Behavior to its parent. It does not disable notification publication or subscriber delivery.
[NoTracing] new NoTracing() With the OpenTelemetry extension enabled, excludes processing of the event from the extension's event tracing and associated execution metrics. It does not change event delivery or notification behavior.

The PublishRetained and PublishRangeRetained convenience methods set the Retain header; PublishTimed and PublishRangeTimed set the TimeToLive header. Use these instead of constructing the respective header when the standard operation is sufficient:

context.Behavior.PublishRetained(new OrderStatusChanged(orderId, "Shipped"));
context.Behavior.PublishTimed(new ShipmentProgress(orderId, "In transit"), 300);

await behavior.SendAsync(
    new ChildCommand(orderId),
    new Dictionary<string, EventHeader>
    {
        [nameof(NoForwarding)] = new NoForwarding(),
        [nameof(NoTracing)] = new NoTracing()
    });

NoForwarding and NoTracing can also be set on the incoming event sent with IBehavior.SendAsync, or supplied in that call's headers. Forwarding concerns apply only to State Machine embedding; NoTracing is honored by the OpenTelemetry extension when processing the event. These controls are independent: for example, retaining a notification does not make its watchers durable, and ImmediatePublish does not make a publication persistent.

Overview
Installation
Runtimes
   Orleans runtime
Concepts
   Events and Structural Events
   Messaging Patterns
   Validation
   Scheduling
   Observability
Behaviors
   Behavior Values
   Dependency Injection
   Behavioral Groups
   State Machines
       Concepts
           State Identity
           In-State Event Deferrals
           Evaluation of Transitions
           Exception Handling
       Building blocks
           Regions
           States
               State
               Composite State
               Orthogonal State
               Final State
           Pseudostates
               Choice
               Junction
               Fork
               Join
               History
           Transitions
               Transition
               Default Transition
               Internal Transition
   Activities
       Concepts
           Exception Handling
           Implicit Fork and Join
           Tokens
       Building blocks
           Nodes
               Action Node
               Decision Node
               Merge Node
               Initial Node
               Final Node
               Input Node
               Output Node
               Fork Node
               Join Node
               Accept Event Action Node
               Send Event Action Node
               Publish Event Action Node
               Time Event Action Node
               Data Store Node
               Structured Activity Node
               Iterative Activity Node
               Parallel Activity Node
           Flows
               Data Flow
               Control Flow
   Actions
   Entities
       Fields
       Mutations
       Projections
Extensions
   ClearScript
   FluentValidation
   JSON definitions
   Minimal APIs
   OneOf
   OpenTelemetry
   PlantUML
   Scheduling

Clone this wiki locally