RabbitMQ Transport
RabbitMQ is BareWire's reference transport (BareWire.Transport.RabbitMQ) and the broker most
of this site is written against. It maps BareWire's core concepts directly onto AMQP 0-9-1:
exchanges, queues, and bindings declared as manual topology, plus consistent-hash and
single-active-consumer for per-key ordering, native dead-letter exchanges, and publish-style
request/response.
Because RabbitMQ is the default throughout the documentation, this page is a transport-specific reference — registration, connection and TLS, settlement, and a map to the feature guides — rather than a re-explanation of every feature. The deep guides are linked at the end of each section.
Registration
As with every BareWire transport, you register the core engine and the RabbitMQ transport together. See Configuration for the full rationale behind the layering.
1. Single call — bundle package (recommended)
The BareWire.RabbitMQ bundle depends on both the core and the transport and exposes one method,
AddBareWireWithRabbitMq. Configure the transport in the first delegate and (optionally) the bus
in the second:
builder.Services.AddTransient<OrderConsumer>(); // consumers are resolved from DI
builder.Services.AddBareWireWithRabbitMq(
transport =>
{
transport.Host("amqp://guest:guest@localhost:5672/");
transport.ConfigureTopology(t => { /* exchanges, queues, bindings */ });
transport.ReceiveEndpoint("orders", e => e.Consumer<OrderConsumer, OrderCreated>());
},
bus =>
{
// serializers, middleware...
});
The bus delegate is optional — omit it when transport defaults are enough:
builder.Services.AddBareWireWithRabbitMq(transport => transport.Host("amqp://localhost"));
2. Two calls — core and transport registered separately
AddBareWireWithRabbitMq is sugar over the explicit pair. Use the two-call form when you reference
the core and transport packages separately (a bundle call registers the core internally):
builder.Services.AddTransient<OrderConsumer>();
builder.Services.AddBareWireRabbitMq(transport =>
{
transport.Host("amqp://guest:guest@localhost:5672/");
transport.ReceiveEndpoint("orders", e => e.Consumer<OrderConsumer, OrderCreated>());
});
builder.Services.AddBareWire(bus => { /* middleware, serializer mappings... */ });
Deprecated: configuring the transport with
cfg.UseRabbitMQ(...)inside theAddBareWiredelegate is an obsolete no-op — any host/credentials passed to it are ignored. Configure the transport throughAddBareWireRabbitMqor the bundle. See Configuration.
Connection
Point the transport at the broker with Host. The connection string is typically injected via
Aspire or configuration:
// Via Aspire (automatic) — registers the RabbitMQ client connection
builder.AddRabbitMQClient("rabbitmq");
// Via connection string
transport.Host("amqp://guest:guest@localhost:5672/");
Credentials can also be supplied (and overridden) through the host configurator rather than embedded in the URI — useful when the username/password come from a secret store:
transport.Host("amqp://broker.internal:5672/", h =>
{
h.Username(username);
h.Password(password); // never logged or echoed in diagnostics
});
Bus start
The bus opens both connections (BareWire-consume, then BareWire-publish) in StartAsync, so
StartAsync performs two connection handshakes and every bus holds both connections from start — also a
service that only publishes or only consumes, and a bus without receive endpoints that never publishes.
- When at least one receive endpoint with consumers uses delayed redelivery, a failure to open either
connection fails
StartAsyncwithBareWireTransportException(the original error is itsInnerException). The connection opened by that attempt is closed and the bus stays stopped. Each of the two opens is bounded by the RabbitMQ client's connection timeout plus its handshake timeout, and closing a connection from the failed attempt can add up to about 11 seconds, so pass a cancellation token toStartAsyncas the hard bound. - Otherwise both opens together are bounded by
DelayedRedeliveryConfirmTimeout. A failure or timeout is logged as a warning (exception type names only), the bus starts anyway, and a connection that is not open yet opens on first use. - Cancelling
StartAsyncalways surfaces asOperationCanceledException.ConnectionTimeoutdoes not bound these opens.
Connection recovery and health
The client recovers a lost connection automatically, retrying every 5 seconds. After recovery it re-registers each consumer, and the receive endpoint keeps receiving without a restart. Messages that were buffered but not yet handled when the connection dropped are discarded: the broker redelivers them. A message that was already in a handler may be processed twice (at-least-once).
While a consumer waits for recovery its endpoint receives nothing. If the connection does not come back,
or the client cannot re-register the consumer (for example because its queue was deleted and the
transport does not declare it), the bus health check reports that endpoint as Degraded after
30 seconds. The endpoint description says how long the consumer has been waiting and whether the
connection is still down or open without the consumer. A Warning is logged once when the limit is
reached, and an Information entry when the consumer recovers after it. The status is Degraded, not
Unhealthy, so a liveness probe does not restart the process during a broker outage. The endpoint is not
restarted automatically: if it stays degraded, fix the broker side (recreate the queue) or restart the
service.
TLS and mutual TLS
For an encrypted connection, use the amqps:// scheme and configure TLS through the host
configurator's UseTls block. UseTls exposes an ITlsConfigurator:
| Method | Meaning |
|---|---|
WithCertificate(path, password?) |
Client certificate file (PFX or PEM) and an optional private-key passphrase (the passphrase is never logged). |
WithMutualAuthentication() |
Enables mTLS — the client presents its certificate to the broker during the handshake. |
WithServerValidation(SslPolicyErrors) |
The set of SslPolicyErrors tolerated during server-certificate validation. Defaults to SslPolicyErrors.None (strict). In production always use None — relax it only to accept self-signed certificates in test environments. |
using System.Net.Security;
// Server-authenticated TLS
transport.Host("amqps://broker.internal:5671/", h =>
{
h.Username(username);
h.Password(password);
h.UseTls(tls => tls.WithServerValidation(SslPolicyErrors.None));
});
// Mutual TLS (client certificate)
transport.Host("amqps://broker.internal:5671/", h =>
{
h.UseTls(tls => tls
.WithCertificate("/etc/secrets/client.pfx", certPassword)
.WithMutualAuthentication()
.WithServerValidation(SslPolicyErrors.None));
});
Receive endpoints
Each receive endpoint binds a consumer (or several) to a queue and carries its own concurrency and retry settings:
transport.ReceiveEndpoint("orders", e =>
{
e.PrefetchCount = 16; // broker-level prefetch
e.ConcurrentMessageLimit = 8; // in-flight concurrency
e.RetryCount = 3; // retry attempts before DLQ
e.RetryInterval = TimeSpan.FromSeconds(1);
e.Consumer<OrderConsumer, OrderCreated>();
});
An endpoint can also host a raw consumer (e.RawConsumer<T>()), a saga state machine
(e.StateMachineSaga<T>()), multiple typed consumers, consume-time routing-key dispatch, and
per-key ordering. See Publishing and Consuming,
Consumer Routing Keys, and
Per-Key Consumer Ordering.
Note
RabbitMQ 4.3 and later reject a queue that is both non-durable and non-exclusive, unless the broker
permits the deprecated transient_nonexcl_queues feature. Declare queues with durable: true (the
default of DeclareQueue and DeclareTopology). Combine it with autoDelete: true when the queue
should disappear once its last consumer disconnects.
Settlement and dead-lettering
When a consumer succeeds the message is acknowledged; when it throws, BareWire retries up to
RetryCount and then negatively settles the delivery. With a dead-letter exchange declared on the
queue, the failed message is routed to the DLX rather than discarded — without one, a rejected
message is permanently lost (and BareWire logs a warning). Always configure a DLX on production
queues. See Retry and Dead Letter Queues.
Delayed redelivery
Delayed redelivery (second-level retry) holds a message that failed its in-process retries for a longer interval before it returns to the endpoint queue. Enable it with UseDelayedRedelivery on a receive endpoint, or on a single consumer inside Consumer<TConsumer, TMessage>(c => ...); both accept the same configuration delegate (Intervals, Handle, Ignore, FullRetryEachCycle) and the consumer form overrides the endpoint one. The level queues it publishes to must be declared with DeclareDelayedRedelivery; configuration, limits and operations are covered in Delayed Redelivery.
rmq.ReceiveEndpoint("orders", e =>
{
e.UseDelayedRedelivery(d => d.Intervals(TimeSpan.FromMinutes(10), TimeSpan.FromHours(1)));
e.Consumer<OrderConsumer, OrderCreated>();
});
How the transport redelivers a message:
- With the TTL plus dead-letter cascade strategy (default) it publishes a copy of the message to the level queue for the current interval: the level queue expires the copy and dead-letters it back to the endpoint queue. With the experimental
NativeDeliveryTimestrategy (DeclareDelayedRedelivery(queue, d => d.Strategy(RabbitMqDelayedRedeliveryStrategy.NativeDeliveryTime).Intervals(...)), diagnosticBWEXP0043) no level queues are declared: it publishes the copy to the endpoint queue withx-opt-delivery-timeset to now plus the delay, and the broker holds it until that time. That strategy needs RabbitMQ 4.4 or later and a quorum endpoint queue declared with the BareWire topology, and rejectsMaxLengthandMaxLengthBytes; the transport writesx-opt-delivery-timeitself andMapHeaderrejects that header name. Both strategies use the default exchange and a publisher confirm on a dedicated confirm channel per endpoint (on the publish connection). - The copy carries the counters
BW-DelayedRedeliveryCountandBW-DelayedRedeliveryDeferrals. Broker-managed headers (x-death,x-first-death-*,x-last-death-*,x-delivery-count,x-opt-delivery-time,x-received-from,CCandBCC) are stripped from the copy. - The wait for the confirm is bounded by
DelayedRedeliveryConfirmTimeout(5 seconds by default). The same bound also covers acquiring the confirm channel. - Outcome of the attempt: a confirm acknowledges the original delivery; a broker nack or a returned message (
basic.return, for example when no level queue matches the delay) dead-letters the original; a timeout or a closed channel requeues the original after the backoff, so the message is never lost. - After 3 consecutive confirm timeouts the confirm channel of that endpoint is closed and recreated.
- A message is dead-lettered without being published when the delay is not a whole number of seconds or the level queue name is longer than 255 bytes of UTF-8 (TTL plus dead-letter cascade only), or an AMQP short string property of the copy is longer than 255 UTF-8 bytes.
- A message is also dead-lettered without being published when the headers of the copy would not fit one AMQP frame (
frame_max, 128 KiB by default, or the value the publish connection negotiated). A header that fitted the original can grow in the copy, for example when invalid UTF-8 bytes in a value become the three-byte replacement character. - There is no limiter for outstanding confirms; the number of unconfirmed publishes on a channel is bounded by the endpoint
ConcurrentMessageLimit. - The longest configurable interval is 4 294 967 seconds (about 49.7 days): intervals are whole seconds and at most 2^32 - 1 ms, the broker
x-message-ttllimit, which the adapter also applies toNativeDeliveryTime. - Inbox deduplication across redelivery cycles needs a producer-assigned
MessageId; a message without one is a new message on each cycle from the Inbox point of view.
Startup topology validation
The level queue names belong to the transport. When the RabbitMQ configuration is built (AddBareWireRabbitMq), BareWireConfigurationException is thrown when a receive endpoint name is a level queue name or contains .delayed-redelivery., or when the topology declares a level queue twice or differently from DeclareDelayedRedelivery (other flags or arguments; the message never contains argument values), binds an exchange to a level queue, or dead-letters another queue into a level queue through the default exchange. These rules catch configuration mistakes; they do not protect against forged messages, because the default exchange still reaches every queue.
When at least one receive endpoint with consumers uses delayed redelivery, StartAsync validates the delayed redelivery topology before the topology is deployed: the configuration checks run before any connection opens, the broker checks once both connections are open. The topology rules above run again on the topology the bus deploys, so a topology registered outside the configurator is checked too. StartAsync then fails with BareWireConfigurationException (the option name is in brackets) and the bus stays stopped when:
- a starting endpoint has no
DeclareDelayedRedeliveryfor its queue ({endpoint}.DelayedRedelivery); - the intervals of
UseDelayedRedeliverydiffer from the declared ones ({endpoint}.DelayedRedelivery.Intervals.Declaration); - the declared endpoint queue has
x-overflow: drop-head, or hasx-max-length/x-max-length-byteswithoutx-overflow(the broker then defaults todrop-head) ({endpoint}.x-overflow), because a full queue would silently drop the oldest redelivered copy; setx-overflowtoreject-publishorreject-publish-dlxon a length-limited endpoint queue; - a level queue that the bus does not deploy itself does not exist on the broker (
DeclareDelayedRedelivery.LevelQueues, the value lists the missing queues); - with
NativeDeliveryTime, the declared endpoint queue is not a quorum queue ({endpoint}.x-queue-type); - with
NativeDeliveryTime, the broker version in the connectionServerPropertiesis lower than 4.4 (RabbitMQ.ServerProperties.version).
With the standard registration the bus deploys the level queues itself, so nothing is checked on the broker. Only level queues missing from the topology the bus deploys (for example queues created by CI/CD or by an operator) are checked with a passive queue.declare on the consume connection, one throw-away channel per queue, one queue at a time. Each check is bounded by DelayedRedeliveryConfirmTimeout, so the checks add at most (starting endpoints with such level queues) x (up to 20 levels) x DelayedRedeliveryConfirmTimeout to the start. A broker failure during the checks fails StartAsync with BareWireTransportException (constant message, the original error is its InnerException, only exception type names are logged), and the connections opened by the attempt are closed, which can add up to about 11 seconds.
Permissions for the check: on RabbitMQ 4.3.1 and later a passive declare needs at least one of configure, write or read on the level queue. Without it the broker refuses the check (403) and the start fails with that BareWireTransportException, so if you withhold read from level queues (they are never consumed), keep configure or write on them for the application user.
Startup warnings (logged; the bus still starts): the declared endpoint queue is a classic queue (TTL plus dead-letter cascade only); the declared quorum endpoint queue has no x-dead-letter-exchange; DeclareDelayedRedelivery sets neither MaxLength nor MaxLengthBytes (TTL plus dead-letter cascade only).
Not checked: broker policies, the arguments of queues declared outside BareWire and feature flags cannot be read over AMQP 0-9-1, and topology deployed with IBusControl.DeployTopologyAsync after the bus has started does not go through the startup checks. Keeping these consistent is the operator's responsibility.
Routing semantics
A publisher confirm tells you the broker accepted a publication — not that it routed it to a
queue. By default BareWire publishes with the AMQP mandatory flag off, so a message the broker
accepts but cannot route to any queue (topology drift, a missing binding or queue, a wrong routing
key) is silently dropped while SendResult.IsConfirmed still reports true. This is at-most-once
routing: fast, but a misconfigured topology loses messages without a signal.
Enable guaranteed routing to surface unroutable publications instead of dropping them silently:
wire.UseRabbitMq(rmq =>
{
rmq.GuaranteedRouting(); // opt-in; default is off
// ... host, topology, endpoints ...
});
With it enabled, BareWire publishes mandatory and detects an unroutable message via the broker's
return, mapping it to SendResult.IsConfirmed == false (and logging a warning). The default-off
behaviour is unchanged — routable publishes are unaffected (the channel already awaits a per-message
publisher confirm, so there is no extra round-trip), and there is no per-message allocation on the
send path.
Where it fails closed. The negative confirm only changes the outcome for code that inspects
SendResult — chiefly the transactional outbox dispatcher, which treats
IsConfirmed == false as non-delivery and retries (the row stays claimed instead of being marked
delivered). The direct IBus.PublishAsync / ISendEndpoint.SendAsync path is fire-and-forget:
the caller never receives a SendResult, and the background publisher does not redeliver on a
negative confirm. On that path guaranteed routing turns a silent drop into an observable one (the
warning log) but does not by itself make direct publishing at-least-once. For at-least-once delivery
against topology drift, publish through the outbox with this option enabled.
Header trust boundary
Headers prefixed BW- are reserved for BareWire and the transport itself.
- Send side — an unmapped
BW-*header in any letter case (BW-Forged,bw-forged,Bw-Forged) is not published; it never reaches the broker. - Receive side — an unmapped raw AMQP header whose name starts with
BW-in any letter case is dropped before the consumer sees it, except for the headers below, which the transport itself stamps or reads:BW-MappingEpoch— the diagnostic mapping-epoch marker the transport stamps on the wire itself. A forged value only affects diagnostics — it can trigger a spurious warning and overwrite the remembered lane epoch, masking or faking a real re-map — never routing, dispatch, or settlement.BW-MessageType— accepted only while the AMQPtypeproperty is empty; thetypeproperty always wins.BW-DelayedRedeliveryCountandBW-DelayedRedeliveryDeferrals— the delayed redelivery counters the transport writes when it republishes a message. They are kept only in that exact letter case, also whenIgnoreUnmappedHeaders()is set; a value longer than 10 characters, or one that is not text, bytes or a number, is dropped on read.
- Routing metadata is always transport-authoritative —
BW-Exchange,BW-RoutingKey,BW-ConsumerChannelId, andBW-Redeliveredare stamped by the transport from the delivery itself, never from a raw header the publisher supplied.BW-Redeliveredis set totrueonly when the broker flags the delivery as redelivered; a rawBW-Redeliveredheader on the wire is dropped. - What the publisher still controls — the message type (via the AMQP
typeproperty, or a rawBW-MessageTypeheader whiletypeis empty),message-id,correlation-id,reply-to,content-type,traceparent, the routing key value used at publish time, and the two delayed redelivery countersBW-DelayedRedeliveryCountandBW-DelayedRedeliveryDeferrals(exact letter case, at most 10 characters). Consumer code must not trust the counters: the transport only clamps them. For untrusted publishers, restrict access with broker permissions or an authorization middleware rather than relying on the header filter alone. - The in-memory transport applies the same reserved-prefix rule, with the same nuance — both
transports strip an unmapped
BW-*header the publisher sets (on RabbitMQ, except the two delayed redelivery counters), and both letBW-MessageTypethrough. RabbitMQ narrows that to the case where the AMQPtypeproperty is empty, and additionally lets you carry any otherBW-*header through the broker with an explicit mapping — the in-memory transport has no mapping mechanism, so it never round-trips one.
Carry your own BW-* header through the broker in both directions with an explicit mapping:
transport.ConfigureHeaderMapping(headers =>
{
headers.MapHeader("BW-TenantId", "BW-TenantId");
});
BW-DelayedRedeliveryCount, BW-DelayedRedeliveryDeferrals, and BW-Redelivered are written only by
the transport. MapHeader, MapCorrelationId, and MapMessageType reject these three names in any
letter case, on either side of a mapping, with a BareWireConfigurationException at configuration time.
Behavior change: an unmapped raw
BW-*header a publisher sets no longer reaches consumers, except the two delayed redelivery counters described above. To keep one, map it explicitly as shown above. For the message type, set the AMQPtypeproperty or configureMapMessageType(...)— a rawBW-MessageTypeheader keeps working only while thetypeproperty is empty.
Feature map
RabbitMQ-specific behaviour is documented across these guides:
| Topic | Guide |
|---|---|
| Transport registration paths and layering | Configuration |
Exchanges, queues, bindings, IQueueConfigurator, DLX |
Topology |
| Publish/subscribe, request/response, raw messages, per-type send routing | Publishing and Consuming |
| Consume-time routing-key dispatch on a shared queue | Consumer Routing Keys |
| Single-active-consumer / consistent-hash per-key ordering | Per-Key Consumer Ordering |
| Retry policies and dead-letter exchanges | Retry and Dead Letter Queues |
| Publish-style competing responders | Publishing and Consuming |
| At-most-once vs opt-in guaranteed routing | Routing semantics |
See also
- Configuration
- Topology
- Transports — the transport-agnostic overview and the other adapters