Chatter.MessageBrokers
0.32.1
See the version list below for details.
dotnet add package Chatter.MessageBrokers --version 0.32.1
NuGet\Install-Package Chatter.MessageBrokers -Version 0.32.1
<PackageReference Include="Chatter.MessageBrokers" Version="0.32.1" />
<PackageVersion Include="Chatter.MessageBrokers" Version="0.32.1" />
<PackageReference Include="Chatter.MessageBrokers" />
paket add Chatter.MessageBrokers --version 0.32.1
#r "nuget: Chatter.MessageBrokers, 0.32.1"
#:package Chatter.MessageBrokers@0.32.1
#addin nuget:?package=Chatter.MessageBrokers&version=0.32.1
#tool nuget:?package=Chatter.MessageBrokers&version=0.32.1
<a name="chatter-messagebrokers"></a> Chatter.MessageBrokers
Technology-agnostic brokered messaging for .NET, built on Chatter.CQRS.
Overview
Chatter.MessageBrokers adds brokered (out-of-process) messaging on top of Chatter.CQRS. It lets you receive messages from a broker and dispatch them to your existing IMessageHandler<TMessage> commands and events, and send/publish/forward messages back out — all without coupling your domain code to a specific broker technology.
The package defines the abstractions and the orchestration (receiving loop, dispatching, routing, reliability, recovery) but ships no concrete transport. The broker-facing interfaces (IMessagingInfrastructureReceiver, IMessagingInfrastructureDispatcher, IBrokeredMessagePathBuilder, etc.) are implemented by a sibling package. Pick one:
- Chatter.MessageBrokers.AzureServiceBus — Azure Service Bus queues/topics.
- Chatter.MessageBrokers.SqlServiceBroker — SQL Server Service Broker.
You register Chatter.MessageBrokers plus one infrastructure package, and the core wires everything together.
Installation
dotnet add package Chatter.MessageBrokers
Then add a concrete broker, e.g.:
dotnet add package Chatter.MessageBrokers.AzureServiceBus
Getting Started
1. Register with DI
Chatter.MessageBrokers extends the Chatter.CQRS builder. The primary entry point is AddMessageBrokers on IChatterBuilder:
using Microsoft.Extensions.DependencyInjection;
services.AddChatterCqrs(configuration)
.AddMessageBrokers(options =>
{
options.WithTransactionMode(TransactionMode.ReceiveOnly);
})
// then add a concrete infrastructure, e.g.:
.AddAzureServiceBus(/* ... */);
AddMessageBrokers scans your assemblies for message types decorated with BrokeredMessageAttribute, and for every type whose receivingPath is set it auto-registers a receiver as a hosted background service. It also registers the dispatcher, routers, recovery strategy, in-memory inbox/outbox, and the default body converters (JsonBodyConverter, TextPlainBodyConverter).
There are several overloads to control which assemblies are scanned for receivers — by marker type, explicit Assembly[], or a namespace wildcard selector:
.AddMessageBrokers("MyApp.Messages.*", options => { /* ... */ });
.AddMessageBrokers(options => { /* ... */ }, typeof(SomeMarkerType));
2. Mark a message
Decorate a Chatter.CQRS ICommand or IEvent with [BrokeredMessage(...)] to map it to broker paths. Supplying receivingPath tells Chatter to start a receiver for that message automatically.
using Chatter.CQRS.Commands;
using Chatter.MessageBrokers;
[BrokeredMessage(sendingPath: "orders.out", receivingPath: "orders.in")]
public class PlaceOrder : ICommand
{
public Guid OrderId { get; set; }
public string Sku { get; set; }
}
BrokeredMessageAttribute also accepts errorQueueName, messageDescription, infrastructureType, and deadletterQueueName. Either sendingPath or receivingPath is required.
3. Handle the received message
Write a normal Chatter.CQRS handler. When the message arrives on the broker, the receiver deserializes the body and dispatches it to your handler, passing an IMessageBrokerContext (which is an IMessageHandlerContext).
using Chatter.CQRS;
using Chatter.CQRS.Context;
public class PlaceOrderHandler : IMessageHandler<PlaceOrder>
{
public async Task Handle(PlaceOrder message, IMessageHandlerContext context)
{
// ... do work ...
// reply / send / publish back out over the same infrastructure:
await context.Publish(new OrderPlaced { OrderId = message.OrderId });
}
}
4. Send / publish without a handler
Inject IBrokeredMessageDispatcher anywhere to send commands or publish events directly:
public class OrderApi
{
private readonly IBrokeredMessageDispatcher _dispatcher;
public OrderApi(IBrokeredMessageDispatcher dispatcher) => _dispatcher = dispatcher;
public Task PlaceAsync(PlaceOrder cmd) => _dispatcher.Send(cmd); // path from attribute
public Task PlaceAsync(PlaceOrder cmd, string path) => _dispatcher.Send(cmd, path);
}
Core Concepts
Brokered Message
A message received from or sent to broker infrastructure. OutboundBrokeredMessage represents what you send; InboundBrokeredMessage represents what was received (available via IMessageBrokerContext.BrokeredMessage). A Body Converter (IBrokeredMessageBodyConverter, selected by IBodyConverterFactory) serializes/deserializes the body to/from your message type.
Receiver
BrokeredMessageReceiver<TMessage> (interface IBrokeredMessageReceiver<TMessage>) consumes messages from the infrastructure in a loop. It runs inside BrokeredMessageReceiverBackgroundService<TMessage>, an IHostedService. Each decorated, receivable message type gets its own background service, and only one receiver instance per message type runs. The loop receives a message, deserializes it, dispatches it to the handler, then acks / nacks / deadletters based on the outcome. ReceiverOptions carries the receiver path, error/deadletter queue paths, TransactionMode, infrastructure type, and MaxReceiveAttempts (default 10).
Dispatcher
IReceivedMessageDispatcher (ScopedReceivedMessageDispatcher) relays a received brokered message to the matching Chatter.CQRS handler in a fresh DI scope, bridging to the CQRS message dispatcher by message type.
Sender / Publisher / Forwarder
IBrokeredMessageDispatcher is the unified outbound surface, composed of:
IBrokeredMessageSender—Send<TCommand>(...)a command to one destination.IBrokeredMessagePublisher—Publish<TEvent>(...)an event (single or batch) to subscribers.IBrokeredMessageForwarder—Forward(...)a receivedInboundBrokeredMessageto a new destination.
The same operations are available as extension methods on IMessageHandlerContext (context.Send(...), context.Publish(...)) so a handler can react over the same infrastructure that delivered the inbound message. context.InMemory() (IInMemoryDispatcher) provides in-process dispatch; it runs on the caller's own Message Context and Context Container, so a nested dispatch must be awaited before the next one starts — see ADR-0011.
Routing & Forwarding
IRouteBrokeredMessages (default BrokeredMessageRouter) resolves destinations and routes outbound messages to the infrastructure. ForwardingRouter (IForwardMessages) handles forwarding inbound messages; ReplyRouter (IReplyRouter) handles reply-to routing. Message IDs are produced by IMessageIdGenerator (default GuidIdGenerator; CombGuidIdGenerator and HashedBodyGuidGenerator are also provided).
Serialization and wire parity
The Body Converters in this module read and write brokered message bodies through one shared System.Text.Json configuration. Sharing a single configuration is what makes the bytes on the wire, and the tolerance applied when reading them back, a property of the module rather than of whichever call site happened to serialize.
That configuration is internal to the package and is not reachable from outside it: it appears in no public signature, and an application has no handle on it to inspect or reconfigure. What is published is the capability it backs — ChatterJson.Serialize<TValue>(TValue value) and ChatterJson.Deserialize<TValue>(string json). Call those to produce bytes this library reads back identically, and to read bytes it wrote, with the leniency described below applied:
var json = ChatterJson.Serialize(myMessage);
var roundTripped = ChatterJson.Deserialize<MyMessage>(json);
Serialize writes the members of the type you DECLARE rather than those of the runtime type, so a base-typed variable holding a derived instance writes the base's members only.
To CHANGE the format rather than match it, supply your own Body Converter: an IBrokeredMessageBodyConverter, selected by IBodyConverterFactory on the brokered message's content type, carries its own JsonSerializerOptions — see Brokered Message. That is the seam for a different wire format; the two methods above are the seam for this one.
Enum and boolean reading is deliberately lenient
Reading is more permissive than System.Text.Json's own defaults, on purpose. The shared configuration restores read-parity with Newtonsoft.Json, which earlier versions of Chatter serialized with, so that a body written by one version of an application still deserializes in another. During a rolling deploy both versions are on the queue at the same time, and a message must not become undeliverable merely because the two ends disagree about how tolerant a reader ought to be.
Writing is not lenient and is unchanged: an enum is written as its numeric value and a boolean as a bare true / false token, byte-identical to what both Newtonsoft.Json and the System.Text.Json defaults produce.
For a property typed as an enum, all of these are accepted on read:
| JSON value | Read as |
|---|---|
{"Status":1} |
the member whose value is 1 |
{"Status":"Booked"} |
the member named Booked |
{"Status":"booked"} |
the same member — names are matched case-insensitively |
{"Status":999} |
999, whether or not a member is declared with that value |
{"Status":"999"} |
the same, quoted as a string |
{"Status":"-1"} |
-1, for an enum with a signed underlying type |
{"Status":"Booked,Cancelled"} |
both members combined — Newtonsoft's comma syntax, accepted whether or not the enum is [Flags] |
A string that names no declared member and is not a number — {"Status":"NotARealStatus"} — is a genuine error and throws JsonException.
For a property typed bool or bool?, all of these are accepted on read:
| JSON value | Read as |
|---|---|
{"Enabled":true} |
true |
{"Enabled":"true"} |
true, quoted — matched case-insensitively, so "TRUE" and "False" read too |
{"Enabled":" true "} |
true — surrounding whitespace is trimmed |
{"Enabled":"1"} / {"Enabled":"0"} |
true / false |
{"Enabled":1} / {"Enabled":0} |
true / false, as bare numbers |
A bool? reads JSON null as null. Any other quoted value — {"Enabled":"notabool"} — throws JsonException.
Each row above is pinned by a test: WhenSerializing and WhenLenientlyReadingEnumsAndBooleans under tests/Serialization/UsingChatterJson, and WhenConverting under tests/UsingJsonBodyConverter.
Deserialization does not validate enum membership
Note the {"Status":999} row. Deserialization is a wire-format concern and applies no domain rule, so an undefined numeric value round-trips straight into the enum-typed property and the value you are handed names no declared member.
A message handler must validate enum membership itself. Do not assume a deserialized enum value is one of the members you declared; check it — with Enum.IsDefined, or with a guard on the domain type the value feeds — before branching on it. The handler is the only thing that knows what an unrecognised value means for its own work: whether it came from a newer version and should be deadlettered, or whether it can be safely ignored.
The leniency is intentional and will not be tightened
None of the above is an oversight awaiting a fix, and none of it will be narrowed. Tightening a read — rejecting an undefined enum value, say, or refusing a quoted boolean — would make a message written by one version undeserializable by another, which is exactly the rolling-deploy break the parity exists to prevent. The rejection would also land on the receiving side, turning a producer's wire change into a poison message on a queue the producer does not own.
Reliability
Outbox
The Outbox pattern records outgoing messages so they can be published reliably alongside local state changes. Enable it via AddReliabilityOptions:
.AddMessageBrokers(options =>
{
options.AddReliabilityOptions(r => r
.WithOutboxRouting() // route outbound messages through the outbox
.WithOutboxPollingProcessor(5000) // BrokeredMessageOutboxProcessor drains it every 5s
.WithOutboxPollBatchSize(100)); // at most 100 messages per poll (the default)
});
WithOutboxRouting() swaps IRouteBrokeredMessages for OutboxBrokeredMessageRouter. WithOutboxPollingProcessor(...) registers BrokeredMessageOutboxProcessor (an IHostedService). WithOutboxPollBatchSize(...) sets ReliabilityOptions.OutboxPollBatchSize, the most messages a single poll takes; it defaults to 100 and a value below 1 is refused while the options are being built. The default store is InMemoryBrokeredMessageOutbox; WithInMemoryOutboxTimeToLive(minutes) controls its retention.
The shipped in-memory outbox and inbox are registered as process-lifetime singletons, not per DI scope. A receiver's ScopedReceivedMessageDispatcher opens a fresh scope for every delivery, so a per-scope instance would start every poll and every delivery with an empty store: the outbox would never have anything to drain and the inbox would deduplicate nothing. MinutesToLiveInMemory is unchanged in what it means — it is still the outbox's cleanup of already-processed rows — but that cleanup now runs across polls instead of being discarded with the scope it used to live in. One consequence worth calling out: SendToOutbox throwing InvalidOperationException for a repeated MessageId is now reachable in practice, because the store the second call sees is the same store the first call wrote into, rather than a fresh empty one.
Draining: a bounded poll, repeated until the backlog is gone
A single poll takes one Outbox Poll Batch — at most OutboxPollBatchSize unprocessed messages that are due, oldest SentToOutboxAtUtc first — so the cost of a poll is bounded by that number rather than by the size of the backlog. On its own a bounded poll is just a throttle: at the defaults it would ship 100 messages every 5000 ms no matter how far behind the outbox was. So the poller re-polls immediately after a batch of the full size and waits OutboxProcessingIntervalInMilliseconds only after a shorter one, which lets a backlog larger than the batch size leave in one interval instead of one batch per interval (MustRepollImmediatelyAfterAFullOutboxPollBatchAndStopAfterAShortOne). An empty first batch is a short batch, so an idle outbox polls once and waits (MustNotRepollWhenTheFirstOutboxPollBatchIsEmpty). Each poll opens its own DI scope, so draining a large backlog does not accumulate every row of every batch in one store instance.
A full batch carrying no message the drain has not already seen also ends the drain and falls through to the interval wait. OutboxProcessor.Process logs and swallows every dispatch failure, so a batch of exactly the batch size that cannot be dispatched is re-fetched on the next poll; without this no-progress guard it would spin against the store forever and never reach the wait. A message is recognised by its (Id, MessageId) pair — the message id is part of the key because InMemoryBrokeredMessageOutbox never assigns an Id, so an Id-only key would end every one of its drains on the second poll and cap the in-memory outbox at one batch per interval. The seen set spans the whole drain rather than just the poll before, and it is keyed on identity rather than on position, so the same poison batch still ends the drain when it comes back unchanged (MustStopRepollingWhenAFullOutboxPollBatchRepeatsUnchanged), when it comes back reversed (MustStopRepollingWhenAFullOutboxPollBatchRepeatsInADifferentOrder), and when consecutive polls return different subsets of rows sharing one SentToOutboxAtUtc (MustStopRepollingWhenOverlappingOutboxPollBatchesAddNoUnseenMessage). That set is bounded in turn: a drain that has seen 10,000 distinct messages ends and takes the interval (MustEndTheDrainOnceTheDrainIdentityCeilingIsReached), which says the pass has run long enough — not that the store made no progress — and the rest of the backlog is taken by the next poll. The drain also honours the stopping token between polls (MustStopDrainingWhenCancellationIsRequestedMidDrain).
IPollableOutboxStore.GetUnprocessedMessagesFromOutbox documents all three clauses of that contract — the cap, the ordering and the due gate — and InMemoryBrokeredMessageOutbox honours them, ordering before capping (MustReturnNoMoreMessagesThanTheOutboxPollBatchSize, MustReturnOldestSentToOutboxMessagesFirst) and gating before both (MustSpendNoBatchSlotOnAMessageThatIsNotDue). A custom store is asked for all three, not held to them. The no-progress guard rests on none of them: it recognises a re-fetched message by its (Id, MessageId) pair, so a store that caps without ordering cannot defeat the guard, though it can still starve an old row behind newer ones. What the guard does need is that a row keep the same identity across fetches — a store minting a fresh Id every time it fetches the same row makes every poll look like progress, and a poison batch then runs the drain up to its identity ceiling instead of ending it on the following poll. A store that answers with more rows than the cap counts as a full batch — still drained, still terminating — but without the bound on poll cost the cap exists for. GetUnprocessedBatch(batchId) is a lookup by batch id and is not an Outbox Poll Batch: it is neither capped, ordered nor due-gated by this contract (MustLeaveTheBatchQueryUngatedByDuenessAndAttempts). RecordDispatchAttempt is the writer the due gate reads, and it is a default interface implementation that records nothing, so a store written against the previous shape of the interface still compiles and still satisfies the cast at the poll site (OutboxCustomPrimaryImplementingBoth_RecordDispatchAttemptDefaultsToANoOp) — such a store keeps the pre-existing behaviour, its rows staying at zero attempts and due now.
On each poll, the drain dispatches the message to broker infrastructure first and only stamps the row's processed date once that publish has returned. A dispatch that does not succeed spends one attempt on the row and schedules the next one a backoff ahead: OutboxDispatchBackoffBaseInSeconds (default 5) on the first failure, doubling with each further one and stopping at OutboxDispatchBackoffCapInSeconds (default 60), so the waits run 5s, 10s, 20s. The wait is derived from OutboxMessage.DispatchAttempts rather than stored in a column of its own (MustGrowTheScheduledWaitWithTheAttemptsTheRowAlreadyCarries, MustScheduleTheNextAttemptOneBackoffAhead). The backoff is not opt-in — it applies to every host. Giving up is: a row is abandoned only once OutboxMaxDispatchAttempts is configured, and that setting is null, and therefore disabled, by default, so a message whose dispatch keeps failing is re-attempted for good unless an operator asks otherwise (MustAcceptAnOmittedOutboxMaxDispatchAttempts).
Delivery is at-least-once, not exactly-once: a publish that throws leaves the row unprocessed so a later poll retries it once its backoff has elapsed, and a publish that succeeds followed by a mark/commit failure — or a second host instance polling the same durable store concurrently — can dispatch the same message a second time. A handler that is not naturally idempotent should sit behind the Inbox on the receiving side to absorb that duplicate.
Inbox
The Inbox pattern records received messages to enforce idempotent, once-only handling (IBrokeredMessageInbox, default InMemoryBrokeredMessageInbox, applied via InboxBehavior).
The inbox reserves the message id before invoking the handler, not after the handler completes. A concurrent delivery that arrives for the same message id while the first delivery is still in flight finds the id already reserved: it is skipped without the handler being invoked and without throwing. If the handler throws, the reservation is released so a retry re-invokes the handler for that id. Because the reservation exists for the whole time the handler is running, HasBeenReceived reports true for a message id that is still in flight, not only for one whose handler has already completed.
A reservation is leased for the deduplication window described below, exactly as a completed receipt is remembered for it: an id is remembered for the window, and a reservation is honoured for the window. A handler that has not returned by the time the lease elapses therefore holds its id for the window and no longer. Once that long has passed, the reservation is abandoned, and from then on it is treated like any other entry the window has released: a redelivery of that id is handled again, HasBeenReceived reports false for it, and the periodic sweep and the entry cap may both reclaim it. Inside the window nothing changes — a delivery that finds a reservation the window still honours is skipped immediately, and never waits for the reservation's owner or takes the delivery over from it.
The lease does not distinguish a dead handler from a slow one. The inbox has no way to tell whether a handler that has not returned has hung or is simply still working, so it pre-empts both identically: a merely SLOW but perfectly live handler loses its reservation the moment the lease elapses. A redelivery arriving after that point is handled again, so a second handler runs concurrently with the first. When the first one finally completes, its completion stamp is silently discarded — the conditional update it makes no longer matches the reservation it took, which is deliberate, since that reservation belongs to whatever took its place. Nothing is logged for that discarded completion. A handler that can run longer than the deduplication window must therefore be idempotent, and the window should be sized above the slowest handler expected to run behind the inbox. Pinned by MustNeverHoldAnInFlightReservationBeyondTheWindowUnderEveryConfigurableWindow.
Like the outbox, the shipped in-memory inbox is a process-lifetime singleton, so a received message id is remembered across scopes rather than only for the delivery that received it. Being process-lifetime, it needs its own retention policy so it doesn't grow without bound:
InMemoryInboxDeduplicationWindowInMinutes(default60) is the deduplication window and the PRIMARY guarantee. After a receipt completes, a redelivery of the same message id is skipped for this long; once the window has elapsed, that id is handled again. The same window is the lease on an in-flight reservation, so it is also how long a handler that has not returned holds its id. It is mandatory and must be at least1minute; anything below that is refused while the options are being built. The window is the store's only reclamation rule — nothing else releases an entry, and the cap below never takes a reservation the window still honours — so a window that could be switched off would leave an entry the store had no way to remove.InMemoryInboxMaxEntries(default200000) is an out-of-memory safety valve, not the deduplication guarantee. It is refused below1. When the store reaches the cap it first reclaims everything the window has already released — completed receipts past their window, and reservations past their lease — and only then evicts entries the window still owes; if it evicts anything still inside its window, it logs a warning exactly once per store, because the advertised window is no longer being honoured under that load. The one entry the cap will never take is a reservation the window still honours, so the cap bounds memory without cancelling a handler that is still running inside the window it was promised. If every entry holds such a reservation, the store grows past the cap rather than blocking or throwing — and because the window is always positive, that growth is bounded in time unconditionally: every one of those reservations becomes reclaimable once its lease elapses, and the store returns to its cap on the next receipt. Pinned byMustReturnToItsCapOnceTheWindowElapsesForTheEntriesThatGrewPastIt.HasBeenReceivedreportstruefor a reservation the window still honours and for a completed receipt still inside the window, andfalseonce the window has elapsed for either of them.
Expiry is decided on contact, not by the periodic sweep: a receipt that has passed its window is already treated as expired — a redelivery of its id is handled again and HasBeenReceived returns false for it — even before the next sweep has run. The sweep only reclaims the memory such receipts hold; it is not what makes them expire.
Because the store is process-lifetime, sizing the window and the cap together matters: a rough estimate is that a retained entry costs on the order of 200 bytes, so the cap should stay comfortably above deduplication window × peak receipt rate. At the defaults — a 60-minute window and a cap of 200,000 — that bounds sustained throughput to roughly 55 receipts per second before the cap starts truncating the window, and holds the store at an estimated ~40 MB at full occupancy. Raise InMemoryInboxMaxEntries (or shorten InMemoryInboxDeduplicationWindowInMinutes) for a workload that runs hotter than that.
Persistence note: the in-memory inbox/outbox are for development and single-node scenarios. Durable, transactional EF-backed implementations of
IBrokeredMessageInbox/IBrokeredMessageOutbox(plusIUnitOfWork/IPersistanceTransaction) live in a sibling EntityFrameworkCore reliability package.
Recovery
Receiving is wrapped by an IRecoveryStrategy — the default RetryWithCircuitBreakerStrategy combines Retry and Circuit Breaker. Configure it with AddRecoveryOptions:
.AddMessageBrokers(options =>
{
options.AddRecoveryOptions(r => r
.UseExponentialDelayRecovery(maxRetryAttempts: 10) // or UseConstantDelayRecovery(ms) / UseNoDelayRecovery()
.RetryWhen<MyTransientException>() // ADD an exception type to the retry set
.UseRouteToErrorQueueRecoveryAction() // IMaxReceivesExceededAction
.WithCircuitBreaker(cb => { /* CircuitBreakerOptionsBuilder */ }));
});
- Retry —
IRetryStrategy(RetryStrategy) with a pluggableIRetryDelayStrategy:NoDelayRetry(default),ConstantDelayRetry,ExponentialDelayRetry. Default max attempts is 5. An exception is retried when its TYPE matches a registered predicate; the default set contains exactly one, matching a transientBrokeredMessageReceiverException. No default predicate readsException.Message— a handler exception routinely echoes message-body content, and text a caller does not control must not be able to influence recovery.RetryWhen/RetryWhen<TException>add to that set — every registered predicate is evaluated, and any single match is enough to retry — they do not replace or restrict it. - Circuit Breaker —
ICircuitBreaker(CircuitBreaker) halts processing after repeated failures; state lives inICircuitBreakerStateStore(defaultInMemoryCircuitBreakerStateStore). Every call takes exactly one decision from the store —AdmitAsync(openToHalfOpenWaitTime, cancellationToken)— and acts on the admission it was issued rather than reading state to pick a branch, so noawaitcan invalidate the branch it is on. What it does re-check across thatawaitis the caller's cancellation token — not the circuit's state — so a cancellation arriving while the store adjudicates stops the action from running (MustNotRunTheActionWhenCancellationArrivesWhileTheStoreIsAdjudicating). The admission's verdict isRefused(throwsCircuitBreakerOpenExceptioncarrying the store's last exception, without invoking the action),Execute(runs the action against a closed circuit), orTrial(runs the action as one half-open trial). The cooling policy is the store's to adjudicate: whileOpenToHalfOpenWaitTimeInSecondshas not elapsed the store refuses and leaves the circuit open, and the call that finds the period elapsed is admitted to a trial with the open→half-open transition made as part of that same decision. Because the wait now paces the refusal after adjudication, anOpenToHalfOpenWaitTimeInSecondsof0admits the first call after opening straight to a trial instead of refusing it — at the default of15nothing changes. Each half-open admission belongs to an episode, and an outcome is recorded only against the episode it was admitted under: a trial that outlives its episode has its success discarded rather than counted toward closing a later one, and its failure discarded rather than re-opening a circuit a later episode has since healed — the exception it carried does not even become the store's last exception. The circuit trips on the same type-only basis as Retry, from its own separate default set (also exactly one predicate, also the same transientBrokeredMessageReceiverExceptioncheck) — so what to retry and what should trip the circuit are two independently registered decisions rather than one type answering both.IsTrippedBy/IsTrippedBy<TException>add to the trip set the same wayRetryWhenadds to the retry set. A customICircuitBreakerStateStoreimplementsAdmitAsync(openToHalfOpenWaitTime, cancellationToken)plus the two outcome reports —RecordSuccessAsync(admission, successesToClose, cancellationToken)andRecordFailureAsync(admission, ex, failuresToOpen, cancellationToken)— and adjudicates the transition itself: each report re-checks the admission it is handed against the store's own current episode and performs whatever transition that outcome warrants under the store's own synchronization, answeringtrueonly when that report is what moved the circuit. All three members carry theCancellationTokenof the call being adjudicated, whichCircuitBreakerpasses at every call site, so a store whose adjudication is real I/O can carry that cancellation into it; the shipped in-memory store's bodies are synchronous under one lock, so it honours the token by throwing before it takes that lock and recording nothing. A custom store must also measure the cooling interval from a monotonic source rather than from the wall clock —LastStateChangedDateUtcis a diagnostic that no decision reads, and deciding fromDateTime.UtcNowminus that stamp admits a trial early after a forward clock correction and holds the circuit open past the configured wait after a backward one (MustNotAdmitATrialEarlyWhenTheWallClockStampMovesBackward,MustStillAdmitATrialWhenTheWallClockStampMovesForward). The store exposes no unconditional transition command of any kind for a caller to invoke. - Max Receives Exceeded — when a message's delivery count reaches
MaxReceiveAttempts, the receiver deadletters it and runs theIMaxReceivesExceededAction(defaultErrorQueueDispatcher).MaxReceiveAttemptsExceededException/MaxRetryAttemptsExceededExceptionsignal the condition. - Critical Failure / Error Queue — an unrecoverable receive error (
CriticalReceiverException) stops the receiver loop and raises a Critical Failure viaICriticalFailureNotifier(defaultCriticalFailureEventDispatcher, which dispatches aCriticalFailureEvent). Failed messages are routed to the Error Queue (ErrorQueueDispatcher). Poison messages (PoisonedMessageException, e.g. a body that won't deserialize) are deadlettered.
Configuration (appsettings)
Everything configured fluently above can also come from configuration. AddMessageBrokers reads the Chatter:MessageBrokers section automatically: it resolves the section from the IConfiguration the Chatter builder already holds, so no extra call is required. Earlier versions never resolved the section on this entry point, so every key underneath it was discarded — which is why configuration appeared to be ignored.
Four sections are bindable. Each section name is a constant on its builder, so it can be referenced instead of retyped:
| Section | Constant |
|---|---|
Chatter:MessageBrokers |
MessageBrokerOptionsBuilder.MessageBrokerSectionName |
Chatter:MessageBrokers:Reliability |
ReliabilityOptionsBuilder.ReliabilityOptionsSectionName |
Chatter:MessageBrokers:Recovery |
RecoveryOptionsBuilder.RecoveryOptionsSectionName |
Chatter:MessageBrokers:Recovery:CircuitBreaker |
CircuitBreakerOptionsBuilder.CircuitBreakerOptionsSectionName |
The last three are children of the first, so the key paths are identical whether the options are built through AddMessageBrokers or through a standalone FromConfig(services, configuration) on one of the sub-builders. Note that the circuit breaker key is spelled CircuitBreaker even though the property it binds onto is named CircuitBreakerOptions: RecoveryOptions.CircuitBreakerOptions is annotated [ConfigurationKeyName("CircuitBreaker")] precisely so that the one documented key works from both entry points.
Bindable keys and their defaults
The default in each row is the value the fluent builder seeds before configuration is bound, so it is also the value a key keeps when configuration omits it.
Chatter:MessageBrokers
| Key | Type | Default |
|---|---|---|
TransactionMode |
None / ReceiveOnly / FullAtomicityViaInfrastructure |
ReceiveOnly |
Chatter:MessageBrokers:Reliability
| Key | Type | Default |
|---|---|---|
RouteMessagesToOutbox |
bool |
false |
MinutesToLiveInMemory |
double |
10 |
EnableOutboxPollingProcessor |
bool |
false |
OutboxProcessingIntervalInMilliseconds |
int |
5000 |
InMemoryInboxDeduplicationWindowInMinutes |
int |
60 |
InMemoryInboxMaxEntries |
int |
200000 |
OutboxPollBatchSize |
int |
100 |
Chatter:MessageBrokers:Recovery
| Key | Type | Default |
|---|---|---|
MaxRetryAttempts |
int |
5 |
Chatter:MessageBrokers:Recovery:CircuitBreaker
| Key | Type | Default |
|---|---|---|
OpenToHalfOpenWaitTimeInSeconds |
int |
15 |
ConcurrentHalfOpenAttempts |
int |
1 |
NumberOfFailuresBeforeOpen |
int |
5 |
NumberOfHalfOpenSuccessesToClose |
int |
3 |
SecondsOpenBeforeCriticalFailureNotification |
int |
1800 |
A worked appsettings.json, showing every bindable key at its default:
{
"Chatter": {
"MessageBrokers": {
"TransactionMode": "ReceiveOnly",
"Reliability": {
"RouteMessagesToOutbox": false,
"MinutesToLiveInMemory": 10,
"EnableOutboxPollingProcessor": false,
"OutboxProcessingIntervalInMilliseconds": 5000,
"InMemoryInboxDeduplicationWindowInMinutes": 60,
"InMemoryInboxMaxEntries": 200000,
"OutboxPollBatchSize": 100
},
"Recovery": {
"MaxRetryAttempts": 5,
"CircuitBreaker": {
"OpenToHalfOpenWaitTimeInSeconds": 15,
"ConcurrentHalfOpenAttempts": 1,
"NumberOfFailuresBeforeOpen": 5,
"NumberOfHalfOpenSuccessesToClose": 3,
"SecondsOpenBeforeCriticalFailureNotification": 1800
}
}
}
}
}
The table above is the whole configurable surface. The remaining fluent calls — the retry delay strategy (UseNoDelayRecovery, UseConstantDelayRecovery, UseExponentialDelayRecovery), the retry and circuit-breaker exception predicates (RetryWhen, IsTrippedBy), and the max-receives-exceeded action (UseRouteToErrorQueueRecoveryAction) — register services and have no configuration key of their own.
UseExponentialDelayRecovery(int) is the exception to the second half of that: as well as registering the delay strategy it also sets MaxRetryAttempts, clamped to 15 (MustClampMaxRetryAttemptsToFifteenWhenExponentialDelayExceedsCeiling). MaxRetryAttempts is in the table above, so a configured value binds over whatever that call set it to. The clamp is applied ONCE, and the clamped budget is what both the options and the registered delay strategy are tuned to: UseExponentialDelayRecovery(30) gives the strategy the same clamped budget the options ended up carrying, so each wait caps at the delay the fifteenth attempt schedules rather than at the far longer cap the discarded argument would have bought (MustTuneTheResolvedExponentialDelayStrategyToTheClampedMaxRetryAttempts). That is the relationship issue #423 left open, and it is settled here.
Precedence: configuration wins
Builder defaults are applied first and configuration is bound over them last, so a key present in configuration wins — over the builder default and over an explicit fluent call alike — while a key absent from configuration keeps the builder default. Configuration is bound into the options instance the builder already created, with non-public binding enabled, and never replaces that instance.
The honest reason an explicit fluent call loses is that these builders carry no nullable sentinel: they cannot distinguish an option that was never set fluently from one that was set to the same value as the default, so there is nothing for the bind to skip over.
Chatter.MessageBrokers.AzureServiceBus applies the opposite rule: its builder holds each fluent value in a nullable sentinel (int?, bool?, TimeSpan?), can therefore tell "never called" from "called with the default value", and lets an explicit fluent call win over configuration. The divergence is deliberate, and an application that configures both modules needs to know that the same-looking fluent call is authoritative in one module and overridable in the other.
In practice this means a TransactionMode in configuration overrides WithTransactionMode(...), and an OutboxProcessingIntervalInMilliseconds in configuration overrides WithOutboxPollingProcessor(2000):
// Chatter:MessageBrokers:TransactionMode = "FullAtomicityViaInfrastructure" in appsettings
// wins over the fluent call below; remove the key to let the fluent value stand.
.AddMessageBrokers(options =>
{
options.WithTransactionMode(TransactionMode.ReceiveOnly);
});
Precedence is settled once, while the options are being built, and the settled result is the only thing any injection style can see: IOptions<T>, IOptionsSnapshot<T> and IOptionsMonitor<T> resolve the same instance as injecting the concrete options type — see Every injection style resolves the same options instance.
Configured values are refused at build time
Three kinds of bad configuration fail in three different places, and two of the three fail while the options are being built.
A value of the wrong TYPE fails during Build(), at the binder. MinutesToLiveInMemory: "abc", RouteMessagesToOutbox: "not-bool", a circuit-breaker count that is not a number, or a TransactionMode naming no member of the enum cannot be converted, so ConfigurationBinder throws an InvalidOperationException out of Build() before anything downstream sees the value. The message carries the full key path, such as Chatter:MessageBrokers:Reliability:MinutesToLiveInMemory. Nothing in this module raises it; it is the binder's own failure, surfacing wherever the builder runs, which for AddMessageBrokers is host start.
A value of the right type can still be refused during Build(), by this module. The refusal is a ConfiguredValueRefusedException (Chatter.MessageBrokers.Exceptions) — this module's own named failure for a semantic case, in this module's vocabulary rather than the binder's or the sink's. It carries OptionName (the offending property, qualified by its options type), RefusedValue, RequiredBound and ConfigurationPath, the section the refusing builder actually resolved, including a custom section name the builder was retargeted onto (MustNameTheRefusedPropertyValueBoundAndResolvedSectionPathWhenAConfiguredValueIsRefused, MustNameTheResolvedCustomSectionPathWhenAConfiguredValueIsRefusedThroughACustomSectionName). ConfigurationPath is null when the refusing builder resolved no section of its own, and the option name still identifies the property in that case.
Validation is its own phase, between resolving the options graph and publishing it, and it walks the FINALIZED graph — after the outermost bind, before any registration. A value configured for a NESTED option is reached even though the nested builders have no configuration section of their own, because such a value only lands on the graph after the parent bind.
These are the values that are refused:
| Option | Refused when |
|---|---|
MessageBrokerOptions.TransactionMode |
the enum does not define it |
ReliabilityOptions.OutboxProcessingIntervalInMilliseconds |
below 0, -1 included, when the outbox polling processor is enabled |
ReliabilityOptions.MinutesToLiveInMemory |
NaN or Infinity |
ReliabilityOptions.InMemoryInboxMaxEntries |
below 1 |
ReliabilityOptions.InMemoryInboxDeduplicationWindowInMinutes |
below 1 |
ReliabilityOptions.OutboxPollBatchSize |
below 1 |
RecoveryOptions.MaxRetryAttempts |
below 1 |
CircuitBreakerOptions.ConcurrentHalfOpenAttempts |
below 1 |
CircuitBreakerOptions.OpenToHalfOpenWaitTimeInSeconds |
negative, or longer than Task.Delay can wait |
CircuitBreakerOptions.SecondsOpenBeforeCriticalFailureNotification |
negative, or longer than Timer.Change can schedule |
Each row is pinned: MustAcceptEveryNumericTransactionModeTheEnumDefines and MustRefuseANumericTransactionModeTheEnumDoesNotDefine for the transaction mode; MustAgreeWithTheOutboxPollingSinkAboutAConfiguredProcessingInterval for the poll interval; MustAgreeWithTheExpiryScanAboutAConfiguredMinutesToLiveInMemory, MustRefuseAConfiguredNaNMinutesToLiveInMemoryTheExpiryScanDoesNotDisableItselfFor and MustRefuseAConfiguredInfiniteMinutesToLiveInMemoryTheExpiryScanRunsWithoutFaulting for the in-memory ttl; MustRefuseAConfiguredInMemoryInboxMaxEntriesOfZero and MustRefuseAConfiguredNegativeInMemoryInboxMaxEntries for the inbox cap; MustRefuseAConfiguredInMemoryInboxDeduplicationWindowOfZero, MustRefuseAConfiguredNegativeInMemoryInboxDeduplicationWindow and MustAcceptTheSmallestInMemoryInboxDeduplicationWindowTheSettingCanExpress for the deduplication window; MustRefuseAConfiguredOutboxPollBatchSizeOfZero and MustRefuseAConfiguredNegativeOutboxPollBatchSize for the poll batch size; MustRefuseAConfiguredMaxRetryAttemptsBelowTheSmallestBudgetTheRetryStrategyCanExpress and MustAcceptTheSmallestMaxRetryAttemptsTheRetryStrategyCanExpress for the attempt budget; MustRefuseAConfiguredConcurrentHalfOpenAttemptsOfZero, MustRefuseAConfiguredNegativeConcurrentHalfOpenAttempts and MustAcceptTheSmallestConcurrentHalfOpenAttemptsTheSemaphoreAdmits for the half-open count.
Two reliability rows read alike but are asked of different hosts. OutboxProcessingIntervalInMilliseconds is refused only when EnableOutboxPollingProcessor is set, because the only thing that waits on it is registered behind that flag, so a stale out-of-range interval is inert on a host that never polls. OutboxPollBatchSize is refused on every host, poller enabled or not: it carries its default as a property initializer rather than taking it from the builder, and a batch size of zero is not inert the way an unread interval is — it reads like a limit and drains nothing the moment the poller is switched on.
The upper bound on the two circuit-breaker durations is a constant derived from the BCL's maximum supported timeout rather than probed at run time. It is straddled by two theories that offer the seconds either side of it to a real Task.Delay and a real Timer.Change and require the builder to agree with whichever answer the sink gives (MustAgreeWithTaskDelayAboutAConfiguredOpenToHalfOpenWaitTime, MustAgreeWithTimerChangeAboutAConfiguredTimeOpenBeforeCriticalEvent), so a move in either BCL bound is loud rather than silent.
Values that are deliberately still accepted:
- a zero
OutboxProcessingIntervalInMilliseconds.Task.Delaycompletes it immediately, so how aggressively the outbox is polled stays the operator's call (MustAgreeWithTheOutboxPollingSinkAboutAConfiguredProcessingInterval). - a non-positive
MinutesToLiveInMemory. That is the outbox's ownttl <= 0disabled-cleanup branch, not a degenerate value (MustAgreeWithTheExpiryScanAboutAConfiguredMinutesToLiveInMemory). The asymmetry withInMemoryInboxDeduplicationWindowInMinutes, which IS refused below1, is deliberate: this one governs cleanup of outbox rows that have already been processed, so disabling it only retains them, whereas the inbox window is that store's only reclamation rule and disabling it would leave an entry nothing could remove. - a zero
OpenToHalfOpenWaitTimeInSeconds, which is load-bearing rather than degenerate: a zero wait is always already elapsed, so an open circuit never refuses and the very next call is trialled instead (MustAcceptAConfiguredOpenToHalfOpenWaitTimeOfZero,MustTrialTheOpenCircuitOnTheCallThatFindsItsCoolingPeriodElapsed). - a
NumberOfFailuresBeforeOpenorNumberOfHalfOpenSuccessesToCloseof zero. The state store counts both as++count >= threshold, so no value faults them, and a threshold of 1 or less states "trip, or close, on the first" — intent an operator is entitled to express (MustAcceptAConfiguredCountThresholdOfZero).
What is still left to the sink. ReceiverOptions.MaxConcurrentCalls below 1 raises an InvalidOperationException naming the receiver when that receiver initializes; ReceiverOptions is not on the bindable surface above and no builder here inspects it.
The refusal set is scoped to what configuration can reach — the keys in the table above and the nested options composed under them. A fluent-only argument with no configuration key and no field on the options it tunes sits outside that scope by decision rather than by oversight, UseConstantDelayRecovery(int) being the one worth naming: its argument is recorded on the builder, reaches the registered delay strategy directly, is never stored on RecoveryOptions, and is not validated.
Every injection style resolves the same options instance
MessageBrokerOptions, ReliabilityOptions, RecoveryOptions and CircuitBreakerOptions are each registered twice over the one instance their builder finished: once as the concrete type, and once behind IOptions<T>, IOptionsSnapshot<T> and IOptionsMonitor<T>. Injecting IOptions<RecoveryOptions> therefore hands back exactly the object RecoveryOptionsBuilder.Build() produced — fluent defaults applied, configuration bound over them — and so does injecting RecoveryOptions directly. Every default in the tables above now holds on every injection style rather than only on direct injection of the concrete type.
Previously the three facets went to the container's own options factory instead, which built a fresh object from the configuration section alone. That object had never seen the fluent defaults, so an IOptions<CircuitBreakerOptions> reader saw ConcurrentHalfOpenAttempts as 0 where the built instance held 1, an IOptions<RecoveryOptions> reader saw MaxRetryAttempts as 0 and a null CircuitBreakerOptions where the built instance held 5 and a populated one, and an IOptions<ReliabilityOptions> reader saw OutboxProcessingIntervalInMilliseconds as 0 where the built instance held 5000. The parent options were the worst of them: IOptions<MessageBrokerOptions> returned an all-default instance whose TransactionMode was None and whose Reliability and Recovery were both null, so reading .Recovery.MaxRetryAttempts off it raised a NullReferenceException rather than returning a wrong number — not one configured key landed.
Nothing inside this package injected those facets. BrokeredMessageOutboxProcessor, RetryStrategy, RetryWithCircuitBreakerStrategy and CircuitBreaker all inject the concrete options types, which were always correctly seeded, so the zeroed values were reachable only by an application that resolved a facet itself.
IOptionsMonitor<T> is supported for resolution only. Configuration is bound once, while the options are being built, so the built options never reload and the change callback is inert. Named options are not a concept in this package either — every name, including none, resolves the same built instance.
Behaviour change: a services.Configure<MessageBrokerOptions>(...), Configure<ReliabilityOptions>(...), Configure<RecoveryOptions>(...) or Configure<CircuitBreakerOptions>(...) registration of your own is no longer consulted. The facets are bound directly to the built instance and never go through the options factory, which is precisely what makes the built instance authoritative, so a post-configure of these four types silently stops applying. The narrowing is intentional, and no known application relies on it, but it is a public behaviour change: configure these options through the fluent builder or through the Chatter:MessageBrokers section instead.
The same rule is applied to ServiceBusOptions by Chatter.MessageBrokers.AzureServiceBus. It is not applied across the whole suite: Chatter.MessageBrokers.RabbitMQ and Chatter.MessageBrokers.SqlServiceBroker still register only the concrete options singleton, deliberately — neither registers a Configure<T>, so neither has anything divergent to close.
Routing Slips
A Routing Slip is a message that carries its own itinerary — an ordered list of destinations to visit. The receiver advances the slip to the next step as each handler completes, enabling itinerary-style choreography without a central orchestrator.
using Chatter.MessageBrokers.Routing.Slips;
var slip = RoutingSlipBuilder.NewRoutingSlip(Guid.NewGuid())
.WithRoute("validate.queue")
.WithRoute("charge.queue")
.WithRoute("ship.queue")
.Build();
RoutingSlipBehavior advances the slip across the configured RoutingSteps; helper extensions (MessageBrokerContextExtensions, SendOptionsExtensions, CommandPipelineBuilderExtensions) attach and read the slip on the message/context.
Diagnostics and Trace Context (optional, opt-in)
The brokered message boundary is instrumented with OpenTelemetry-compatible tracing and metrics, and W3C trace context is propagated across it. Both are off until an application opts in, and Chatter.MessageBrokers takes no dependency on any OpenTelemetry.* NuGet package — the instrumentation is built on the .NET base class library only: System.Diagnostics.ActivitySource for spans and System.Diagnostics.Metrics.Meter for instruments.
Turning it on
The ActivitySource and the Meter are both named after the emitting assembly — Chatter.MessageBrokers. Chatter.CQRS emits under its own separate scope, named after its assembly, so send/receive and in-process dispatch can be sampled and filtered independently. Subscribe with a prefix wildcard to get both, or name the scopes exactly:
services.AddOpenTelemetry()
.WithTracing(t => t.AddSource("Chatter.*")) // or .AddSource("Chatter.CQRS", "Chatter.MessageBrokers")
.WithMetrics(m => m.AddMeter("Chatter.*")); // or .AddMeter("Chatter.CQRS", "Chatter.MessageBrokers")
Any .NET ActivityListener / MeterListener works just as well — an OpenTelemetry provider merely subscribes to these base-class-library primitives, it is not a prerequisite for them.
Off means off
When nothing subscribes to the Chatter.MessageBrokers source or meter, nothing is emitted and nothing extra goes on the wire. Each emit site checks whether Chatter's own source has a subscriber as its first statement and returns before a span name, a tag collection, or a traceparent header is constructed — so an application that never opts in pays no per-message cost and its messages are byte-identical to the un-instrumented ones. In particular, no traceparent is written unless Chatter itself started a span: the injection is a pure function of the span Chatter started, never of the ambient Activity.Current, which is non-null in any host running unrelated instrumentation. The guarantee is per-operation; constructing the ActivitySource and Meter themselves is a one-time static initialization per process, which is unavoidable for any ActivitySource-based design.
What is emitted
Two spans, one Chatter-native span event alongside the standard exception event, and three instruments. Names prefixed chatter. are Chatter-native; messaging.*, error.type and exception.* are OpenTelemetry semantic conventions pinned to v1.30.0.
Fill rule — every row below states when it is emitted; a blank condition cell is a defect, and Always is a positive claim that the emit site is unconditional rather than a default. A condition on an attribute, event or metric-attribute row is stated relative to its signal existing at all: whether a span exists at all is the span table's Started when, and whether a measurement is taken at all is the instrument table's Recorded when. One row per facet — no comma-joined lists.
Span name rule. A span is named {messaging.operation.name} {messaging.destination.name}, degrading to the bare operation name when no destination is set. A bare send is therefore the same span under this rule rather than a further one, and a name whose destination is resolved only at span stop is rewritten there.
Spans
| Span | Name | Kind | Started by | Started when |
|---|---|---|---|---|
| send | send {messaging.destination.name}, per the span name rule |
ActivityKind.Producer |
BrokeredMessageDispatcher's send and publish paths, ForwardingRouter, ReplyRouter, OutboxProcessor's drain, and the Cosmos change-feed relay's drain (from the sibling reliability package) |
Once per dispatch call that reaches the send path, however many messages that call carries, and once per row the outbox drain publishes — and only while a .NET ActivityListener is attached to the Chatter.MessageBrokers source and samples the span. Two shapes reach no span at all: ForwardingRouter returns before any diagnostics when the forward destination is blank, and ReplyRouter does the same when the reply routing context is null. A reply whose BuildReply throws does start one — the span opens before the reply is built, so a reply that could not be constructed is reported as a failed send rather than as a metric with no span beside it. |
| receive | receive {messaging.destination.name}, per the span name rule; the destination is the receiver path |
ActivityKind.Consumer |
BrokeredMessageReceiver<TMessage> at worker entry |
Once per delivery, covering every Recovery attempt made for that delivery — and only while a .NET ActivityListener is attached to the Chatter.MessageBrokers source and samples the span. |
Those two are the whole span inventory; the name rule renames a span, it never adds one. messaging.operation.type also declares the semconv values create, process and settle, but Chatter emits none of them, so a query written against those values matches nothing.
Span attributes
An unset attribute below is an unconditional write of a null value, not a skipped write: .NET Activity.SetTag drops a tag whose value is null.
| Attribute | Span | Value | Emitted | Name origin |
|---|---|---|---|---|
messaging.system |
send | The Messaging Infrastructure identifier the dispatch names — the infrastructure-type entry of the routing options' Message Context, the outbound message's own on a forward, the inbound message's on a reply (the reply aliases that same context, so it is the identity the reply carries and it is known before the reply is built), or the entry persisted with the row on an outbox drain. | Only when the dispatch carries a non-blank identifier; a dispatch carrying none — or one that names the default infrastructure, whose identifier is the empty string — leaves the attribute unset, and nothing is invented in its place. | semconv v1.30.0 |
messaging.system |
receive | The receiver's configured ReceiverOptions.InfrastructureType, normalized so that a blank value leaves the attribute unset. |
Only when the Brokered Message Receiver was configured with one; a receiver configured without one leaves the attribute unset. | semconv v1.30.0 |
messaging.operation.name |
send | send |
Always. | semconv v1.30.0 |
messaging.operation.name |
receive | receive |
Always. | semconv v1.30.0 |
messaging.operation.type |
send | send |
Always. | semconv v1.30.0 |
messaging.operation.type |
receive | receive |
Always. | semconv v1.30.0 |
messaging.destination.name |
send | The destination the call named, when it named one; otherwise the single destination every message of the batch resolved to. | A forward or a reply sets it at span start, from the outbound message's own destination, and never rewrites it. A Send / Publish given an explicit destination also sets it at span start, then rewrites the same value in the dispatch call's finally. An attribute-routed Send / Publish starts with none and first writes it at span stop — in that same finally, the destination being resolved by the one enumeration the Router performs — rewriting the span name with it there. Unset on that attribute-routed shape alone, when the batch resolved to more than one destination or yielded nothing. |
semconv v1.30.0 |
messaging.destination.name |
receive | The receiver path, as the Messaging Infrastructure's path builder resolved it. | Always, at span start — the path is resolved once at receiver startup, before any delivery. | semconv v1.30.0 |
messaging.batch.message_count |
send | How many messages the call handed to the Router: the number a Send / Publish actually yielded, 1 for a forward, 1 for a drained outbox row, and for a reply 1 once the Router has been called or 0 when the call failed before that — the same number messaging.client.sent.messages records for that call. |
Always. A forward and a drain set it at span start; a Send / Publish and a reply write it at span stop — in the call's finally, the count being unknown until the Router's one enumeration ends, or until the reply has actually been handed to the Router — overwriting the 0 the span started with. |
semconv v1.30.0 |
messaging.message.id |
receive | The Messaging Infrastructure's own identifier for the delivered message. | Only when the infrastructure supplied a non-empty one. | semconv v1.30.0 |
chatter.messaging.receive.attempts |
receive | How many Recovery attempts ran for this delivery; 0 when the delivery failed before Recovery began, as a poisoned body does. |
Always, written at span stop. | Chatter-native |
chatter.messaging.settlement |
receive | The settlement Chatter answered with: ack when handling completed and the worker token was not cancelled; nack when handling completed under a cancelled worker token, or a processing fault left the delivery count below MaxReceiveAttempts; deadletter on a poisoned body, or a processing fault whose delivery count has reached MaxReceiveAttempts. |
Only on those branches of the worker's error ladder that choose a settlement, and recorded where the branch chooses it rather than after the settlement call, which is best-effort. A delivery that ended in a CriticalReceiverException, in a shutdown cancellation, or in a delivery-count probe that itself failed reaches no such branch and carries no settlement. |
Chatter-native |
error.type |
send | The fully qualified exception type name. | Only when an exception ended the dispatch call. | semconv v1.30.0 |
error.type |
receive | The fully qualified exception type name; or settlement_failed when the Messaging Infrastructure returned a Failed Settlement Outcome without raising anything. |
Only when a failure was retained for the delivery. A shutdown cancellation is deliberately not a failed receive — a clean restart would otherwise emit one failure per delivery in flight — and retains none. | semconv v1.30.0 |
| Status — the span's own status field, not a tag | send | Error, with the exception's message as the status description. |
Recorded by the same ActivityOutcome.RecordFailure call that writes this span's error.type above, so the status and the attribute cannot disagree. |
Activity.SetStatus, .NET base class library |
| Status — the span's own status field, not a tag | receive | Error; the description is the exception's message on an exception-shaped failure, and on the non-exception settlement_failed path the description of what did not settle. |
Recorded by the same ActivityOutcome.RecordFailure call that writes this span's error.type above, so the status and the attribute cannot disagree — the settlement_failed path included, which sets both without raising anything. |
Activity.SetStatus, .NET base class library |
Span events
| Event | Span | Attributes | Emitted |
|---|---|---|---|
chatter.messaging.receive.retry |
receive | chatter.messaging.receive.attempts, carrying the number of the attempt this event records. |
On every Recovery attempt after the first, and only while Activity.IsAllDataRequested is true, so a sampled-out or recording-only span pays nothing to construct it. |
exception |
send | Provenance-split by target framework: on net10.0 the base class library's Activity.AddException writes them; on net8.0 Chatter writes the exception.* set itself. The event name is exception either way. |
Only when an exception ended the dispatch call and Activity.IsAllDataRequested is true. |
exception |
receive | Provenance-split by target framework, exactly as on the send span: Activity.AddException on net10.0, Chatter-written exception.* tags on net8.0. |
Only when an exception ended the delivery and Activity.IsAllDataRequested is true. A Failed Settlement Outcome the infrastructure returned without raising carries no event, deliberately: there is no exception, and a never-thrown marker exception would attach a synthetic stack trace as false evidence about something that never happened. A shutdown cancellation likewise carries none. |
Metrics
| Instrument | Type | Unit | Advised buckets | Records | Recorded when |
|---|---|---|---|---|---|
messaging.client.operation.duration |
Histogram<double> |
s |
0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10 — published as instrument advice on net10.0 only; on net8.0 the instrument carries none. See Histogram bucket boundaries below. |
The elapsed time of one dispatch call, of one outbox drain publish, or of one delivery. | Once per dispatch call that reaches the send path, once per row the outbox drain publishes, and once per delivery, on the failing path as well as the succeeding one, and only while a .NET MeterListener has enabled this instrument. The two no-op routes that start no span — a blank forward destination, a null reply routing context — record nothing either; a reply whose BuildReply throws records here and on the send span alongside it. |
messaging.client.sent.messages |
Counter<long> |
{message} |
Not applicable — a Counter<long> has no buckets. |
The number of messages the dispatch call handed to broker infrastructure: the number a Send / Publish yielded, 1 for a forward, 1 for each row the outbox drain publishes, and for a reply 1 once the Router has been called or 0 when the call failed before that. |
Once per dispatch call that reaches the send path, once per row the outbox drain publishes, on the failing path as well as the succeeding one, and only while a .NET MeterListener has enabled this instrument. The two no-op routes that start no span — a blank forward destination, a null reply routing context — record nothing here either. |
messaging.client.consumed.messages |
Counter<long> |
{message} |
Not applicable — a Counter<long> has no buckets. |
One message per delivery. "Consumed" is the pinned specification's wire spelling for what this module calls receiving. | Once per delivery, on the failing path as well as the succeeding one, and only while a .NET MeterListener has enabled this instrument. |
Metric attributes
| Attribute | Instruments | Value | Emitted |
|---|---|---|---|
messaging.system |
all three | On a send measurement, the Messaging Infrastructure identifier the dispatch names — null when it names none, or names the default infrastructure, whose identifier is the empty string. A reply resolves it off the inbound message before the reply is built, so a reply whose BuildReply throws still carries the inbound infrastructure's identifier rather than null; a drain carries the identifier persisted with the row. On a receive measurement, the receiver's configured ReceiverOptions.InfrastructureType — null when the receiver was configured without one. |
Always, as a key, whatever the value. |
messaging.operation.name |
all three | send on a send measurement, receive on a receive measurement. |
Always, as a key. |
messaging.operation.type |
all three | send on a send measurement, receive on a receive measurement. |
Always, as a key. |
messaging.destination.name |
all three | On a send measurement, the destination the call named or the single destination the batch resolved to — null when the call named none and the batch resolved to more than one, or yielded nothing. On a receive measurement, the receiver path. | Always, as a key, whatever the value. |
error.type |
all three | The fully qualified exception type name; or settlement_failed for a Failed Settlement Outcome the Messaging Infrastructure returned without raising anything. |
Only when a non-blank error type was resolved for the operation; an operation that did not fail carries no error.type key at all. |
Where a span leaves an attribute unset, the instruments still carry that attribute as a key with a null value. Query the spans for a missing attribute; query the instruments for a null one.
Metric attribute names are a strict subset of the span attribute names. A rate broken down by settlement outcome, by message id or by attempt count therefore cannot be built from these instruments — that breakdown has to come from the spans.
Histogram bucket boundaries
messaging.client.operation.duration records seconds. The OpenTelemetry .NET SDK's default explicit histogram boundaries are millisecond-sized (0, 5, 10, 25, ... 10000), so a collector that applies them puts every realistic measurement in the first bucket and P50, P90 and P99 all report the same number forever. Chatter.MessageBrokers therefore publishes seconds-sized bucket boundaries on the duration histogram itself; the two counters alongside it have no buckets to advise. The boundaries match the OpenTelemetry messaging semantic conventions and are listed in the Metrics table above.
They are advice, not a setting. The boundaries are published as instrument advice — a default that an application's own view overrides. An application that already registers a view for messaging.client.operation.duration keeps winning exactly as it did before; nothing it configured changes. Advice is the right layer for this precisely because it cannot take that choice away from the application.
Advice is published on net10.0 only. The base class library type that carries instrument advice does not exist in the net8.0 shared framework, and this package takes no package dependency to reach it. On net8.0 the instrument therefore ships with no advice at all, and the collector falls back to its own millisecond-sized defaults.
On net8.0, configure the equivalent view in your own application. AddView and ExplicitBucketHistogramConfiguration are OpenTelemetry.Metrics types that come from your application's OpenTelemetry packages — this package still takes no dependency on any OpenTelemetry.* NuGet package, and the snippet below adds none to it:
using OpenTelemetry.Metrics;
services.AddOpenTelemetry()
.WithMetrics(m => m
.AddMeter("Chatter.MessageBrokers")
.AddView("messaging.client.operation.duration", new ExplicitBucketHistogramConfiguration
{
Boundaries = new double[] { 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10 }
}));
The same view is harmless on net10.0: it overrides advice that already carries these boundaries. This net8.0 caveat retires when net8.0 is dropped and the package single-targets net10.0 after .NET 8 reaches end of life on 2026-11-10 — tracked in issue #395.
Attribute names are data, not API
Broker-boundary spans carry OpenTelemetry semantic-convention attributes pinned to v1.30.0 (messaging.system, messaging.operation.name, messaging.operation.type, messaging.destination.name, messaging.message.id, messaging.batch.message_count, error.type). Because telemetry attributes are emitted data rather than a compile-time type surface, they may change in a minor release when that pin advances. Dashboards and alert queries that hard-code attribute names should expect to be revisited on a pin bump; the bump is announced in this package's CHANGELOG.
Propagation scope
Trace context rides the Message Context as the ordinary traceparent / tracestate headers, so it survives anywhere the whole context survives. Scope is deliberately partial and stated honestly.
Trace context flows for:
| Path | Notes |
|---|---|
| Azure Service Bus | Both directions — the context is projected onto the message's application properties on send and read back on receive. |
| RabbitMQ | Both directions, as a preserved non-core header. |
| The EntityFramework outbox | Persisted with the context and rehydrated on drain — and, with diagnostics on, reparented there, as below. |
| The Cosmos outbox | Same shape — serialized on stage, materialized on relay — and, with diagnostics on, reparented there as well, exactly as the EntityFramework outbox is. |
| Outbox replay generally | A traceparent round-trips as a string through context materialization. |
The outbox drain reparents; it does not break the chain. Both drains behave the same way here: OutboxProcessor polling the EntityFramework outbox, and the Cosmos change-feed relay draining the Cosmos outbox. With diagnostics on, each publishes the drained row or document under a fresh send span parented to the traceparent persisted with that row or document, then writes that span's context onto the outgoing message. A downstream receive therefore parents to the drain span rather than directly to the write span, and the trace reads write → drain → receive: one extra hop, and it is the hop that actually put the message on the broker, minutes after the write and in another process. A row or document that carries no persisted context — one written while diagnostics were off, or received over a path that propagates none — starts a fresh root instead, with the ambient activity of the drain loop or of the change feed attached as a link rather than promoted to parent, because neither the poll nor the feed caused the message.
The Cosmos drain opens this module's send span; it declares none of its own. Chatter.MessageBrokers.Reliability.Cosmos emits its own drain metrics — lag, per-document outcome, batch size and batch count — under its own assembly-named scope, and no span at all: it publishes each drained document under the Chatter.MessageBrokers send span described above and never re-emits that span under its own scope, so one drained document is never reported by two send spans. Its instruments are documented in that package's README.
The reparenting happens only when diagnostics are opted into, on either drain. With them off, on the metrics-only path, and when the drain span is sampled out, nothing is written and the persisted traceparent rides out unchanged.
Trace context does NOT flow for:
Chatter.MessageBrokers.SqlServiceBroker'sDEFAULT-message-type receive path. That path builds a fresh header dictionary, so all upstream context is dropped. Only the Chatter envelope path — taken when the sending application supplies the Chatter brokered-message type — round-trips the context. The deadletter path likewise builds a fresh dictionary.Chatter.SqlChangeFeed. Its messages originate from a SQL trigger. There is no producer-side Chatter dispatch and no headers at all, so there is nothing to propagate and nothing to extract.
Both gaps are pre-existing limitations that affect all headers alike — they are not introduced by tracing, and closing them is a change to those receive paths, not to the instrumentation. Both are pinned by conformance tests, so a change that accidentally fixes or worsens either is visible.
Design rationale, the propagation scope, and the off-guard rules are recorded in ADR-0010.
Domain Language
Terminology used throughout this module (Brokered Message, Receiver, Dispatcher, Router/Forwarder, Inbox/Outbox, Recovery, Circuit Breaker, Critical Failure, Error Queue, Max Receives Exceeded, Body Converter) is defined in the domain glossary.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Chatter.CQRS (>= 0.16.0)
- Microsoft.Extensions.Configuration.Abstractions (>= 10.0.0)
- Microsoft.Extensions.Hosting (>= 10.0.0)
- Scrutor (>= 3.3.0)
-
net8.0
- Chatter.CQRS (>= 0.16.0)
- Microsoft.Extensions.Configuration.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Hosting (>= 8.0.1)
- Scrutor (>= 3.3.0)
NuGet packages (6)
Showing the top 5 NuGet packages that depend on Chatter.MessageBrokers:
| Package | Downloads |
|---|---|
|
Chatter.MessageBrokers.AzureServiceBus
An implementation of the Chatter.MessageBrokers adapter library for Azure Service Bus. |
|
|
Chatter.MessageBrokers.SqlServiceBroker
An implementation of the Chatter.MessageBrokers adapter library for SQL Service Broker. |
|
|
Chatter.MessageBrokers.Reliability.EntityFramework
An implementation of the Chatter.MessageBrokers.Reliability adapter library which leverages EF Core for transactions, units of work, inbox and outbox. The inbox row records whether a message id is claimed or handled, so a handler that never completed no longer suppresses its redelivery, and a unit of work that rolls back a transaction it began leaves no tracked change behind it |
|
|
Chatter.IntegrationEventRelay
Capture domain events from changes in a SQL database and relay them to message broker infrastructure as integration events. Add a change source package, such as Chatter.IntegrationEventRelay.ServiceBroker. |
|
|
Chatter.MessageBrokers.Reliability.Cosmos
Azure Cosmos DB reliability provider for Chatter.MessageBrokers, shipping three independently registrable primitives. Document Tier (WithCosmosDocumentReliability<TCommand>): a per-command opt-in in which the handler's aggregate write, its Co-Resident Outbox Document, and its Batched Inbox Marker commit on one partition-scoped TransactionalBatch; the Document-Tier Outbox Relay publishes afterwards and always reconstructs the message verbatim. Standalone Inbox Gate (WithCosmosInbox): lease-less redelivery dedup for stateless consumers via a two-phase Write-Ahead Claim confirmed on completion; it dedups redeliveries only, not concurrent delivery — two concurrent deliveries of one message id both run the handler, so handlers behind it must be idempotent and safe under concurrent execution of the same id. Standalone Outbox Relay (AddCosmosOutboxRelay): its own hosted service, independent of the command pipeline, draining pending Outbox Documents off a monitored container's change feed; it alone consults an optional Outbox Body Resolver. The Document Tier's public staging surface rejects application documents carrying the inbox:/outbox: id prefixes, while a Standalone Outbox Relay drains an application-authored trigger document only when its id is exactly outbox:{encoded(MessageId)}. Delivery is at-least-once (receivers dedup via the Inbox Marker); the monitored container must have defaultTtl enabled for delivered documents to self-purge; the application owns the CosmosClient and provisions the Cosmos resources. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 0.35.3 | 784 | 9/26/2026 |
| 0.35.2 | 112 | 9/26/2026 |
| 0.35.1 | 1,416 | 9/24/2026 |
| 0.35.0 | 163 | 9/24/2026 |
| 0.34.0 | 182 | 9/23/2026 |
| 0.33.0 | 137 | 9/23/2026 |
| 0.32.1 | 139 | 9/22/2026 |
| 0.32.0 | 148 | 9/20/2026 |
| 0.31.0 | 307 | 9/15/2026 |
| 0.30.0 | 183 | 9/13/2026 |
| 0.28.0 | 284 | 9/11/2026 |
| 0.27.0 | 124 | 9/11/2026 |
| 0.26.0 | 126 | 9/9/2026 |
| 0.25.0 | 148 | 9/9/2026 |
| 0.20.0 | 131 | 9/8/2026 |
| 0.19.1 | 138 | 9/5/2026 |
| 0.19.0 | 155 | 9/4/2026 |
| 0.18.1 | 531 | 9/2/2026 |
| 0.17.1 | 139 | 9/2/2026 |
| 0.17.0 | 270 | 9/1/2026 |