Skip to content

Messaging and Orleans standard

This page sets the rules for publishing and handling messages and for writing Orleans grain code in ConnectSoft services. It is written for engineers who add events, commands, handlers, subscribers or grains, and for their reviewers. Rules with the CS-MSG prefix cover messaging; rules with the CS-ORL prefix cover grain code. The message model is explained in Messaging Model and the patterns in Event-Driven Architecture.

The default messaging stack

Orleans messaging through ConnectSoft.Extensions.MessagingModel.Orleans is the default for new services; MassTransit and NServiceBus are supported options with licence constraints (ADR-0106 §3). With Orleans messaging:

  • the publisher writes each message to an outbox table in its own database, inside the business transaction;
  • a dispatcher delivers the message to each subscriber listed in the publisher's settings;
  • the subscriber's inbox removes duplicates by message id before the handler runs;
  • delivery is at least once.

The rules below are written for that stack. Where a rule names an Orleans messaging setting, a service on another stack applies the same intent with that stack's equivalent.

Messaging rules

CS-MSG-001: Name events and commands with their suffix

Severity: major · Applies to: service, library, template · Enforced by: manual · Status: active

Why

The suffix tells a reader whether a message announces a fact or asks for an action, which decides who may publish it and how many handlers it may have. The convention is settled by ADR-0105 §5.

Do

  • Name an event in the past tense with the Event suffix, for example OrderCreatedEvent.
  • Name a command in the imperative with the Command suffix, for example CreateOrderCommand.
  • Keep message contracts as plain classes in the *.MessagingModel project, with no transport types in them.

Don't

  • Name an event without the suffix, or in the present tense, such as OrderCreate.
  • Name an event in the imperative or a command in the past tense.

Example

public class OrderCreatedEvent : IEvent
{
    public Guid OrderId { get; set; }
}

public class CreateOrderCommand : ICommand
{
    public Guid OrderId { get; set; }
}

How to check

New types in *.MessagingModel end in Event or Command and follow the tense rule.

CS-MSG-002: Declare every published event with its subscribers or an unrouted reason

Severity: blocker · Applies to: service, template · Enforced by: manual (target: ENF-041) · Status: active

Why

Registering a handler in the subscriber changes nothing on the wire. The publisher delivers an event only to the subscribers its own settings route it to. Without a route, the event is dropped. The handler's unit tests and the publisher's tests stay green, and nothing arrives. Orleans messaging refuses to start, and refuses to publish, when an event is not declared, so the route decision is made on purpose.

Do

  • Add every event the service publishes to OrleansMessaging:PublishedEvents.
  • For each event, either add a subscription with its SubscriberNames, or give an UnroutedReason that says why no service handles it yet.
  • When you add a handler in a subscriber, add the route in the publisher in the same change, or in a change that is merged first.
  • After a change to routes or handlers, run the route verification (IRouteVerifier) against the deployed publisher.

Don't

  • Add a handler without a route in the publisher.
  • Use UnroutedReason to hide a route that is needed.
  • Set OrleansMessaging:RequirePublishedEventDeclarations to false.

Example

"OrleansMessaging": {
  "Subscriptions": [
    { "EventType": "Company.Orders.MessagingModel.OrderCreatedEvent", "SubscriberNames": [ "company-invoices" ] }
  ],
  "PublishedEvents": [
    { "EventType": "Company.Orders.MessagingModel.OrderCreatedEvent" },
    { "EventType": "Company.Orders.MessagingModel.OrderArchivedEvent", "UnroutedReason": "No service handles archiving yet." }
  ]
}

How to check

  • Every PublishEvent call in the change publishes an event declared in PublishedEvents.
  • Every AddConnectSoftEventHandler<TEvent, THandler>() added in a subscriber has a matching subscription in the publisher.
  • When a route check script is used, compare its "handlers checked" count with the number of handler registrations before trusting a green result.
  • No settings file in the change sets OrleansMessaging:RequirePublishedEventDeclarations to false.

CS-MSG-003: Publish inside the unit-of-work transaction

Severity: blocker · Applies to: service, template · Enforced by: manual · Status: active

Why

The outbox row is written in the same database transaction as the business change. Either both commit or neither does, so an event is never sent for a change that was rolled back and never lost for a change that was committed. A publish outside a transaction commits the message on its own. Orleans messaging therefore refuses it unless AllowNonTransactionalPublish is set.

Do

  • Call PublishEvent inside the ExecuteTransactional or ExecuteTransactionalAsync delegate that writes the change, as CS-SVC-004 requires.
  • Pass an ordering key, such as the aggregate id, when subscribers need the messages of one aggregate in commit order.

Don't

  • Set OrleansMessaging:Outbox:AllowNonTransactionalPublish to true.
  • Publish after the transaction has committed, or from a controller.

