Repository navigation
4.2. 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.
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.
For an ordinary Activity, a send still waits for its run-to-completion processing, despite not expecting a response event. Orleans Activity streaming adds an explicit admission-only operation: activity.StreamInputAsync(...) returns Accepted before its network work necessarily finishes. During streaming, a regular send waits for its transactional part, not unrelated streamed work or mixed descendants handed off to the stream. Token-input requests are rejected while a stream is active; use sends and output watches/queries.
activity.CheckpointAsync() sends the dedicated ActivityCheckpoint event and returns after the snapshot commits. It is not a progress query or completion notification. See Activity Checkpoints.
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.
Use context.Behavior.StageSending(new RecheckOrder(orderId)) instead of Send
when a self-send must be queued only after the current behavior transaction commits
successfully. Parent/owner contexts provide the corresponding relationship-specific
operation. The event and headers are snapshotted when staged.
In the Orleans runtime staged sends are durable outbox entries, committed atomically with behavior state and receipts. A joined child's staged sends wait for the root transaction to commit; an abort discards them. An independent delivery worker sends them in staging order without making the source await target processing, avoiding self/parent-send deadlocks. Failed deliveries remain pending and are retried through durable reminders, including after host restart when durable storage is configured. Delivery retries keep the same event ID and cannot roll back the committed source.
TimeToLive uses the same attribute/header precedence as notifications and starts
when the send is staged, not when it commits. Expired sends are discarded; without a
TTL they remain eligible for retry. Delivery is at least once: receipt deduplication
reduces duplicate processing but does not guarantee exactly-once external effects.
Deferred notifications share the committed outbox and retain their subscription
handoff/watermark behavior. Immediate notifications remain independent side effects.
Other runtimes retain their previous in-memory staging behavior.
Staging is rejected outside a behavior transaction and during streamed Activity
execution. An HTTP endpoint's context is not a behavior transaction.
A staged send cannot carry JoinTransaction: its sender transaction has already
ended when delivery takes place.
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() |
Keeps only the latest retained notification of each declared event type for requests, replay, and subscription retries. A positive TTL still expires it; zero keeps it indefinitely. |
[TimeToLive(seconds)] |
new TimeToLive(seconds) |
Sets the notification lifetime, measured from publication. Zero disables history and subscription retries unless retained. PublishTimed/PublishRangeTimed set a TimeToLive header (60 seconds by default). TTL is not a delay before publishing. |
[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.
In a streaming Activity, streamed and mixed firings publish immediately without an ImmediatePublish header. Pure transactional firings retain successful-call outbox ownership and discard deferred publications on failure, unless immediate publication is explicitly requested. A regular publication commit does not checkpoint the busy network's values and marking; a streamed publication can be observed before that network state becomes durable.
Publication defaults to Retain = false and TTL 0. Live delivery, retained-value replay, and historical requests are separate concerns:
| Retain | TTL | Stored notifications | Requests and subscription delivery |
|---|---|---|---|
false |
0 |
None | Current subscribers and watchers receive one delivery attempt. No historical requests, replay, or subscription retries. |
true |
0 |
Only the latest retained notification of each type | Queryable and eligible for subscription retries indefinitely. |
true |
Positive | Only the latest retained notification of each type | Queryable and eligible for subscription retries until TTL expires. |
false |
Positive | All unexpired notifications | Eligible for subscription retries and timestamp-based requests until expiry; excluded from requests without a timestamp. |
A newer retained publication replaces the previous retained value and its pending retries. An already executing delivery cannot be retracted. Expiration never revives an older retained value. Positive-TTL nonretained history remains available until expiry even after successful delivery.
// Live updates only: no history or subscription retries.
context.Behavior.Publish(new ShipmentProgress(orderId, "Packing"));
// Latest value, available indefinitely.
context.Behavior.PublishRetained(new OrderStatusChanged(orderId, "Shipped"));
// History and subscription retries for five minutes.
context.Behavior.PublishTimed(new ShipmentProgress(orderId, "In transit"), 300);
// Latest value, available for five minutes.
context.Behavior.PublishRetained(
new OrderStatusChanged(orderId, "Delivered"),
new Dictionary<string, EventHeader>
{
[nameof(TimeToLive)] = new TimeToLive(300)
});
var latest = await behavior.GetNotificationsAsync<OrderStatusChanged>();
var history = await behavior.GetNotificationsAsync<ShipmentProgress>(since);
var envelopes = await behavior.GetNotificationsAsync(
new[] { Event<OrderStatusChanged>.Name }, since);Requests without a timestamp return only the latest unexpired retained values. Timestamp-based requests return matching unexpired history from that time plus the latest retained values, even if those values were published earlier. Requests do not clear notifications or wait for future publication.
Orleans persists retryable notifications and pending behavior-subscription deliveries. Failed deliveries are retried through reminders or subsequent publications until acknowledged, superseded, expired, or unsubscribed. TTL-zero nonretained publications do not write notification history or persistent subscription-delivery state. Positive-TTL notifications become unavailable at expiry; expired stored history is pruned on publication or the notification reminder (one-minute interval). Client watches remain volatile and are not durable retry queues. Durability across host restart requires durable Orleans storage; other runtimes use their configured notification storage.
Retention does not change dispatch timing: ImmediatePublish controls when a notification is sent, while Retain and TTL control what is kept. Publisher outbox delivery is also distinct from subscription retries: a transactional publication is handed off after its publisher commits, even when its eventual notification is transient.
Home page Support Code licensed under an MIT-style License. Documentation licensed under CC BY 4.0. © by Mikołaj Milewski, 2026