Messaging practical recipes
These compiled examples use ordinary grains which inject IInbox or IOutbox, and named journaled state. Configure Journaling and Durable Jobs and call AddMessaging as shown in Messaging. Use persistent shared providers for deployments; the in-memory configuration is suited to local execution.
All handler examples finish validation and asynchronous preparation with local
values, then send typed messages, apply the business update, and call Complete()
without awaiting. Input which can never become valid is dead-lettered with
Fail(reason) or answered with a typed rejection reply. The inbox persists that
outcome. Ordinary grain methods await
their own journal write. Each grain registers typed handlers with
Register and injects the outbox directly.
Grains inject the application’s Messages class, whose
MessageType<T> bindings pair each subject with its body type.
Run the stock-reservation sample
Section titled “Run the stock-reservation sample”The Messaging sample runs an order grain and a stock grain in one localhost silo. Three independent hierarchical command IDs exercise acceptance, insufficient stock, and invalid quantity. The order grain sends each command through its outbox and waits for the stock grain’s typed reply, which reaches the order grain’s inbox. The host verifies that each command receives its own outcome, that rejections leave stock unchanged, and that the stock grain processes each command once.
From the repository root:
pwsh .\samples\Build-Samples.ps1 -SkipExternalAssetsdotnet run --project .\samples\Messaging\Messaging.csproj --configuration Release --no-buildThe sample uses locally packed Orleans packages while these APIs await publication. Its README also describes the self-contained copy-out workflow. Volatile journals and in-memory jobs support local execution; configure persistent shared providers for restart recovery.
Reserve inventory once per order line
Section titled “Reserve inventory once per order line”Use one inventory grain per tenant/SKU with available-stock. The sender derives
the envelope’s command ID using
OrderOperationKeys,
and places the quantity and response destination in ReserveStock. The
typed send helper encodes the
record under the envelope’s inventory.reserve.v1 subject.
The inventory registers two typed handlers with
Register: inventory.reserve.v1 decodes
ReserveStock for the reservation method, and inventory.restock.v1 decodes
Restock for the stock-increment method. Each method receives its decoded record
and the handler context. The grain registers both in
OnActivateAsync, after journal recovery has restored its state.
[GenerateSerializer]public sealed record ReserveStock( [property: Id(1)] int Quantity, [property: Id(2)] GrainId ResponseDestination);
[GenerateSerializer]public sealed record Restock([property: Id(0)] int Quantity);
[GenerateSerializer]public abstract record ReservationResult( [property: Id(1)] int Quantity, [property: Id(3)] int RemainingStock) : OrderOutcome;
[GenerateSerializer]public sealed record ReservationAccepted(int Quantity, int RemainingStock) : ReservationResult(Quantity, RemainingStock);
[GenerateSerializer]public sealed record ReservationRejected( int Quantity, int RemainingStock, [property: Id(0)] ReservationRejectionReason Reason) : ReservationResult(Quantity, RemainingStock);
public enum ReservationRejectionReason{ InvalidQuantity, InsufficientStock}
public interface IInventoryGrain : IGrainWithStringKey{ Task SetAvailableAsync(int quantity); ValueTask<int> GetAvailableAsync();}
public sealed class InventoryGrain( IInbox inbox, IOutbox outbox, Messages messages, IDurableStateManager state, [FromKeyedServices("available-stock")] IDurableValue<int> available) : Grain, IInventoryGrain{ public override Task OnActivateAsync(CancellationToken cancellationToken) { inbox .Register(messages.ReserveStock, HandleReserveStock) .Register(messages.Restock, HandleRestock); return base.OnActivateAsync(cancellationToken); }
public async Task SetAvailableAsync(int quantity) { ArgumentOutOfRangeException.ThrowIfNegative(quantity); available.Value = quantity; await state.WriteStateAsync(); }
public ValueTask<int> GetAvailableAsync() => new(available.Value);
private void HandleReserveStock(ReserveStock request, IInboxHandlerContext context) { var current = available.Value; ReservationResult outcome = request.Quantity switch { <= 0 => new ReservationRejected(request.Quantity, current, ReservationRejectionReason.InvalidQuantity), var quantity when quantity > current => new ReservationRejected(quantity, current, ReservationRejectionReason.InsufficientStock), var quantity => new ReservationAccepted(quantity, current - quantity) };
outbox.SendReply(messages.ReservationResult, context, request.ResponseDestination, outcome); if (outcome is ReservationAccepted) available.Value = outcome.RemainingStock; context.Complete(); }
private void HandleRestock(Restock request, IInboxHandlerContext context) { if (request.Quantity <= 0) { context.Fail("Restock quantity must be positive."); return; } var next = checked(available.Value + request.Quantity); available.Value = next; context.Complete(); }}The reservation method computes its next stock and result locally. SendReply
encodes and stages the deterministic result reply, then the method applies stock
and completes synchronously. The first command commits that stock decrement, reply,
and inbox completion together. A repeat with the same command ID recognizes the
retained completion fact and preserves the original handler effects.
The serialized abstract ReservationResult derives from OrderOutcome;
sealed ReservationAccepted and ReservationRejected records distinguish the
valid business result types and carry the original quantity and remaining stock.
A nonpositive quantity sends ReservationRejected with InvalidQuantity;
a shortage sends it with InsufficientStock. Both complete with unchanged stock.
Invalid immutable reservation commands complete as durable business rejections.
The original outbox intent delivers the reply
within its configured delivery policy.
For a nonpositive Restock increment, the handler calls
Fail with a clear reason
and returns before mutation, because that command can never become valid. A positive
increment computes the checked new stock value before mutation, then commits that
update with inbox completion. Checked overflow throws and follows the processing
retry policy until InboxRetryTimeout.
Give each distinct
restocking operation its own stable command ID. The example’s SetAvailableAsync
is an administrative absolute-stock update. In
an order workflow, add explicit confirmation, expiry, and release policies for held
reservations and keep a record indexed by the reservation command ID when those
operations need lookup. Give release its own leaf, for example
{order}/inventory/{sku}/release, and commit its outcome with stock restoration.
Authorize stock administration and derive the tenant/SKU grain identity at the
application’s trusted entry point.
Charge an external provider with a stable key
Section titled “Charge an external provider with a stable key”Register an IServiceCollection implementation of the shown gateway contract. Its adapter maps the key to the provider’s idempotency header or request field and implements the provider’s outcome reconciliation protocol.
[GenerateSerializer]public sealed record ChargePayment( [property: Id(1)] decimal Amount, [property: Id(2)] string Currency, [property: Id(3)] GrainId ResponseDestination);
[GenerateSerializer]public sealed record PaymentResult( [property: Id(0)] ChargePayment Request, [property: Id(1)] string ProviderReference, [property: Id(2)] bool Charged) : OrderOutcome;
public interface IIdempotentPaymentGateway{ // The provider binds the canonical command key to its original request and result. Task<PaymentResult> ChargeAsync( string idempotencyKey, ChargePayment request, CancellationToken cancellationToken);}
public interface IPaymentGrain : IGrainWithStringKey{ ValueTask<PaymentResult?> GetResultAsync(MessageId commandId);}
public sealed class PaymentGrain( IInbox inbox, IOutbox outbox, Messages messages, IIdempotentPaymentGateway gateway, [FromKeyedServices("payment-results")] IDurableDictionary<MessageId, PaymentResult> results) : Grain, IPaymentGrain{ public override Task OnActivateAsync(CancellationToken cancellationToken) { inbox.Register(messages.ChargePayment, HandleChargeAsync); return base.OnActivateAsync(cancellationToken); }
public ValueTask<PaymentResult?> GetResultAsync(MessageId commandId) { results.TryGetValue(commandId, out var outcome); return new(outcome); }
private async ValueTask HandleChargeAsync( ChargePayment request, IInboxHandlerContext context, CancellationToken cancellationToken) { if (Validate(request) is { } invalid) { // An immutable command which can never become valid is dead-lettered once, without a provider call. context.Fail(invalid); return; }
cancellationToken.ThrowIfCancellationRequested(); var commandId = context.Message.Envelope.MessageId; var outcome = await gateway.ChargeAsync(commandId.ToString(), request, cancellationToken); if (outcome.Request != request || string.IsNullOrWhiteSpace(outcome.ProviderReference)) { throw new InvalidOperationException("The payment provider returned an inconsistent result."); }
cancellationToken.ThrowIfCancellationRequested();
outbox.SendReply(messages.PaymentResult, context, request.ResponseDestination, outcome); results[commandId] = outcome; context.Complete(); }
private static string? Validate(ChargePayment request) => request switch { { Amount: <= 0 } => "A payment amount must be positive.", { Currency: var currency } when string.IsNullOrWhiteSpace(currency) => "A payment requires a currency.", { ResponseDestination.IsDefault: true } => "A payment requires a response destination.", _ => null };}The handler first validates the immutable command. An amount, currency, or response
destination which can never become valid dead-letters the command with
Fail, before any provider call. The
provider call precedes shared journaled changes. The asynchronous handler
passes its token to the gateway, and the method checks cancellation after that
await before SendReply and the final result update. A provider fault throws, so the
message retries with backoff. If the provider succeeds and activation
loss interrupts the local commit, a replacement attempt uses the same provider key.
The canonical envelope ID is also the provider idempotency key. After local
completion, the inbox recognizes a resubmission during retention. The result-query
state, deterministic reply, and inbox completion share one write.
Normalize currency and scope the command ID to the provider account and tenant. Treat declined payments as completed outcomes; treat ambiguous provider responses using the provider’s same-key retry or query contract. Expose a status query, as this grain does, so a caller can reconcile an uncertain response by the same command ID. Retain provider idempotency facts for the full retry horizon; adapt key length with a deterministic canonical-key hash when the provider requires it. See External side effects for retention and reconciliation responsibilities.
Converge an out-of-order stock projection
Section titled “Converge an out-of-order stock projection”A dashboard or search projection can accept complete stock snapshots independently of transport ordering. The authoritative inventory producer assigns a monotonically increasing version for the same tenant/SKU.
[GenerateSerializer]public sealed record StockSnapshot( [property: Id(0)] long Version, [property: Id(1)] int Available);
public interface IStockProjectionGrain : IGrainWithStringKey{ ValueTask<StockSnapshot> GetSnapshotAsync();}
public sealed class StockProjectionGrain( IInbox inbox, Messages messages, [FromKeyedServices("stock-snapshot")] IDurableValue<StockSnapshot> snapshot) : Grain, IStockProjectionGrain{ public override Task OnActivateAsync(CancellationToken cancellationToken) { inbox.Register(messages.StockSnapshot, HandleSnapshot); return base.OnActivateAsync(cancellationToken); }
public ValueTask<StockSnapshot> GetSnapshotAsync() => new(snapshot.Value ?? new StockSnapshot(0, 0));
private void HandleSnapshot(StockSnapshot update, IInboxHandlerContext context) { if (update.Version <= 0 || update.Available < 0) { context.Fail("A snapshot requires a positive version and nonnegative stock."); return; }
var current = snapshot.Value; if (current is not null && update.Version == current.Version && update != current) { context.Fail("A snapshot version must retain its original value."); return; }
if (current is null || update.Version > current.Version) { snapshot.Value = update; } context.Complete(); }}If version 12 arrives before version 11, the projection retains version 12 and
completes version 11 as superseded. A repeated version binds to its original content:
a snapshot which reuses a version with different content, or carries an invalid
version or stock value, is dead-lettered with Fail(reason).
The version and complete stock value are one durable record. A stable message ID
recognizes the completed snapshot command; the domain version orders different
snapshot commands.
This recipe applies to complete replacement snapshots. Incremental debit, credit, or stock-delta events use a contiguous-sequence policy with a journaled gap buffer and a domain-defined recovery path for missing events.
Publish a durable notification campaign
Section titled “Publish a durable notification campaign”An ordinary method can stage several destinations with one business update. Give the campaign a stable ID so a repeated client submission finds its recorded content and recipient set.
[GenerateSerializer]public sealed record NotificationCampaign( [property: Id(0)] string Text, [property: Id(1)] GrainId[] Recipients);
public interface ICampaignGrain : IGrainWithStringKey{ Task PublishAsync(Guid campaignId, string text, GrainId[] recipients); ValueTask<NotificationCampaign?> GetCampaignAsync(Guid campaignId);}
public sealed class CampaignGrain( IOutbox outbox, IDurableStateManager state, [FromKeyedServices("campaigns")] IDurableDictionary<Guid, NotificationCampaign> campaigns, Messages messages, IGrainContext grainContext) : Grain(grainContext), ICampaignGrain{ public ValueTask<NotificationCampaign?> GetCampaignAsync(Guid campaignId) { campaigns.TryGetValue(campaignId, out var campaign); return new(campaign); }
public async Task PublishAsync(Guid campaignId, string text, GrainId[] recipients) { if (campaignId == Guid.Empty) { throw new ArgumentException("A campaign ID must be nonempty.", nameof(campaignId)); } ArgumentException.ThrowIfNullOrWhiteSpace(text); ArgumentNullException.ThrowIfNull(recipients); if (recipients.Length == 0 || recipients.Any(id => id.IsDefault) || recipients.Distinct().Count() != recipients.Length) { throw new ArgumentException("Specify distinct, nondefault recipients.", nameof(recipients)); }
if (campaigns.TryGetValue(campaignId, out var previous)) { if (previous.Text != text || !previous.Recipients.SequenceEqual(recipients)) { throw new ArgumentException("A campaign ID must retain its original content and recipients."); } await state.WriteStateAsync(); return; }
var campaign = new NotificationCampaign(text, recipients.ToArray()); var root = HierarchicalKey.Create("campaigns", campaignId.ToString("N")); var message = new Notify(text); outbox.Send(messages.Notify, campaign.Recipients.Select(recipient => (new MessageId(root.CreateChildKey(recipient.ToString())), recipient, message))); campaigns.Add(campaignId, campaign); await state.WriteStateAsync(); }}The campaign record and every outgoing intent are captured in the same sender
journal write. The typed batch
Send helper encodes every recipient
command before staging any, so an encoding failure stages nothing, then stages them
in order. The campaign record is added after all sends succeed, and a repeated
submission uses the same recipient command identities and content.
Each destination commits independently through the
notification handler. Each envelope’s
ID is a stable recipient child under the campaign root, with literal grain identity
escaping handled by the key factory. The recipient’s retained inbox completion
record recognizes that notification command. The campaign record also supports
GetCampaignAsync queries. A successful publish response
means the campaign and intents are durable; recipient completion is a later event.
Bound the recipient count and payload size at your ingress according to journal capacity and latency budgets. For larger campaigns, persist a campaign cursor and emit bounded recipient chunks, committing the cursor and each chunk together. If delivery confirmation is needed, have recipients reply with a keyed outcome and let the campaign grain aggregate those results. Retain campaign state for its submission/query horizon and receiver completion facts for the supported resubmission horizon.
Combine the recipes into an order workflow
Section titled “Combine the recipes into an order workflow”A coordinator that receives several subjects registers one typed handler per subject. This example registers inventory and payment result handlers that share one method and records outcomes by their deterministic reply IDs for progress and result queries:
public interface IOrderOutcomesGrain : IGrainWithStringKey{ ValueTask<int> GetCompletedStepCountAsync(); ValueTask<OrderOutcome?> GetOutcomeAsync(MessageId replyId);}
public sealed class OrderOutcomesGrain( IInbox inbox, Messages messages, [FromKeyedServices("order-outcomes")] IDurableDictionary<MessageId, OrderOutcome> outcomes) : Grain, IOrderOutcomesGrain{ public override Task OnActivateAsync(CancellationToken cancellationToken) { inbox .Register(messages.ReservationResult, Record) .Register(messages.PaymentResult, Record); return base.OnActivateAsync(cancellationToken); }
public ValueTask<int> GetCompletedStepCountAsync() => new(outcomes.Count);
public ValueTask<OrderOutcome?> GetOutcomeAsync(MessageId replyId) { outcomes.TryGetValue(replyId, out var outcome); return new(outcome); }
private void Record(OrderOutcome outcome, IInboxHandlerContext context) { outcomes[context.Message.Envelope.MessageId] = outcome; context.Complete(); }}Each registration matches its subject ordinally and decodes the body with its binding. Each handler completes in the same synchronous block as its state update. Decoding failures and subjects without a matching handler follow the processing retry and dead-letter policy.
A per-order coordinator persists its expected step keys and phase, sends
inventory and payment requests, then completes the initiating command. Each
response records its outcome and completes in one local commit. Once all required
steps have succeeded, one transition emits shipment/create.
| Phase | Durable transition |
|---|---|
| Submitted | Save the expected leaf keys and emit stock and payment requests. |
| Waiting | Save each correlated participant result under its reply ID; the inbox recognizes repeated reply commands. |
| Ready | Record the ready phase and emit the separately keyed shipment request. |
| Rejected | Record the business rejection and emit release/refund commands for completed participant steps. |
| Finished | Record shipment or compensation outcomes and retain workflow state for result queries and audit. |
Each transition uses the same prepare-then-synchronous-final-block pattern. Keep
business rejection in the workflow state, dead-letter permanently invalid input with
Fail(reason), and reserve exceptions for transient preparation failures. Use
recorded step outcomes to answer status queries during outages.
Schedule a workflow step
Section titled “Schedule a workflow step”A grain schedules its own later step by sending itself a message with a deliverAt
time. This checkout confirms an order once its grace period elapses, unless the
buyer cancels first:
[GenerateSerializer]public sealed record SubmitCheckout([property: Id(0)] decimal Total);
[GenerateSerializer, Immutable]public sealed record GracePeriodElapsed;
public enum CheckoutStatus { None, Submitted, Cancelled, Confirmed }
public interface ICheckoutGrain : IGrainWithStringKey{ Task CancelAsync(); ValueTask<CheckoutStatus> GetStatusAsync();}
public sealed class CheckoutGrain( IInbox inbox, IOutbox outbox, IDurableStateManager state, Messages messages, [FromKeyedServices("checkout-status")] IDurableValue<CheckoutStatus> status, [FromKeyedServices(DurableJobTimeProviderNames.DurableJobs)] TimeProvider jobClock, IGrainContext grainContext) : Grain(grainContext), ICheckoutGrain{ public static readonly TimeSpan GracePeriod = TimeSpan.FromMinutes(1);
public override Task OnActivateAsync(CancellationToken cancellationToken) { inbox .Register(messages.SubmitCheckout, Submit) .Register(messages.GracePeriodElapsed, Confirm); return base.OnActivateAsync(cancellationToken); }
public ValueTask<CheckoutStatus> GetStatusAsync() => new(status.Value);
public async Task CancelAsync() { if (status.Value == CheckoutStatus.Submitted) { status.Value = CheckoutStatus.Cancelled; } await state.WriteStateAsync(); }
private void Submit(SubmitCheckout checkout, IInboxHandlerContext context) { if (status.Value == CheckoutStatus.None) { var timerId = context.Message.Envelope.MessageId.Key.CreateChildKey("grace-period"); outbox.Send(messages.GracePeriodElapsed, new MessageId(timerId), this, new GracePeriodElapsed(), jobClock.GetUtcNow() + GracePeriod); status.Value = CheckoutStatus.Submitted; } context.Complete(); }
private void Confirm(GracePeriodElapsed elapsed, IInboxHandlerContext context) { if (status.Value == CheckoutStatus.Submitted) { status.Value = CheckoutStatus.Confirmed; } context.Complete(); }}The checkout computes deliverAt from the Durable Jobs clock, which it injects as
the keyed TimeProvider named DurableJobTimeProviderNames.DurableJobs.
The checkout’s inbox accepts the GracePeriodElapsed message in the same journal
write that records the submission, so the scheduled step exists exactly when the
Submitted status does. The scheduled message counts toward the checkout’s
MaxCapacity until it completes. Messaging wakes the grain when the message is due
and runs its handler with the inbox’s retry policy. The handler acts on the current
status, so a cancelled checkout completes the message without changing state.
The message ID is a child of the submission’s ID, and a redelivered submission
finds a recorded status and schedules nothing new.
Choose an application migration pattern
Section titled “Choose an application migration pattern”Move existing application responsibilities into the handler and its typed payload records, using the inbox/outbox commit boundary for outgoing intent:
| Existing application pattern | Messaging pattern |
|---|---|
| Request/reply grain method | Put the stable command ID and subject in the envelope and the response destination in its body; the handler stages a deterministic typed reply with completion. |
| Business update followed by a remote call | Stage the outgoing envelope with the business update; acknowledged outbox state drives delivery and retry. |
| External provider call | Prepare the provider outcome using the canonical command ID, then commit its local query state, reply, and inbox completion together. |
| Notification loop | Call typed Send for each stable recipient identity, record the campaign after successful staging, and await the journal write. |
| Related records and attachments | Put application records and byte[] attachments in one serializable message and use the typed send and handler helpers. |
Preserve command identity and recorded outcomes when moving application workflows. Applications own subject contracts, reply routing, authorization, and ID construction. See Application payload evolution for rolling application-record changes.
Verify your handlers
Section titled “Verify your handlers”Exercise same-ID resubmissions from several grains, conflicting pending request reuse, distinct child commands, out-of-order arrival, and cancellation during local preparation. Assert business state, query outcomes, outgoing envelopes, and completion together. Test activation recovery and ambiguous storage/provider outcomes against the actual providers used in deployment.
The executable documentation examples exercise hierarchical key isolation, typed reservation acceptance, zero/negative-quantity rejections, shortages, polymorphic result round trips, reply-stage failure without stock mutation, permanent invalid-restock, invalid-payment, and invalid-snapshot dead-lettering, checked restock overflow, provider-success/local-cancellation retry, out-of-order projections, typed multi-subject dispatch, campaign batch encoding, scheduled steps on the Durable Jobs clock, and ordinary composite-message round trips. Verify the original reply’s actual journal acknowledgement and the exact completion-retention boundary when testing end-to-end resubmission. For runtime guarantees and operating controls, see Messaging operations.