How to check

  • Every PublishEvent call in the change is inside a transactional delegate.
  • No settings file sets AllowNonTransactionalPublish to true.

CS-MSG-004: Configure each route in every settings variant and in the deployment pipeline

Severity: major · Applies to: service, pipelines, template · Enforced by: manual · Status: active

Why

The publisher reads its routes and subscriber addresses from its own settings, and each host variant has its own file: the base file, Development, Docker and the acceptance test hosts. A route that is missing from one variant drops events in that environment only. Where several environments share a machine, a subscriber address that the deployment does not override points the publisher at another environment's cluster, and the events are delivered there.

Do

  • Add a new route or subscriber to every appsettings*.json of the publisher that configures OrleansMessaging, including the acceptance test hosts.
  • Add the environment-specific subscriber settings (cluster id, service id and gateway endpoints) to the deployment pipeline's settings for each environment.
  • After a deployment, read the deployed subscriber settings.

Don't

  • Rely on the base file's subscriber addresses in a deployed environment.

How to check

  • The change adds the route to every settings variant of the publisher.
  • A new subscriber has pipeline settings for each environment it is deployed to.

CS-MSG-005: Make every handler idempotent

Severity: major · Applies to: service, template · Enforced by: manual · Status: active

Why

Delivery is at least once. A message can arrive again after a timeout, a retry, a replay from the outbox or a redeployment. The inbox removes duplicates by message id, but a handler that does work outside its own transaction, or a message replayed under a new id, can still be applied twice.

Do

  • Write each handler so that applying the same message twice leaves the same state as applying it once, for example by checking the current state before changing it.
  • Where the handler changes data, claim the message in the handler's own transaction with IInboxClaim, so the claim and the change commit together.
  • Make side effects outside the database, such as e-mails or calls to other services, safe to repeat or guarded by a stored marker.

Don't

  • Assume that a message arrives exactly once.
  • Increment a counter or append a row without checking whether the message was already applied.

How to check

  • Each new handler has a test that delivers the same message twice and asserts the state after the second delivery.
  • Each new handler that changes data calls IInboxClaim inside the same transaction as the change.

CS-MSG-006: Choose a non-default messaging stack only with a recorded reason

Severity: minor · Applies to: service, template · Enforced by: manual · Status: active

Why

MassTransit 9 and NServiceBus need commercial licences, and every stack has its own outbox, retry and routing model. ADR-0106 §3 makes Orleans messaging the default so that a reviewer can tell a deliberate choice from drift.

Do

  • Use Orleans messaging for a new service.
  • Record the reason when a service uses MassTransit or NServiceBus, for example an existing broker, a saga requirement or a client mandate, in an ADR or the service README.

Don't

  • Add MassTransit or NServiceBus to a service without a recorded reason.
  • Move MassTransit past the version held by ADR-0103.

How to check

A new reference to MassTransit or NServiceBus comes with a recorded reason.

CS-MSG-007: Carry the initial value of every projected field on the creation event

Severity: major · Applies to: service, template · Enforced by: manual · Status: active

Why

A subscriber that keeps a projection learns a field's value only from events. When only a "changed" event carries the field, every record that is created and never changed keeps an empty value in the projection, and rules that read the field miss those records.

Do

  • Put the initial value of each field that subscribers project on the event that announces the creation.
  • Write the field in the projection from both the creation event and the change event.

Don't

  • Add a projected field that only a change event writes.

How to check

For each projected field, a projection test applies the creation event alone and asserts the field's initial value.

CS-MSG-008: Signal the outbox dispatcher only after the transaction commits

Severity: major · Applies to: library, service, template · Enforced by: manual · Status: active

Why

A dispatcher signalled inside the unit of work wakes before the outbox row is visible, finds nothing, and goes back to sleep. The message then waits for the next signal or for the periodic sweep, which turns sub-second delivery into a delay of tens of seconds with no error and no retry.

Do

  • Signal the dispatcher from an after-commit callback of the transaction that wrote the outbox row.
  • Keep the periodic sweep as the fallback, not as the delivery path.

Don't

  • Signal the dispatcher from inside the transactional publish.

How to check

An integration test publishes one message on an idle host and asserts that it is dispatched well within the periodic sweep interval.

CS-MSG-009: Give each service interface one owner when optional modules can register it

Severity: major · Applies to: library, service, template · Enforced by: manual · Status: active

Why

When two optional modules each register the same interface, such as the event bus, dependency injection resolves the last Add and ignores every later TryAdd. Which implementation runs then depends on registration order, and nothing reports the one that was dropped.

Do

  • Register module-specific implementations as keyed services, under the module's name.
  • Register the unkeyed interface in one place that chooses the implementation explicitly, for example from configuration.
  • Keep a container test for each supported combination of modules that asserts which implementation resolves.

