Path: redb-route/redb.Route.AzureServiceBus/README.md Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.AzureServiceBus/README.md ---- # redb.Route.AzureServiceBus Azure Service Bus connector for the [redb.Route](../README.md) ESB framework. Provides a full-featured **producer** (single & batch), **consumer** (PeekLock / ReceiveAndDelete), **session consumer** (FIFO per session), and **transacted acknowledgement**. Uses the `asb` URI scheme. [![NuGet](https://img.shields.io/nuget/v/redb.Route.AzureServiceBus?label=NuGet&color=blue)](https://www.nuget.org/packages/redb.Route.AzureServiceBus) [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue)](../../LICENSE) ## Quick Start ```csharp // Consumer: receive from a queue .From(Asb.Queue("orders") .ConnectionString("Endpoint=sb://my-ns.servicebus.windows.net/;SharedAccessKeyName=...;SharedAccessKey=...") .MaxConcurrentCalls(5) .PrefetchCount(10)) // Producer: send to a queue .To(Asb.Queue("orders") .ConnectionString("Endpoint=sb://...")) // Topic/subscription roundtrip .From(Asb.Topic("events", "my-subscription") .ConnectionString("Endpoint=sb://...")) .To(Asb.Topic("events", "ignored-for-producer") .ConnectionString("Endpoint=sb://...")) ``` ## URI Format ``` asb://entity-name?connectionString=...¶m=value ``` Entity detection is automatic: if `subscriptionName` is set, the entity is treated as a **topic**; otherwise as a **queue**. ## Producer The producer sends messages via `ServiceBusSender`. Two modes are supported: ### Single Message (default) ```csharp var exchange = new Exchange(new Message("Hello ASB")); exchange.In.Headers[AzureServiceBusHeaders.CorrelationId] = "corr-123"; exchange.In.Headers[AzureServiceBusHeaders.Subject] = "order.created"; await producer.Process(exchange); // After send, MessageId header is set var id = exchange.In.Headers[AzureServiceBusHeaders.MessageId]; ``` ### A list body A list body is sent as one Service Bus batch, one message per element, as Apache Camel's azure-servicebus sends an `Iterable` body; Service Bus takes the batch whole or not at all. A list of `IMessage` (a batch consumer's body, for one) sends each element with its own body and headers as application properties, none of the exchange's; any other list sends each value as the body under the exchange's headers, each with a message id of its own. Messages that do not fit in `batchMaxSizeBytes` (and the entity's own limit) fail the send and nothing is sent. To send a list as one message, serialize it in the route. ```csharp .To(Asb.Queue("orders") .ConnectionString("...") .BatchMaxSizeBytes(262144)) var items = new[] { "msg-1", "msg-2", "msg-3" }; var exchange = new Exchange(new Message(items)); await producer.Process(exchange); var count = (int)exchange.In.Headers[AzureServiceBusHeaders.BatchMessageCount]!; // 3 ``` > **Note:** `PartitionKey` is only set when `SessionId` is empty (ASB constraint). ## Consumer The consumer uses `ServiceBusProcessor` with callback-based message delivery. ```csharp .From(Asb.Queue("orders") .ConnectionString("...") .AckMode(AckMode.Manual) // default: PeekLock .MaxConcurrentCalls(10) .PrefetchCount(20) .MaxAutoLockRenewalDuration(300)) // 5 min ``` ### Acknowledge Modes | Scenario | `exchange.Exception` | `AutoDeadLetter` | Action | |----------|---------------------|-------------------|--------| | Success | `null` | — | Complete | | Error | set | `false` | Abandon (re-delivery) | | Error | set | `true` | Dead-letter with reason | ```csharp // Auto dead-letter on processing error .From(Asb.Queue("orders") .ConnectionString("...") .AutoDeadLetter(true) .DeadLetterReason("ProcessingFailed")) ``` A stop of the consumer (single or session) receives nothing more and waits up to 30 s for the messages in work; they finish and are settled as above. Only after that time is the route's cancellation token cancelled. ### ReceiveAndDelete Messages are removed from the queue immediately upon receipt. No acknowledgement needed: ```csharp .From(Asb.Queue("orders") .ConnectionString("...") .AckMode(AckMode.Auto)) // ReceiveAndDelete ``` ### Batch mode `batching=true` makes the consumer hand the route one exchange per batch of messages, by the batch contract every broker of redb.Route follows. Apache Camel's azure-servicebus has no batch consumer (it batches only the producer); the contract is redb.Route's own, the same as for Kafka, RabbitMQ, IBM MQ, SQS and AMQP 1.0. - `maxBatchMessages` (default 100) caps the batch; `pollTimeoutMs` (default 1000) sends a batch on once no message came for that long, restarted by every message; `batchingIntervalMs` sends it on once that long has passed since its first message. A batch option without `batching=true`, a value out of range, and `batching=true` with `enableSessions=true` (the messages of a session entity are received and settled per session) fail the start. - Each of `maxConcurrentCalls` workers has a receiver of its own and collects with `ReceiveMessagesAsync`, one batch at a time. - The body is a `List`, one message per Service Bus message with the same body and headers a single message gets, even for a batch of one; the size is `body.Count`. The exchange is InOnly. `Split` over the body gives each part its message. - With `ackMode=manual` (PeekLock) every message is completed after the route. A failed batch follows the rule of a failed message for every message in it: abandoned, delivered again, and moved to the dead letter sub-queue by the entity after its `MaxDeliveryCount`; with `autoDeadLetter=true` dead-lettered at once with `deadLetterReason`. A batch the route rolled back (`.RollbackAll()`) is abandoned. The locks of the batch are renewed while the route runs, up to `maxAutoLockRenewalDuration`, as the processor renews a single message's lock; keep `batchingIntervalMs` well below the entity's lock duration, since a lock is not renewed while the batch is still being collected. - With `ackMode=auto` (ReceiveAndDelete) the messages are gone on receipt, and a failure does not bring them back. - A batch half collected when the consumer stops is not run: its messages are abandoned. The stop waits for the receive in progress, at most `pollTimeoutMs`. ### Sub-Queues Read from dead-letter or transfer dead-letter queues: ```csharp .From(Asb.Queue("orders") .ConnectionString("...") .SubQueue("deadletter")) ``` ### Consumer Headers Each received message populates the following exchange headers: | Header | Type | Description | |--------|------|-------------| | `redbAsb.MessageId` | `string` | Message ID | | `redbAsb.CorrelationId` | `string` | Correlation ID | | `redbAsb.SessionId` | `string` | Session ID | | `redbAsb.PartitionKey` | `string` | Partition key | | `redbAsb.ReplyToSessionId` | `string` | Reply-to session ID | | `redbAsb.Subject` | `string` | Message subject / label | | `redbAsb.ContentType` | `string` | Content type | | `redbAsb.ReplyTo` | `string` | Reply-to address | | `redbAsb.To` | `string` | Destination address | | `redbAsb.TimeToLive` | `TimeSpan` | Time to live | | `redbAsb.ScheduledEnqueueTime` | `DateTimeOffset` | Scheduled enqueue time | | `redbAsb.SequenceNumber` | `long` | Sequence number | | `redbAsb.DeliveryCount` | `int` | Number of deliveries | | `redbAsb.EnqueuedTime` | `DateTimeOffset` | When message was enqueued | | `redbAsb.ExpiresAt` | `DateTimeOffset` | When the message expires | | `redbAsb.LockedUntil` | `DateTimeOffset` | Lock expiry (PeekLock only) | | `redbAsb.DeadLetterSource` | `string` | Original entity (dead-letter messages) | | `redbAsb.DeadLetterReason` | `string` | Dead-letter reason | | `redbAsb.DeadLetterErrorDescription` | `string` | Dead-letter error description | All `ApplicationProperties` from the message are also copied to exchange headers. ## Session Consumer Enable session-aware FIFO processing with `enableSessions=true`: ```csharp .From(Asb.Queue("session-queue") .ConnectionString("...") .EnableSessions(true) .MaxConcurrentSessions(5) .SessionIdleTimeout(30)) // Filter by specific session .From(Asb.Queue("session-queue") .ConnectionString("...") .EnableSessions(true) .SessionId("my-session-id")) ``` The session consumer uses `ServiceBusSessionProcessor` and guarantees message ordering within a session. `MaxConcurrentSessions` controls parallelism across sessions; messages within the same session are always processed sequentially. ## Transactions The consumer settles a delivery itself once the route has finished: it completes the message on success and abandons it on failure. Inside `.Transacted()` that comes last, after the database and the deferred sends have committed. A producer inside `.Transacted()` joins the transaction: the message is sent once the database has committed and dropped if the block rolls back. ```csharp From(Asb.Queue("orders.in").ConnectionString("...")) .Transacted() .ProcessWithRedb(async (redb, ex, ct) => await redb.SaveAsync((Order)ex.In.Body!, ct)) .To(Asb.Queue("orders.created").ConnectionString("...")) // sent after the commit .To(Asb.Queue("alerts").ConnectionString("...").Transacted(false)) // sent at once .End(); ``` - `transacted=false` sends at once, outside the transaction, even if the block later rolls back. - `transacted=true` requires an enclosing block; outside one the step fails instead of losing the message. - The Service Bus client would enlist a send in the ambient `System.Transactions` transaction by itself. The connector never lets it: a send that leaves at once runs with the ambient transaction suppressed and a deferred one after the transaction closed, so Service Bus never becomes a second resource next to the database. - By default the sends a producer deferred in a block go out one after the other. With `batchCommit=true` (`.BatchCommit()`) they leave as **one batch** when the block commits: Service Bus takes a batch to one entity whole or not at all. The block's messages must fit in one batch (`batchMaxSizeBytes`, and the entity's limit — 256 KB on Standard); a block whose messages do not fit fails its commit and sends nothing. On a partitioned or session entity the messages of one batch must share the partition key or session id. See the framework-wide **Transactions** guide (`TRANSACTIONS.md` in the [redb.Route repository](https://github.com/redbase-app/redb)) for the commit order and nesting. ## Topic / Subscription ```csharp // Producer sends to the topic .To(Asb.Topic("events", "sub-name") .ConnectionString("...")) // Consumer reads from a subscription .From(Asb.Topic("events", "my-subscription") .ConnectionString("...")) ``` The second argument to `Asb.Topic()` is the subscription name. The producer ignores `subscriptionName` and sends directly to the topic; the consumer uses it to create a `ServiceBusProcessor` for that subscription. ## Connection Factory For complex or shared client configurations, register a named `AzureServiceBusConnectionFactory`: ```csharp var factory = new AzureServiceBusConnectionFactory { ConnectionString = "Endpoint=sb://my-ns.servicebus.windows.net/;...", MaxRetries = 5, RetryMode = ServiceBusRetryMode.Fixed, TransportType = ServiceBusTransportType.AmqpWebSockets, ProxyAddress = "http://proxy:8080", }; context.AddToRegistry("myAsb", factory); // Reference by name in URI Asb.Queue("orders").ConnectionFactory("myAsb") ``` If `ProxyAddress` is set, transport is automatically switched to `AmqpWebSockets` with the configured proxy. ### Factory Properties | Property | Type | Default | Description | |----------|------|---------|-------------| | `ConnectionString` | `string` | `""` | ASB connection string | | `MaxRetries` | `int` | `3` | Max retry count | | `DelayMs` | `int` | `800` | Initial retry delay (ms) | | `MaxDelayMs` | `int` | `60000` | Max retry delay (ms) | | `RetryMode` | `ServiceBusRetryMode` | `Exponential` | `Exponential` or `Fixed` | | `TryTimeoutMs` | `int` | `60000` | Per-try timeout (ms) | | `TransportType` | `ServiceBusTransportType` | `AmqpTcp` | Transport: `AmqpTcp` or `AmqpWebSockets` | | `ProxyAddress` | `string?` | — | HTTP proxy for `AmqpWebSockets` | ## DI Registration ```csharp services.AddRedbRouteAzureServiceBus(); ``` ## Configuration Reference ### Connection | Parameter | Default | Description | |-----------|---------|-------------| | `connectionString` | — | ASB connection string (required if no factory) | | `connectionFactory` | — | Named factory from DI registry | ### Consumer | Parameter | Default | Description | |-----------|---------|-------------| | `ackMode` | `manual` | `manual` (PeekLock: completed after the route) or `auto` (ReceiveAndDelete) | | `maxConcurrentCalls` | `1` | Max concurrent handler invocations | | `prefetchCount` | `0` | Messages to pre-fetch | | `maxAutoLockRenewalDuration` | `300` | Auto lock renewal (seconds) | | `subQueue` | — | `deadletter` or `transferdeadletter` | | `autoDeadLetter` | `false` | Dead-letter on processing error | | `deadLetterReason` | — | Dead-letter reason string | | `batching` | `false` | Batch mode: the route gets a `List` (see [Batch mode](#batch-mode)) | | `maxBatchMessages` | `100` | Batch mode: largest batch | | `pollTimeoutMs` | `1000` | Batch mode: idle timeout, restarted by every message | | `batchingIntervalMs` | — | Batch mode: hard limit since a batch's first message | | `transacted` | unset | Producer: unset follows an enclosing `.Transacted()` block, `false` sends at once, `true` requires a block | ### Sessions | Parameter | Default | Description | |-----------|---------|-------------| | `enableSessions` | `false` | Session-aware consumer | | `sessionId` | — | Fixed session ID filter | | `maxConcurrentSessions` | `1` | Max concurrent session handlers | | `sessionIdleTimeout` | `0` | Session idle timeout (seconds, 0 = SDK default) | ### Producer | Parameter | Default | Description | |-----------|---------|-------------| | `messageId` | — | Dynamic message ID expression (`${...}`) | | `producerSessionId` | — | Dynamic session ID expression | | `partitionKey` | — | Partition key | | `scheduleDelaySeconds` | `0` | Delayed delivery (seconds) | | `timeToLive` | — | Message TTL (`HH:MM:SS` format) | ### Batch | Parameter | Default | Description | |-----------|---------|-------------| | `batchMaxSizeBytes` | `262144` | Max size of the batch a list body or a `batchCommit` block is sent as (bytes, default 256 KB) | ### Retry These are the Service Bus client's retries of a call to the service that failed (`ServiceBusRetryOptions`), not attempts of the route: a message the route fails is not run again in the process. With `ackMode=manual` the entity delivers it again up to its `MaxDeliveryCount`; with `ackMode=auto` it is gone. | Parameter | Default | Description | |-----------|---------|-------------| | `retryMaxRetries` | `3` | Max retry count | | `retryDelayMs` | `800` | Initial retry delay (ms) | | `retryMaxDelayMs` | `60000` | Max retry delay (ms) | | `retryMode` | `Exponential` | `Exponential` or `Fixed` | ## Headers Reference All headers use the `redbAsb.` prefix. | Constant | Value | Direction | Used By | |----------|-------|-----------|---------| | `MessageId` | `redbAsb.MessageId` | In/Out | Producer, Consumer | | `CorrelationId` | `redbAsb.CorrelationId` | In/Out | Producer, Consumer | | `SessionId` | `redbAsb.SessionId` | In/Out | Producer, Consumer | | `PartitionKey` | `redbAsb.PartitionKey` | In/Out | Producer, Consumer | | `ReplyToSessionId` | `redbAsb.ReplyToSessionId` | In/Out | Producer, Consumer | | `Subject` | `redbAsb.Subject` | In/Out | Producer, Consumer | | `ContentType` | `redbAsb.ContentType` | In/Out | Producer, Consumer | | `ReplyTo` | `redbAsb.ReplyTo` | In/Out | Producer, Consumer | | `To` | `redbAsb.To` | In/Out | Producer, Consumer | | `TimeToLive` | `redbAsb.TimeToLive` | In/Out | Producer, Consumer | | `ScheduledEnqueueTime` | `redbAsb.ScheduledEnqueueTime` | In/Out | Producer, Consumer | | `SequenceNumber` | `redbAsb.SequenceNumber` | Out | Consumer | | `DeliveryCount` | `redbAsb.DeliveryCount` | Out | Consumer | | `EnqueuedTime` | `redbAsb.EnqueuedTime` | Out | Consumer | | `ExpiresAt` | `redbAsb.ExpiresAt` | Out | Consumer | | `LockedUntil` | `redbAsb.LockedUntil` | Out | Consumer (PeekLock) | | `LockToken` | `redbAsb.LockToken` | — | Declared, not set | | `DeadLetterSource` | `redbAsb.DeadLetterSource` | Out | Consumer (DLQ) | | `DeadLetterReason` | `redbAsb.DeadLetterReason` | Out | Consumer (DLQ) | | `DeadLetterErrorDescription` | `redbAsb.DeadLetterErrorDescription` | Out | Consumer (DLQ) | | `SessionState` | `redbAsb.SessionState` | — | Declared, not set | | `BatchMessageCount` | `redbAsb.BatchMessageCount` | Out | Producer (batch) | ### Header filter strategy Every other exchange header goes out as an application property, and every application property of a received message comes in. `headerFilterStrategy=#name` names an `IHeaderFilterStrategy` in the registry that decides which headers cross, as in Apache Camel: on a producer, which exchange headers become application properties; on a consumer (plain and session alike), which application properties come in. It replaces the default, `AzureServiceBusHeaderFilterStrategy` (keeps `redbAsb.*` back), entirely; derive from that class to add to it. The system properties above and the trace context are set whatever the strategy says. ```csharp ctx.AddToRegistry("correlationOnly", new DefaultHeaderFilterStrategy { OutFilter = ["Correlation-ID"], FilterOnMatch = false, // a whitelist: only the listed headers go out }); // asb://orders?connectionString=...&headerFilterStrategy=#correlationOnly ``` ## Requirements - **Azure Service Bus** or Azure Service Bus Emulator - .NET 10.0 / 11.0. The 4.7 line stays on .NET 8, 9 and 10 for applications that cannot move yet. - `Azure.Messaging.ServiceBus` 7.x ## Concurrency The default is **1** concurrent consumer — the industry norm (Camel, Spring, the Azure SDK all ship 1): a single consumer preserves ordering and your handlers need no thread safety. Parallelism is an explicit opt-in: ``` maxConcurrentCalls=4 # a fixed worker count maxConcurrentCalls=auto # max(CPU count, 2) — the NServiceBus formula ``` Anything else — `0`, a negative, a typo — fails at endpoint creation naming the option (the old int-typed option silently fell back to 1). Raising the value trades ordering for throughput: messages from the same queue are processed out of order, and your processors must be safe to run in parallel. ## A lost connection The Service Bus client reconnects by itself, for the processor, the session processor and the batch receiver alike. While the connection is lost, the endpoint's health is `Warning`, then `Critical` once an attempt failed, and `Healthy` when it is back; a Warning is logged when it is lost and an Information when it is back, and `Reconnects` counts each return. A loss is not counted in `Errors`. The batch receiver learns of the return from its next receive. The processors give no event for it, so while the connection is lost the consumer peeks the entity's dead-letter queue on the `RedbRoute:Reconnect` schedule, through its own client: it needs only the Listen right the consumer has and locks nothing (each peek is bounded to 10 s and ends with the route's stop); the next message restores it too, whichever comes first. Only communication errors start a lost connection. While it is connected, an entity that does not exist, a refused claim and other errors the client reports are counted in `Errors` as before, and health shows them as recent errors, not as a connection being retried. While the connection is lost, every error of a receive belongs to the loss and is the reason health shows (a namespace coming back may refuse the entity for a moment). A lost session lock is neither an error nor a lost connection: the session processor accepts a session again by itself, and a message it cut short is counted where it failed. ## Tracing On the `redb.Route` activity source (`AddSource("redb.Route")`). The trace context travels in the application properties: the `traceparent` value under Azure's own name for it, `Diagnostic-Id`; `tracestate` and `baggage` under their own names. - **Consumer.** One `Consumer` span per message, named `{entity} receive`, over the whole unit of work, settlement included, for the session consumer too. Its parent is the sender's `Diagnostic-Id`; without one it is a root, never a child of whatever activity the processor thread holds. The sender's baggage is back on it, and the route's spans are its children. It carries `redb.route.endpoint` and `messaging.message.id`, and is an error when the route fails. - **Producer.** One `Producer` span per send, named `{entity} send`; an error when the send fails. Every message, each message of a batch included, carries the context of this span: a `Diagnostic-Id` the header bridge copied from a received message is replaced, as it names the previous hop. - `RouteEngineOptions.EnableTelemetry = false` opens neither span. A context that came in still goes out.