Orleans messaging¶
ConnectSoft.Extensions.MessagingModel.Orleans implements the ConnectSoft IEventBus port over Microsoft Orleans. It moves events and commands between services without a message broker. It is the default messaging stack for new services (ADR-0106 §3). MassTransit and NServiceBus remain supported options with licence constraints.
Standards
This page explains concepts. The checkable rules are in the messaging and Orleans standard. The message contracts themselves are described in Messaging Model, and the patterns in Event-Driven Architecture.
What it is¶
The library is a sibling of ConnectSoft.Extensions.MessagingModel.MassTransit and ConnectSoft.Extensions.MessagingModel.NServiceBus. Application code depends only on the abstraction package ConnectSoft.Extensions.MessagingModel: it calls IEventBus.PublishEvent and IEventBus.SendCommand, and implements IEventHandler<T> or ICommandHandler<T>. The transport is chosen at registration.
The library needs:
- an Orleans silo co-hosted in each service (see Microsoft Orleans);
- SQL Server, where the messaging tables live in each service's own database;
- the NHibernate unit of work from
ConnectSoft.Extensions.PersistenceModel.NHibernate, which the outbox writer joins.
It targets .NET 10 and .NET 11 with Orleans 10.
When to use it¶
- A new service that publishes or handles integration events. This is the default.
- A service that already runs an Orleans silo and SQL Server, and has no broker.
- A service that must run without a commercial messaging licence.
Choose another stack only with a recorded reason (CS-MSG-006). See Comparison with MassTransit and NServiceBus.
Architecture¶
Each service is its own Orleans cluster with its own identity, ports and clustering database. A publisher reaches a subscriber by calling a grain in the subscriber's cluster. There is no broker and no Orleans stream in the path.
flowchart LR
A["Domain service"] -->|"PublishEvent in transaction"| B["Outbox tables"]
B --> C["Outbox dispatcher grain"]
C -->|"one delivery per subscriber"| D["Inbox grain"]
D --> E["Inbox table"]
D --> F["Event handler"]
The parts, in the order a message passes through them:
| Part | Where it runs | What it does |
|---|---|---|
NHibernateOutboxWriter |
Publisher | Writes one [Outbox] row inside the business transaction. After the commit it nudges the dispatcher. It refuses a publish outside a transaction. |
OutboxDispatcherGrain |
Publisher | Sharded grain backed by an Orleans reminder. On first dispatch it resolves the recipients from the routing settings and writes one [OutboxDelivery] row per subscriber. It then delivers each due row. |
| Subscriber client | Publisher | For a remote subscriber, an Orleans cluster client built from the subscriber's cluster id, service id and gateway endpoints. For a co-hosted subscriber (Mode: Local), the local grain factory. |
IInboxGrain |
Subscriber | Keyed by the publisher's service name. Checks the contract (message type, schema version, payload), removes duplicates by (DeduplicationScope, MessageId), and calls the registered handlers. |
[Inbox] table |
Subscriber | Records processed messages. A redelivery with the same id and a different payload is quarantined, not applied. |
IOutboxRecovery |
Publisher | Lists poisoned deliveries and blocked ordering keys, and replays or skips them with an audit record. |
The bootstrap creates the messaging schema at startup (default schema ConnectSoftMessaging) unless EnsureSchema is off.
Configuration¶
Both roles read the OrleansMessaging section. An Outbox block turns on the publisher role; an Inbox block turns on the subscriber role. A service can have both.
Publisher:
"OrleansMessaging": {
"ServiceName": "orders-service",
"Outbox": {
"ConnectionString": "Server=localhost;Database=OrdersService;..."
},
"Subscribers": {
"billing-service": {
"Mode": "OrleansClient",
"ClusterId": "billing-service",
"ServiceId": "billing-service",
"GatewayProvider": "Static",
"GatewayEndpoints": [ "127.0.0.1:30003" ]
}
},
"Subscriptions": [
{
"EventType": "Contoso.Orders.MessagingModel.OrderCreatedEvent",
"SubscriberNames": [ "billing-service" ]
}
],
"PublishedEvents": [
{ "EventType": "Contoso.Orders.MessagingModel.OrderCreatedEvent" },
{
"EventType": "Contoso.Orders.MessagingModel.OrderArchivedEvent",
"UnroutedReason": "No service handles archiving yet."
}
]
}
Subscriber:
builder.Services.AddConnectSoftOrleansMessagingInbox(builder.Configuration);
builder.Services.AddConnectSoftEventHandler<OrderCreatedEvent, OrderCreatedHandler>();
"OrleansMessaging": {
"ServiceName": "billing-service",
"Inbox": {
"ConnectionString": "Server=localhost;Database=BillingService;..."
}
}
Notes on the settings:
ServiceNameis the logical name of the service. It is stamped on every message as the source service, and it keys the inbox grain in the subscriber.SchemaNamesets the SQL schema of the messaging tables. A host that sets its own schema, for exampleOrdersMessaging, uses it in every operator query.Subscribersdeclares each subscriber's connection once.SubscriptionsandCommandRoutesrefer to it by name.GatewayProviderisStatic(fixed gateway endpoints) orAdoNet(the client reads the subscriber cluster's membership table).AdoNetneeds the subscriber's membership connection string in the publisher.- Options are validated at startup. A host with an invalid value fails with an
OptionsValidationExceptionthat names each key.
The full list of options and defaults is in the library's options reference (docs/design/options-configuration.md in the library repository). Clustering setup for the silo is described in Orleans Clustering (ADO.NET).
Event routing and subscriptions¶
Routing is decided by the publisher's settings. Registering a handler in a subscriber does not change what the publisher sends.
- Each event type in
Subscriptionsmaps to one or more subscriber names (fan-out). - Each command type in
CommandRoutesmaps to exactly one subscriber. An unrouted command fails atSendCommand. A command routed twice fails at startup. - Every event the service publishes must be listed in
PublishedEvents, with a subscription or anUnroutedReason, not both. Startup fails otherwise, and publishing an undeclared event throws. - An event declared with an
UnroutedReasonis stored with statusUnrouted. It is counted on its own counter and delivered to nobody.
Without these declarations, an event with no route is a silent drop: the publish succeeds, the handler's tests pass, and nothing arrives. The declaration check is on by default (RequirePublishedEventDeclarations). See CS-MSG-002.
Routes and subscriber addresses live in each settings file of the publisher, and the environment-specific subscriber addresses belong in the deployment pipeline settings. A route missing from one variant drops events in that environment only. See CS-MSG-004.
Two checks help after a change:
IRouteVerifier.VerifyAsyncasks each subscriber for its manifest (handled types and accepted schema versions) and reports each route as Handled, NotHandled, IncompatibleSchemaVersion or Unknown. Unknown means the subscriber was not reachable, which is not an error by itself.- A subscriber with no handler for a delivered type answers
UnknownMessageType, and the delivery is poisoned at the publisher.
Reliability¶
Delivery is at least once. Nothing is exactly once.
Outbox and ordering¶
- The outbox row and the business change commit in one transaction (CS-MSG-003). A rolled-back change sends nothing; a committed change is never lost.
- Messages that share an
OrderingKeyreach each subscriber in commit order, across restarts and shards. Use the id of the aggregate the transaction changes. Messages with different keys never wait for each other. There is no order across keys or across publishers. - Each subscriber's delivery has its own status, attempt count and back-off. A failing subscriber does not delay a healthy one, and a delivered message is not sent again because a sibling failed.
Retries¶
| Failure | Example | Effect |
|---|---|---|
| Not attempted | Subscriber unreachable, connect timeout, subscriber in cooldown | Deferred. The attempt count does not change. |
| Attempted | Handler threw, delivery timeout, silo died during the call | Retried with exponential back-off and jitter (defaults: 5 s base, 5 min cap, 10 attempts), then poisoned. |
| Contract | Unknown type, unsupported schema version, malformed payload, same id with a different payload | Poisoned at once. Retrying cannot help. |
Poisoned deliveries instead of dead letters¶
There is no dead-letter queue. A delivery that cannot succeed stays in [OutboxDelivery] with status poisoned, together with the error that poisoned it. Only that subscriber is affected.
When a message with an ordering key is poisoned, its followers for that subscriber wait by default (Halt). A publisher can set Skip per message so that followers proceed. An operator fixes the cause and then replays or skips the message through IOutboxRecovery. Replay keeps the message id, so an inbox that already processed it answers Duplicate. Every replay and skip is written to [OutboxRecoveryAudit]. A message older than the replay horizon (default 21 days) is refused unless the operator forces it.
Idempotency¶
- The inbox removes duplicates by
(DeduplicationScope, MessageId)and keeps its records forInbox:RetentionDays(default 30 days). - A handler that claims the message with
IInboxClaiminside its own transaction commits its change and its inbox record together. - Any other handler may run more than once and must be idempotent (CS-MSG-005).
- Handlers accept schema version 1 by default. A handler declares further versions when it registers.
Payloads over 1 MB are refused. Carry a reference to large content instead.
Operations¶
The library repository contains an operations runbook (docs/Runbook.md in ConnectSoft.Extensions.MessagingModel.Orleans). It covers:
- where the messaging tables live and how long rows are kept;
- the metrics and suggested alerts (poisoned, blocked and deferred deliveries, quarantined messages, oldest pending age);
- SQL queries to diagnose a stalled dispatcher;
- recovery of poisoned and blocked messages through
IOutboxRecovery, and its HTTP surface in the separateConnectSoft.Extensions.MessagingModel.Orleans.AspNetCorepackage; - route verification after a deployment;
- schema upgrade, application rollback and changing the shard count.
Metrics use the meter ConnectSoft.Extensions.MessagingModel.Orleans, and traces use the activity source exposed by OrleansMessagingDiagnostics. The readiness health check (AddConnectSoftOrleansMessagingOutboxHealthCheck) reports backlog age and depth. Poisoned and deferred deliveries are alert signals, not readiness failures.
Do not update the outbox tables by hand. Use the recovery API, which keeps the audit and the ordering rules.
Grain code in a service follows the async and Orleans grain rules, for example CS-ASY-002 and CS-ORL-002.
Comparison with MassTransit and NServiceBus¶
| Orleans messaging | MassTransit | NServiceBus | |
|---|---|---|---|
| Position | Default for new services | Supported option | Supported option |
| Licence | No commercial licence | Version 9 needs MT_LICENSE; held at 9.2.6 (ADR-0103) |
Commercial licence for production |
| Broker or transport | None. Uses the service's Orleans silo and SQL Server | A broker such as RabbitMQ or Azure Service Bus | A transport such as SQL Server, RabbitMQ or Azure Service Bus |
| Outbox | Built in, in the service's database | Optional | Optional |
| Failed messages | Poisoned per subscriber, replayed through an audited API | Retries and error queues | Retries and error queue, with ServiceControl |
| Request/reply and sagas | Not provided | Request/response and saga state machines | Request/response and sagas |
| Choose when | A new service, or any service without a reason to choose otherwise | An existing broker or a saga requirement, with the reason recorded | An existing NServiceBus estate or a client mandate, with the reason recorded |
See MassTransit and NServiceBus for those stacks.