Don't

  • Register the same unkeyed interface with AddSingleton in more than one optional module.
  • Mix Add and TryAdd registrations for one interface.

How to check

  • Search the change for registrations of an interface that another module also registers, and check that one place owns the unkeyed registration.
  • No interface in the change is registered with both Add... and TryAdd... calls.

Orleans grain rules

CS-ORL-001: Never use ConfigureAwait(false) in grain code

Severity: blocker · Applies to: service, library, template · Enforced by: manual · Status: retired

Replaced by: CS-ASY-002. The grain rule is part of the async rule for grains and components.

CS-ORL-002: Never block on async code that a grain can reach

Severity: blocker · Applies to: service, library, template · Enforced by: manual · Status: active

Why

A blocking wait such as .GetAwaiter().GetResult() holds the activation's only thread. When the awaited work needs that activation, or another call that queues behind it, the grain deadlocks. The same code can work from a controller, which runs on the thread pool, so the defect appears only when a grain starts calling it.

Do

  • Await asynchronous calls all the way down from a grain.
  • When a grain starts calling an existing service method, check that the method and its callees do not block.

Don't

  • Call .Result, .Wait() or .GetAwaiter().GetResult() in grain code or in code that a grain calls.

How to check

Search the change, and the methods a changed grain calls, for .Result, .Wait( and GetAwaiter().GetResult().

CS-ORL-003: Resolve scoped services in a grain through a new scope

Severity: major · Applies to: service, template · Enforced by: manual · Status: active

Why

A grain lives longer than a request, and its constructor runs outside any request scope. A scoped service such as a unit of work or a database session that is injected into the grain's constructor is shared by every call to the activation, or cannot be resolved at all.

Do

  • Inject IServiceScopeFactory into the grain.
  • For each call that needs scoped services, create a scope with CreateScope() or CreateAsyncScope(), resolve the services from it and dispose it at the end of the call.

Don't

  • Inject a unit of work, a repository or another scoped service directly into a grain's constructor.

How to check

Grain constructors in the change take only singleton services, grain services and IServiceScopeFactory.

CS-ORL-004: Key grains by the identifier of the thing they represent

Severity: minor · Applies to: service, template · Enforced by: manual · Status: active

Why

A grain key that equals the aggregate id makes the grain for an aggregate easy to find from logs, messages and the database, and guarantees one activation per aggregate. A key built from several parts in different places drifts and creates two grains for one thing.

Do

  • Use the aggregate's Guid id as the grain key.
  • When a compound key is needed, build it in one static method next to the grain interface and document its format there.

Don't

  • Build a grain key from string concatenation at each call site.

How to check

Each GetGrain<T>(...) call in the change passes an aggregate id or the result of the grain's key method.

CS-ORL-005: Start a fake clock at the test's baseline time

Severity: major · Applies to: service, template · Enforced by: manual · Status: active

Why

Orleans runtime timers use the host's TimeProvider. When a test moves a FakeTimeProvider forward by months or years, every timer replays each of its missed ticks, and the test host hangs before the first step runs. The hang looks like a database or transport problem.

Do

  • Pass the baseline time of the test to the FakeTimeProvider constructor (CS-TIM-004).
  • Move the clock forward only by the amount the scenario needs.

Don't

  • Call SetUtcNow or Advance with a jump of years on a host that runs Orleans.

How to check

Fake clocks in Orleans acceptance tests are created with an explicit start time close to the times the scenarios use.

CS-ORL-006: Reference the Orleans SDK directly in every project with grains

Severity: blocker · Applies to: service, library, template · Enforced by: manual · Status: active

Why

Orleans generates the code that makes grains callable at build time, through the generator in its SDK package. A project that receives the generator only transitively loses it when another package drops the dependency. The build and the unit tests still pass, and every host fails at run time to find an implementation for the grain interfaces.

Do

  • Add a direct reference to the Orleans SDK package to every project that contains grains or grain interfaces.
  • Keep a test that checks the built assembly for generated code and for its application-part attribute.

Don't

  • Rely on a runtime, server or client package to bring in the code generator.

How to check

Every project that contains a Grain subclass or an IGrainWith* interface references the Orleans SDK package directly.

CS-ORL-007: Confirm a host has stopped before starting another instance of it

Severity: minor · Applies to: service, pipelines · Enforced by: manual · Status: active

Why

A silo with a fixed cluster identity and fixed ports cannot run twice. When a restart script starts a second instance while the first is still alive, the cluster evicts the original, which stops without a word in its own log, and the new instance fails to bind its ports.

Do

  • In restart and supervision scripts, stop the old process, wait for it to exit and for its ports to be free, and only then start the new one.
  • Treat one slow health probe as slow, not as dead. Decide a process is dead only after several failed probes or when it has exited.

Don't

  • Start a host instance while another instance with the same identity may still be running.

How to check

Restart scripts check process exit and free ports before they start a host.