LowCodeHub.RabbitMQ
0.1.0
dotnet add package LowCodeHub.RabbitMQ --version 0.1.0
NuGet\Install-Package LowCodeHub.RabbitMQ -Version 0.1.0
<PackageReference Include="LowCodeHub.RabbitMQ" Version="0.1.0" />
<PackageVersion Include="LowCodeHub.RabbitMQ" Version="0.1.0" />
<PackageReference Include="LowCodeHub.RabbitMQ" />
paket add LowCodeHub.RabbitMQ --version 0.1.0
#r "nuget: LowCodeHub.RabbitMQ, 0.1.0"
#:package LowCodeHub.RabbitMQ@0.1.0
#addin nuget:?package=LowCodeHub.RabbitMQ&version=0.1.0
#tool nuget:?package=LowCodeHub.RabbitMQ&version=0.1.0
LowCodeHub.RabbitMQ
A topology-first RabbitMQ library for .NET 11. Declare queues, exchanges, bindings, and consumers in a single fluent DSL — the library compiles it to broker topology, wires up DI, and manages the consumer lifecycle automatically. Built on RabbitMQ.Client 7.x with full async channel support.
Why This Library?
| Feature | LowCodeHub.RabbitMQ | Raw RabbitMQ.Client | MassTransit | EasyNetQ |
|---|---|---|---|---|
| Topology declaration | Fluent DSL — compiled + validated | Manual channel calls | Convention-based | Convention-based |
| Consumer wiring | Auto-discovery via [Queue] attribute |
Manual BasicConsume |
Consumer classes | IBus.Subscribe |
| Retry strategy | Republish-with-header (finite, safe) | Manual nack/requeue | Built-in pipeline | Manual |
| DLQ setup | One-liner .DeadLetterDefaultExchange() |
Manual exchange/queue | Configurable | Manual |
| RPC | Built-in request/reply client + server | Manual correlation | Built-in | Built-in |
| Publisher confirms | PublishWithConfirmAsync() |
Manual confirm select | Built-in | Manual |
| Health checks | Auto-registered | Manual | Built-in | Manual |
| Observability | OpenTelemetry metrics + traces | Manual | Built-in | Manual |
| Cluster failover | Multi-endpoint config | Manual endpoint list | Built-in | Manual |
Table of Contents
- Installation
- Quick Start
- Connection Configuration
- Topology DSL
- Queue Options
- Dead Letter Queues
- Consumers
- Publishing
- RPC (Request/Reply)
- Health Checks
- Observability
- Clustering
- SSL/TLS
- Conflict Handling
- Custom Serializer
- Architecture Overview
- Production Checklist
Installation
dotnet add package LowCodeHub.RabbitMQ
Quick Start
1. Add connection config to appsettings.json:
{
"RabbitMQ": {
"HostName": "localhost",
"Port": 5672,
"UserName": "myapp",
"Password": "secret",
"VirtualHost": "/"
}
}
2. Register services and declare topology:
builder.Services.AddRabbitMq(builder.Configuration, topology => topology
.Default(x => x
.Queue("orders.created", q => q.Quorum().DeadLetterDefaultExchange())));
Consumers ([Queue] classes) are discovered in the entry assembly. To be explicit, or to pick up consumers from other assemblies, use topology.Consumer<OrderCreatedConsumer>() / topology.ConsumersFromAssembly(typeof(SomeType).Assembly); either one turns off entry-assembly scanning.
3. Create a consumer:
[Queue("orders.created")]
public sealed class OrderCreatedConsumer : MessageConsumer<OrderCreatedEvent>
{
public override async Task ConsumeAsync(
ConsumeContext<OrderCreatedEvent> context,
CancellationToken cancellationToken = default)
{
var order = context.Message;
// Process the order...
}
}
4. Publish a message:
public class OrderService(IMessagePublisher publisher)
{
public Task PlaceOrderAsync(OrderCreatedEvent evt, CancellationToken ct)
=> publisher.PublishWithDefaultExchangeAsync("orders.created", evt, cancellationToken: ct);
}
That's it. The library handles connection management and recovery, topology declaration, consumer wiring and restarts, retries, DLQ routing, graceful shutdown, health checks, and OpenTelemetry metrics/traces. IMessagePublisher and IMessageRpcClient are singletons you can inject anywhere.
Connection Configuration
Configure via appsettings.json under the RabbitMQ section:
{
"RabbitMQ": {
"HostName": "rabbitmq.internal",
"Port": 5672,
"VirtualHost": "/",
"UserName": "myapp",
"Password": "secret",
"ClientProvidedName": "MyService",
"AutomaticRecoveryEnabled": true,
"TopologyRecoveryEnabled": true,
"NetworkRecoveryIntervalSeconds": 5,
"RequestedHeartbeat": 60,
"ConnectionTimeoutSeconds": 30,
"DefaultPrefetchCount": 10,
"ConsumerDispatchConcurrency": 1,
"EnablePublisherConfirms": false,
"PublisherConfirmChannelPoolSize": 4,
"StartupRetryCount": 5,
"StartupRetryDelaySeconds": 2,
"ConsumerWatchdogIntervalSeconds": 5
}
}
| Property | Default | Description |
|---|---|---|
HostName |
localhost |
Broker hostname or IP |
Port |
5672 |
AMQP port |
VirtualHost |
/ |
RabbitMQ virtual host |
UserName |
guest |
Authentication username |
Password |
guest |
Authentication password |
ClientProvidedName |
auto | Connection name shown in RabbitMQ management UI |
AutomaticRecoveryEnabled |
true |
Auto-reconnect on connection loss |
TopologyRecoveryEnabled |
true |
Re-declare topology after reconnect (required for cluster failover) |
NetworkRecoveryIntervalSeconds |
5 |
Delay between recovery attempts |
RequestedHeartbeat |
60 |
Heartbeat interval in seconds |
ConnectionTimeoutSeconds |
30 |
Connection timeout |
DefaultPrefetchCount |
10 |
Default QoS prefetch per consumer (must be ≥ 1) |
ConsumerDispatchConcurrency |
1 |
Deliveries processed concurrently per consumer channel (override per consumer with [Queue(ConsumerDispatchConcurrency = n)]) |
EnablePublisherConfirms |
false |
Make every PublishAsync / PublishBatchAsync wait for broker confirms |
PublisherConfirmChannelPoolSize |
4 |
Confirm channels used concurrently by the publisher |
StartupRetryCount |
5 |
Startup retries (topology + consumers) while the broker is unreachable; 0 = fail immediately |
StartupRetryDelaySeconds |
2 |
Initial startup retry delay, doubled per attempt (max 30s) |
ConsumerWatchdogIntervalSeconds |
5 |
How often dead consumers are detected and restarted |
Ssl, Endpoints |
— | See SSL/TLS and Clustering |
Options are validated at startup (ValidateOnStart): an invalid port, empty host/user, prefetch 0, a missing certificate file, etc. stop the host with a descriptive error.
Or configure programmatically, or bind configuration and then override (e.g. a secret from a vault):
builder.Services.AddRabbitMq(
options =>
{
options.HostName = "rabbitmq.internal";
options.UserName = "myapp";
options.Password = "secret";
},
topology => { /* ... */ });
builder.Services.AddRabbitMq(
builder.Configuration,
options => options.Password = secrets.RabbitPassword,
topology => { /* ... */ });
Topology DSL
Settings
Settings(...) is optional. Call it before declaring queues so QueueDefaults apply to them:
topology.Settings(s => s
.Prefetch(50) // Override default prefetch count
.DeleteAndRecreateOnConflict() // Recreate conflicting entities on startup
.QueueDefaults(q => q.Quorum())); // Apply defaults to all queues
Queue Defaults
Set once, applied to every queue. Individual queues can override any setting:
topology.Settings(s => s
.QueueDefaults(q => q
.Quorum() // Default queue type
.DeadLetterDefaultExchange() // Auto-create DLQ for every queue
.Ttl(86_400_000) // 24h message TTL
.MaxLength(100_000) // Max 100k messages
.LazyMode())); // Disk-first storage
Override per queue:
topology.Default(x =>
{
x.Queue("orders.created"); // Inherits all defaults
x.Queue("temp.events", q => q.Stream()); // Override: stream instead of quorum
x.Queue("fast.queue", q => q.NoDeadLetter()); // Override: no DLQ
x.Queue("priority.queue", q => q.MaxPriority(10)); // Add priority support
});
Default Exchange Queues
For point-to-point messaging using the AMQP default exchange (""):
topology.Default(x =>
{
x.Queue("orders.created");
x.Queue("payments.processed");
x.Queue("notifications.email");
});
Direct Exchange
Route messages by exact routing key match:
topology.Direct("payments.direct", direct =>
{
direct.Queue("payments.authorized", "payment.authorized");
direct.Queue("payments.failed", "payment.failed");
});
Topic Exchange
Route messages by wildcard patterns (* = one word, # = zero or more):
topology.Topic("orders.events", topic =>
{
topic.Queue("orders.created", "order.created.*");
topic.Queue("orders.all", "order.#");
});
Fanout Exchange
Broadcast to all bound queues (routing key ignored):
topology.Fanout("notifications.fanout", fanout =>
{
fanout.Queue("notifications.email");
fanout.Queue("notifications.sms");
fanout.Queue("notifications.push");
});
Headers Exchange
Route by header matching:
topology.Headers("risk.headers", headers =>
{
headers.Queue("risk.high",
b => b.MatchAll().Header("region", "eu").Header("priority", "high"));
headers.Queue("risk.any",
b => b.MatchAny().Header("region", "eu").Header("priority", "high"));
});
Queue Options
Available on both QueueDefaults(...) and per-queue Queue("name", q => ...):
| Method | Description |
|---|---|
.Quorum() |
Quorum queue (replicated, durable — recommended) |
.Stream() |
Stream queue (append-only log) |
.Type(RabbitMqQueueType.Classic) |
Explicit queue type |
.Durable(bool) |
Survive broker restart (default: true) |
.Exclusive(bool) |
Exclusive to connection |
.AutoDelete(bool) |
Delete when last consumer disconnects |
.Ttl(int ms) |
Per-message TTL |
.MaxLength(int) |
Max message count |
.MaxLengthBytes(long) |
Max total size in bytes |
.MaxPriority(int) |
Enable priority queue (0–255) |
.LazyMode() |
Store messages to disk early |
.DeadLetterDefaultExchange() |
Route dead letters via "" exchange to {name}.dlq |
.DeadLetterNamedExchange(...) |
Route dead letters via a named exchange |
.NoDeadLetter() |
Disable dead lettering |
Dead Letter Queues
Default Exchange DLQ (Recommended)
x.Queue("orders.created", q => q.DeadLetterDefaultExchange());
Creates:
- Main queue:
orders.createdwithx-dead-letter-exchange: ""andx-dead-letter-routing-key: orders.created.dlq - DLQ:
orders.created.dlq(durable, classic)
Named Exchange DLQ
x.Queue("orders.created", q => q
.DeadLetterNamedExchange("dlx.orders", routingKey: "failed", dlqName: "orders.dead"));
Creates:
- Main queue with
x-dead-letter-exchange: dlx.orders - Exchange:
dlx.orders(direct, durable) - DLQ:
orders.deadbound todlx.orderswith routing keyfailed
Consumers
Message Consumer
Each queue may be assigned to exactly one consumer type. AddRabbitMq throws immediately when two consumers use the same [Queue("name")], when a consumer's queue is not declared in the topology, or when [Queue] settings are invalid. Consumers are resolved from a new DI scope per message.
[Queue("orders.created", PrefetchCount = 50, MaxRetryAttempts = 5, RequeueOnFailure = true)]
public sealed class OrderCreatedConsumer : MessageConsumer<OrderCreatedEvent>
{
private readonly IOrderService _orderService;
public OrderCreatedConsumer(IOrderService orderService)
{
_orderService = orderService;
}
public override async Task ConsumeAsync(
ConsumeContext<OrderCreatedEvent> context,
CancellationToken cancellationToken = default)
{
await _orderService.ProcessAsync(context.Message, cancellationToken);
}
}
[Queue] attribute options:
| Property | Default | Description |
|---|---|---|
Name |
(required) | Queue name to consume from |
PrefetchCount |
0 (use global) |
Override QoS prefetch for this consumer |
ConsumerDispatchConcurrency |
0 (use global) |
Deliveries processed concurrently |
AutoAck |
false |
Broker-side ack on delivery: failed messages are lost (no retry/DLQ). Ignored for RPC consumers |
MaxRetryAttempts |
3 |
Retries before the message is rejected (to the DLQ if configured) |
RequeueOnFailure |
false |
Treat Reject from OnErrorAsync (the default) as Requeue, i.e. retry every failure |
RetryDelayMs |
0 |
Delay before a retry is redelivered (0 = immediately) |
RetryBackoffMultiplier |
2 |
Delay multiplier per further attempt |
MaxRetryDelayMs |
300000 |
Upper bound for the computed delay |
Consumer Lifecycle Hooks
[Queue("orders.created")]
public sealed class OrderCreatedConsumer : MessageConsumer<OrderCreatedEvent>
{
public override async Task<bool> OnBeforeConsumeAsync(
ConsumeContext<OrderCreatedEvent> context,
CancellationToken cancellationToken = default)
{
// Return false to skip processing and acknowledge
if (context.Message.Amount <= 0) return false;
return true;
}
public override async Task ConsumeAsync(
ConsumeContext<OrderCreatedEvent> context,
CancellationToken cancellationToken = default)
{
// Main processing logic
}
public override async Task OnAfterConsumeAsync(
ConsumeContext<OrderCreatedEvent> context,
CancellationToken cancellationToken = default)
{
// Post-processing (runs after successful consume)
}
}
Error Handling
Consumer Pipeline Lifecycle
Every message flows through these stages in order:
OnBeforeConsumeAsync— optional pre-processing gate. Returnfalseto skip the message and auto-ack it.ConsumeAsync— your business logic (required override).OnAfterConsumeAsync— optional post-processing hook after successful consumption.- If
ConsumeAsync(or any stage) throws,OnErrorAsyncis invoked instead.
ErrorHandlingResult Options
When ConsumeAsync throws, the framework catches the exception and calls OnErrorAsync. You return one of three values:
| Result | Behavior |
|---|---|
Acknowledge |
Ack the message — removed from the queue permanently. |
Reject |
Reject without requeue. If a DLQ is configured, the message goes there. (default) |
Requeue |
Retry the message (up to MaxRetryAttempts), then reject it. |
The default OnErrorAsync implementation returns ErrorHandlingResult.Reject.
How Retry Works Internally
The library never uses BasicNack(requeue: true) for handler failures (that loops forever). Instead:
- It reads the
x-retry-countheader (starts at0). - If
retryCount < MaxRetryAttempts, it publishes a copy withx-retry-count + 1directly to the consumer's own queue through the default exchange (so a retry of a fanout/topic message is never re-delivered to the other bound queues), waits for the broker confirm, and then acks the original. - With
RetryDelayMs > 0the copy goes to{queue}.retryinstead — a queue declared automatically whose expired messages are dead-lettered back to{queue}. The per-message TTL isRetryDelayMs * RetryBackoffMultiplier^(attempt-1), capped atMaxRetryDelayMs. Because RabbitMQ only expires messages at the head of a queue, delays are minimums: a long delay can hold back shorter ones queued behind it. - When retries are exhausted the message is rejected (
requeue: false) and goes to the DLQ if one is configured.
Settlement is guaranteed: if OnErrorAsync throws, the message is rejected; if the retry copy cannot be published, the original is nacked with requeue so it is redelivered instead of lost; any unexpected error rejects the delivery rather than leaving it unacknowledged (which would stall the consumer once prefetch is exhausted). Delivery is at-least-once — keep consumers idempotent.
Accessing Retry Count
The current retry attempt is exposed on ConsumeContext<T>.RetryCount:
public override Task ConsumeAsync(ConsumeContext<OrderCreated> context, CancellationToken ct)
{
if (context.RetryCount > 0)
Console.WriteLine($"Retry attempt: {context.RetryCount}");
// business logic
return Task.CompletedTask;
}
Full Example: Retry with Conditional Error Handling + DLQ
1. Configure the queue with a DLQ:
topology.Default(x => x.Queue("payments.process", q => q
.Quorum()
.DeadLetterDefaultExchange())); // creates payments.process.dlq
2. Implement the consumer:
using LowCodeHub.RabbitMQ.Abstractions;
using LowCodeHub.RabbitMQ.Attributes;
[Queue("payments.process", MaxRetryAttempts = 5, RetryDelayMs = 1_000)]
public sealed class PaymentsConsumer : MessageConsumer<PaymentCommand>
{
public override async Task ConsumeAsync(
ConsumeContext<PaymentCommand> context,
CancellationToken cancellationToken = default)
{
await ProcessPaymentAsync(context.Message, cancellationToken);
}
public override Task<ErrorHandlingResult> OnErrorAsync(
ConsumeContext<PaymentCommand> context,
Exception exception,
CancellationToken cancellationToken = default)
{
// Transient errors → retry (up to MaxRetryAttempts)
if (exception is HttpRequestException or TimeoutException)
return Task.FromResult(ErrorHandlingResult.Requeue);
// Permanent errors → reject immediately (goes to DLQ)
return Task.FromResult(ErrorHandlingResult.Reject);
}
}
What happens at runtime:
ConsumeAsyncthrows anHttpRequestException→OnErrorAsyncreturnsRequeue.- The message is republished to
payments.process.retrywithx-retry-count = 1and re-delivered topayments.processafter 1s (then 2s, 4s, ...). - Steps 1–2 repeat up to 5 times.
- After 5 retries the message is rejected and routed to
payments.process.dlqfor inspection. - If
ConsumeAsyncthrows a non-transient exception (e.g.ArgumentException),OnErrorAsyncreturnsRejectand the message goes to the DLQ immediately without any retry.
Graceful Shutdown
On host shutdown the consumers stop receiving new deliveries (basic.cancel), in-flight handlers are allowed to finish within the host's shutdown timeout, and only then are the channels closed. Handlers still running at the timeout get their CancellationToken cancelled; their messages are redelivered.
Recovery
- With
AutomaticRecoveryEnabled(default) RabbitMQ.Client reconnects and restores channels and consumers itself; the library never replaces a recovering connection. Publishing during recovery throwsRabbitMqConnectionRecoveringException. - A watchdog restarts any consumer whose channel was closed by a channel-level error (e.g.
406 PRECONDITION_FAILED), after a connection was recreated (auto-recovery disabled), and after a recovery whenTopologyRecoveryEnabledisfalse(topology is re-declared first). - If the broker is unreachable at startup, startup is retried
StartupRetryCounttimes with exponential backoff; configuration errors (e.g.406topology conflicts) fail immediately.
ConsumeContext Properties
| Property | Type | Description |
|---|---|---|
Message |
TMessage |
Deserialized message body |
Body |
ReadOnlyMemory<byte> |
Raw message bytes |
Properties |
IReadOnlyBasicProperties |
AMQP message properties |
DeliveryTag |
ulong |
Delivery tag for ack/nack |
Exchange |
string |
Source exchange |
RoutingKey |
string |
Routing key |
Redelivered |
bool |
Whether this is a redelivery |
ConsumerTag |
string |
Consumer tag |
MessageId |
string? |
Message ID |
CorrelationId |
string? |
Correlation ID |
RetryCount |
int |
Current retry attempt (0-based) |
Timestamp |
DateTimeOffset? |
Publish timestamp |
Publishing
Publish to Default Exchange
Point-to-point delivery to a specific queue:
await publisher.PublishWithDefaultExchangeAsync("orders.created", message, cancellationToken: ct);
Publish to Named Exchange
Route through an exchange with a routing key:
await publisher.PublishAsync("orders.events", "order.created.eu", message, cancellationToken: ct);
Publisher Confirms
Wait for broker acknowledgment (reliable publishing). Returns false instead of throwing when the publish fails or is not confirmed within PublishOptions.ConfirmTimeoutMs (default 30s). Set EnablePublisherConfirms to make every PublishAsync confirmed (failures then throw):
bool confirmed = await publisher.PublishWithConfirmAsync(
"orders.events", "order.created.eu", message, cancellationToken: ct);
if (!confirmed)
{
// Handle publish failure
}
Batch Publishing
Publish multiple messages on a single channel. With publisher confirms enabled, up to 256 confirms are kept in flight and the call throws if any message is not confirmed:
var messages = new[] { order1, order2, order3 };
await publisher.PublishBatchAsync("orders.events", "order.created", messages, cancellationToken: ct);
Publish Options
await publisher.PublishAsync("orders.events", "order.created", message, new PublishOptions
{
MessageId = "custom-id",
CorrelationId = correlationId,
Persistent = true, // Survive broker restart (default: true)
Priority = 5, // 0-9
Expiration = "60000", // TTL in ms
Mandatory = true, // Return unroutable messages
Headers = new() { ["tenant"] = "acme" }
}, ct);
The publisher is a thread-safe singleton: unconfirmed publishes share one channel (preserving the order of a caller's sequential publishes) and confirmed publishes are spread over PublisherConfirmChannelPoolSize channels; each channel is used by one publish at a time. PublishOptions is not mutated, so instances can be reused. The current Activity is propagated in a traceparent header.
Factory methods:
PublishOptions.WithCorrelationId("abc-123");
PublishOptions.WithExpiration(60_000);
PublishOptions.ForRpc("reply.queue", correlationId: "abc");
RPC (Request/Reply)
RPC Server
[Queue("pricing.requests")]
public sealed class PricingRpcConsumer : RpcMessageConsumer<PriceRequest, PriceResponse>
{
public override async Task<PriceResponse> HandleAsync(
RpcContext<PriceRequest> context,
CancellationToken cancellationToken = default)
{
var price = await CalculatePrice(context.Message);
return new PriceResponse { Total = price };
}
}
RPC Client
IMessageRpcClient is registered by AddRabbitMq. Make a call:
public class PricingService(IMessageRpcClient rpcClient)
{
public async Task<PriceResponse> GetPriceAsync(PriceRequest request, CancellationToken ct)
{
return await rpcClient.CallAsync<PriceRequest, PriceResponse>(
exchange: "",
routingKey: "pricing.requests",
request: request,
timeoutMs: 10_000,
cancellationToken: ct);
}
}
The client uses RabbitMQ direct reply-to (amq.rabbitmq.reply-to), so there is no reply queue to declare and nothing goes stale after a reconnect.
- A handler failure is reported back once no retry is pending:
CallAsyncthrowsRabbitMqRpcException(withRemoteExceptionType) instead of waiting for the timeout.RequeueOnFailure/Requeueretries are bounded byMaxRetryAttemptslike regular consumers. - Requests are published
mandatory: an unroutable request fails immediately withRabbitMqRpcException. - Requests expire after
timeoutMs(unlessPublishOptions.Expirationis set), so nobody processes a request whose caller has given up. - On timeout
CallAsyncthrowsTimeoutException.
Health Checks
Automatically registered with tag rabbitmq:
app.MapHealthChecks("/health", new HealthCheckOptions
{
Predicate = check => check.Tags.Contains("rabbitmq")
});
| Status | When |
|---|---|
| Healthy | Connection open and every consumer running |
| Degraded | Connected, but consumers are still starting or a consumer channel is down (the watchdog is restarting it) |
| Unhealthy | No connection (broker unreachable or auto-recovery in progress) |
Data includes the endpoint, cluster name, consumer count and the queues whose consumers are down. The check never replaces a recovering connection.
Observability
Built-in OpenTelemetry support via System.Diagnostics.ActivitySource and System.Diagnostics.Metrics.
Activity source: LowCodeHub.RabbitMQ
| Activity | Kind | Description |
|---|---|---|
rabbitmq.publish |
Producer | Per publish / batch; injects a W3C traceparent header |
rabbitmq.consume |
Consumer | Per-message processing span, parented to the incoming traceparent |
rabbitmq.rpc.call |
Client | RPC call |
Meters: LowCodeHub.RabbitMQ
| Metric | Type | Description |
|---|---|---|
rabbitmq.consumer.messages.processed |
Counter | Messages successfully processed |
rabbitmq.consumer.messages.failed |
Counter | Messages that failed processing |
rabbitmq.consumer.messages.retried |
Counter | Messages republished for retry |
rabbitmq.consumer.processing.duration |
Histogram | Processing time (ms) |
rabbitmq.consumer.restarts |
Counter | Consumers restarted by the watchdog |
rabbitmq.publisher.messages.published |
Counter | Messages published (batches count every message) |
rabbitmq.publisher.messages.failed |
Counter | Publish failures |
rabbitmq.publisher.duration |
Histogram | Publish time (ms) |
rabbitmq.healthcheck.total |
Counter | Health check invocations |
rabbitmq.healthcheck.failed |
Counter | Failed health checks |
rabbitmq.healthcheck.duration |
Histogram | Health check time (ms) |
Subscribe in your OpenTelemetry setup:
builder.Services.AddOpenTelemetry()
.WithTracing(t => t.AddSource("LowCodeHub.RabbitMQ"))
.WithMetrics(m => m.AddMeter("LowCodeHub.RabbitMQ"));
Clustering
Configure multiple endpoints for high availability:
{
"RabbitMQ": {
"HostName": "rabbit-1",
"Port": 5672,
"UserName": "myapp",
"Password": "secret",
"Endpoints": [
{ "HostName": "rabbit-1", "Port": 5672 },
{ "HostName": "rabbit-2", "Port": 5672 },
{ "HostName": "rabbit-3", "Port": 5672 }
]
}
}
The client connects to the first available node. SSL settings are propagated to all endpoints. On connection loss, automatic recovery reconnects to any available node with topology re-declaration.
SSL/TLS
{
"RabbitMQ": {
"HostName": "rabbitmq.prod",
"Port": 5671,
"Ssl": {
"Enabled": true,
"ServerName": "rabbitmq.prod",
"CertificatePath": "/certs/client.pfx",
"CertificatePassword": "cert-password",
"AllowInsecureCertificateValidation": false
}
}
}
⚠️
AllowInsecureCertificateValidation: truedisables certificate verification. A startup warning is logged. Do not use in production.
Conflict Handling
When your topology changes (e.g., switching a queue from classic to quorum), the broker rejects re-declaration with PRECONDITION_FAILED (406).
Default behavior — fail fast on startup:
topology.Settings(s => s.DeleteAndRecreateOnConflict(false));
Auto-recreate — delete the conflicting entity and recreate it:
topology.Settings(s => s.DeleteAndRecreateOnConflict());
The delete is guarded (
ifUnusedfor exchanges,ifUnused+ifEmptyfor queues), so an entity that is in use or still holds messages is never dropped — the original406is surfaced instead. Use for development/staging or planned migrations.
Custom Serializer
Default: System.Text.Json with JsonSerializerDefaults.Web.
Replace globally (before or after AddRabbitMq):
builder.Services.UseMessageSerializer<MessagePackSerializer>();
Implement IMessageSerializer:
public sealed class MessagePackSerializer : IMessageSerializer
{
public string ContentType => "application/x-msgpack";
public byte[] Serialize<T>(T message) { /* ... */ }
public T? Deserialize<T>(ReadOnlySpan<byte> data) { /* ... */ }
public object? Deserialize(ReadOnlySpan<byte> data, Type type) { /* ... */ }
}
Architecture Overview
AddRabbitMq(config, topology => { ... })
│
├─ RabbitMqMessagingConfiguration ← Fluent DSL input
│ │
│ ▼
├─ RabbitMqTopologyCompiler ← Validates + compiles to declarations
│ │
│ ▼
├─ RabbitMqCompiledTopology ← Exchanges, queues, bindings, name mappings
│
├─ DI Registration
│ ├─ IRabbitMqConnectionManager ← Connection lifecycle, recovery-aware (singleton)
│ ├─ IMessagePublisher ← Publish API over a locked channel pool (singleton)
│ ├─ IMessageRpcClient ← RPC client, direct reply-to (singleton)
│ ├─ IMessageSerializer ← JSON by default (singleton)
│ └─ RabbitMqHealthCheck ← ASP.NET health check
│
└─ RabbitMqConsumerHostedService ← IHostedService
├─ TopologyInitializer ← Declares topology on broker at startup
├─ Consumer discovery ← Explicit Consumer<T>() or [Queue] scanning
├─ Per-queue dedicated channel ← Isolated QoS / dispatch concurrency per consumer
├─ Watchdog ← Restarts consumers the client will not recover
└─ Graceful drain ← Cancel → finish in-flight → close
Production Checklist
- Use quorum queues for business-critical workloads
- Configure dead letter queues for failed message inspection
- Set
AutoAck = false(default) for reliable message processing - Keep consumers idempotent — at-least-once delivery under retries
- Use publisher confirms for critical publishes
- Set proper credentials — startup warns on
guestusage - Enable SSL/TLS for production brokers
- Configure cluster endpoints for high availability
- Subscribe to
LowCodeHub.RabbitMQactivity source and meter for observability - Set
DeleteAndRecreateOnConflict(false)in production (default) - Review startup topology report logs for warnings
- Map the
rabbitmqhealth check (Degraded = a consumer is down) - Give the host a shutdown timeout long enough for in-flight handlers to finish
Requirements
- .NET 11 or later
RabbitMQ.Client7.x (included as a dependency)
License
MIT © Ahmed Abuelnour
AI agent skills
This package targets net11.0 and includes version-matched agent instructions under
skills/. After restoring your application's dependencies, install them into your
agent's skill directory:
dotnet tool install --global dotnet-package-skills --prerelease
dotnet-package-skills install
The default destination is .agents/skills/. For Claude, pass
--destination .claude/skills. Run the installer again after package upgrades.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net11.0 is compatible. |
-
net11.0
- Microsoft.Extensions.Diagnostics.HealthChecks (>= 11.0.0)
- Microsoft.Extensions.Options.ConfigurationExtensions (>= 11.0.0)
- RabbitMQ.Client (>= 7.2.2)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.