Anyone searching for a RabbitMQ .NET tutorial has usually moved past “hello world” and wants to know what changes in production: how to retry without blocking the queue, what to do with a message that always fails, and how not to lose an event when the database commits and the broker goes down. We run RabbitMQ in 15 systems and .NET in 16, so this article comes from real projects, with the shortest code snippets that explain each point.
Plain client or MassTransit
The official package is RabbitMQ.Client. It exposes connections, channels, exchanges, queues and consumers. Nothing more. You write serialization, retry, error handling, reconnection and correlation yourself.
Libraries such as MassTransit (and alternatives like Wolverine and NServiceBus) sit on top and deliver typed contracts, topology created from your types, configurable retry and redelivery, outbox, sagas and in-memory test harnesses. For business systems, that layer usually pays off, because time goes to the rules and not to the plumbing. Mind the license: MassTransit v8 remains under Apache 2.0, with maintenance announced through at least the end of 2026, and v9 is commercial and requires a paid license (official announcement). Evaluate the alternatives, Wolverine and NServiceBus, or use RabbitMQ.Client directly.
The plain client makes sense for small services, integration tools and cases where every millisecond and every dependency counts.
Topology: exchanges, queues and bindings
A layout that works well for most cases:
- one exchange per event type (fanout or topic) for events that several services consume;
- one queue per consuming service, bound to the exchange. Each service gets its own copy and processes at its own pace;
- a direct command queue for work addressed to one specific service;
- a dead-letter exchange with one error queue per service.
With MassTransit, the topology comes from the message types. With the plain client, declare everything idempotently at startup.
Quorum queues as the default
For durable queues, use quorum queues. They replicate messages across cluster nodes through Raft consensus and survive the loss of a node without losing acknowledged data. Mirrored classic queues were deprecated and removed in recent versions, so there is no reason to start with them.
Two properties deserve attention:
x-delivery-limitcaps how many times a message returns to the queue. Past the limit, it goes to the dead-letter exchange or is dropped. This cuts the infinite loop of a poison message.- They use more disk and memory than classic queues and offer priority at only two levels (normal and high), starting with RabbitMQ 4.0, while classic queues have more levels. For temporary or very short-lived queues, a classic queue is still valid.
Declaring a quorum queue with the official client:
await channel.QueueDeclareAsync(
queue: "orders.process",
durable: true,
exclusive: false,
autoDelete: false,
arguments: new Dictionary<string, object?>
{
["x-queue-type"] = "quorum",
["x-delivery-limit"] = 5,
["x-dead-letter-exchange"] = "orders.dlx"
});
Acknowledgment: from producer to consumer
Two mechanisms close the chain.
Publisher confirms on the producer: the broker replies that it persisted the message. Without them, a Publish that returned without error may still have been lost.
Manual ack on the consumer: you confirm only after processing. If the process dies midway, the message returns to the queue.
var consumer = new AsyncEventingBasicConsumer(channel);
consumer.ReceivedAsync += async (_, ea) =>
{
try
{
await handler.HandleAsync(ea.Body, ea.BasicProperties.MessageId);
await channel.BasicAckAsync(ea.DeliveryTag, multiple: false);
}
catch (TransientException)
{
await channel.BasicNackAsync(ea.DeliveryTag, false, requeue: true);
}
catch
{
await channel.BasicNackAsync(ea.DeliveryTag, false, requeue: false); // goes to the DLX
}
};
await channel.BasicQosAsync(0, prefetchCount: 20, global: false);
await channel.BasicConsumeAsync("orders.process", autoAck: false, consumer);
prefetchCount defines how many unacknowledged messages a consumer holds. Very high values pile load onto a slow consumer, and very low values underuse the network. Start around 10 to 50 and tune by measuring.
Retries without blocking the queue
There are two kinds of failure, and each needs different handling.
Transient failure (timeout, deadlock, external service down). Retry with growing delays. In MassTransit:
x.AddConsumer<ProcessOrderConsumer>();
cfg.ReceiveEndpoint("orders.process", e =>
{
e.SetQuorumQueue(3);
e.UseMessageRetry(r => r.Exponential(
retryLimit: 5,
minInterval: TimeSpan.FromSeconds(1),
maxInterval: TimeSpan.FromMinutes(1),
intervalDelta: TimeSpan.FromSeconds(5)));
e.ConfigureConsumer<ProcessOrderConsumer>(context);
});
In-memory retry holds the message in the consumer and occupies a prefetch slot. For long delays (minutes), use redelivery with a scheduled message, or retry queues with TTL that dead-letter back to the main queue. That way the main queue keeps moving.
Permanent failure (malformed message, violated rule). Retrying is pointless. Reject without requeue and send it to the DLQ.
Dead-letter queue: what to do with it
A DLQ only helps if someone looks at it. Recommended practices:
- store the reason in a header (
x-exception-type,x-exception-message) and the correlation ID; - alert when the DLQ size rises above zero and stays there;
- a clear replay procedure: fix the cause and republish to the original queue, with a tool or an admin command;
- a defined retention: a DLQ without a policy becomes a dumping ground.
In MassTransit, messages that exhaust retry go to an _error queue, and those that fail in a way the consumer cannot process go to _skipped. The same works as a convention for the plain client.
Idempotency: the consumer must tolerate repeats
Delivery is at-least-once. The same message can arrive more than once: lost ack, redelivery after a crash, producer retry. The handler must produce the same effect on the first and on the fifth execution.
Strategies, from simplest to most robust:
- Naturally idempotent operation:
UPDATE ... SET status = 'paid'instead ofbalance = balance + amount. - Processed-messages table with a unique key on
MessageId, inserted in the same transaction as the business rule. If the insert fails on a duplicate, the handler exits with no effect. - Idempotency key in the external system, when the handler calls a third-party API.
await using var tx = await db.Database.BeginTransactionAsync();
if (!await db.Processed.AnyAsync(p => p.MessageId == msg.MessageId))
{
db.Processed.Add(new Processed(msg.MessageId));
await ProcessAsync(msg);
await db.SaveChangesAsync();
}
await tx.CommitAsync();
Under high concurrency, rely on the database’s unique constraint and handle the duplicate-key exception, instead of counting on AnyAsync alone.
Outbox: do not lose events between the database and the broker
Consider a handler that writes an order to SQL Server and publishes OrderCreated. If the database commits and the broker is down, the event vanishes. If you publish first and the database fails, the event announces something that does not exist. There is no practical distributed transaction between the two.
The transactional outbox solves it: you write the event to an Outbox table in the same transaction as the order. A background process reads the table and publishes to RabbitMQ with publisher confirms, marking each row as sent. It may publish the same event twice, which is why the consumer is idempotent.
MassTransit offers an outbox integrated with Entity Framework Core, with the outbox table in the same DbContext and a delivery service:
services.AddMassTransit(x =>
{
x.AddEntityFrameworkOutbox<AppDbContext>(o =>
{
o.UseSqlServer();
o.UseBusOutbox();
});
x.UsingRabbitMq((ctx, cfg) => cfg.ConfigureEndpoints(ctx));
});
With the outbox on, Publish inside the handler writes to the table, and the SaveChanges commit carries event and data together.
Observability and operations
In production, four signals are enough to start:
- queue depth and consumption rate per queue;
- unacknowledged messages and connected consumers;
- DLQ size and the age of the oldest message;
- memory and disk alarms on the broker.
RabbitMQ exposes metrics for Prometheus, and .NET propagates trace context with OpenTelemetry. MassTransit ships with instrumentation. Connecting the trace from the HTTP request to the consumer saves hours of investigation. On Kubernetes, the official RabbitMQ operator manages the cluster and the quorum queues.
Mistakes we see often
- One connection per published message. Connections are expensive and should be long-lived. Use one per process and channels per thread or task.
- Auto-ack turned on. The message disappears from the broker before it is processed.
- Unbounded queue with no alert, which grows until the memory alarm blocks the producers.
- Message contract with no versioning. Changing a field breaks old consumers. Prefer additive changes.
- Messages that are too large. Store the payload in object storage and send the reference.
Tests and the local environment
Run RabbitMQ in a container in the development environment and in the CI pipeline. Three integration tests are the most valuable. The first publishes a message and checks the effect in the database. The second publishes the same message twice and checks that the effect appears only once. The third forces a permanent exception and checks that the message reaches the DLQ with the reason. MassTransit has an in-memory harness for testing consumers without a broker, which helps with business rules. Queue, ack and dead-letter behavior, however, can only be validated against a real RabbitMQ.
Also configure the client’s automatic reconnection and treat channel closure as a normal event. Networks and cluster nodes fail, and the service must recover on its own.
Where this fits in a .NET system
Messaging rarely arrives alone. When we move legacy Windows Services to Worker Services, queues replace timers and polling loops, which adds resilience. Read the full path in our guide to .NET Framework to .NET migration. If you are still deciding on the broker itself, start with RabbitMQ vs Kafka.
How we can help
We design queues, retries, dead-lettering, outbox and observability in custom .NET systems, and we review messaging that is already in production. See our RabbitMQ consulting expertise, our custom software development practice and the Regina Festas case study, where RabbitMQ runs asynchronous tasks in production. The free assessment is the starting point: you bring the current architecture and leave with scope and timeline in weeks.