Introduction
The fact that RabbitMQ delivered a message to a consumer does not mean that the work has successfully completed. The consumer may stop immediately after receiving the message, the network connection may fail, a database operation may be rejected, or the process may restart before the handler finishes. A reliable asynchronous system must therefore distinguish between “the message was delivered” and “the message was processed successfully.”
In this lesson, you will compare automatic and manual acknowledgements, use BasicAck, BasicNack, and BasicReject, and limit the number of outstanding deliveries with prefetch. You will also test multiple consumer instances and observe what happens to unacknowledged messages during application shutdown.
1. Automatic and manual acknowledgements
RabbitMQ provides two basic acknowledgement modes. With automatic acknowledgement, the consumer is registered with autoAck: true. RabbitMQ considers the message handled as soon as it delivers it to the connection. If the consumer fails after receiving the message but before completing the business operation, the message is not guaranteed to be delivered again.
With manual acknowledgement, the consumer is registered with autoAck: false. The consumer explicitly acknowledges the message after processing succeeds. If the channel or connection closes before the acknowledgement is sent, RabbitMQ can requeue the unacknowledged delivery. This provides at-least-once delivery semantics, so the application must be prepared for redelivery and duplicate execution.
| Approach | Benefit | Risk |
|---|---|---|
| Automatic acknowledgement | Simple and potentially higher delivery throughput | The message can be lost before processing completes |
| Manual acknowledgement | The application controls when processing is complete | Redelivery and idempotency must be handled |
For long-running operations, database writes, email delivery, and external service calls, manual acknowledgement is usually the safer starting point.
2. BasicAck, BasicNack, and BasicReject
BasicAck
BasicAck tells RabbitMQ that a delivery was processed successfully. The acknowledgement must be sent on the same channel that delivered the message. Sending it through another channel can cause an “unknown delivery tag” error and close the channel.
Use multiple: false to acknowledge one delivery. With multiple: true, the client can acknowledge all outstanding deliveries up to the specified delivery tag. Batch acknowledgements may reduce protocol traffic, but they should only be used when the application can guarantee that the preceding messages have also completed successfully.
BasicNack
BasicNack reports that processing failed and can apply to multiple deliveries. Its most important option is requeue. A temporary database or external service failure may justify requeue: true. However, blindly requeueing every failure can create an infinite retry loop.
BasicReject
BasicReject rejects one message. With requeue: false, the message is discarded or routed to a dead-letter exchange if the queue is configured for dead lettering. Invalid JSON, unsupported message types, and permanent validation failures are good candidates for rejection without requeueing.
3. A manual acknowledgement consumer in .NET
The following example uses the asynchronous RabbitMQ .NET client API. The consumer calls BasicAckAsync only after the handler completes successfully. Temporary failures are requeued, while permanent failures are rejected.
using System.Text.Json;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
public sealed class OrderConsumer : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private IConnection? _connection;
private IChannel? _channel;
public OrderConsumer(IServiceScopeFactory scopeFactory)
{
_scopeFactory = scopeFactory;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var factory = new ConnectionFactory
{
HostName = "localhost",
UserName = "app",
Password = "app-password"
};
_connection = await factory.CreateConnectionAsync(stoppingToken);
_channel = await _connection.CreateChannelAsync(cancellationToken: stoppingToken);
await _channel.BasicQosAsync(0, prefetchCount: 4, global: false, stoppingToken);
await _channel.QueueDeclareAsync("orders", durable: true, exclusive: false, autoDelete: false, cancellationToken: stoppingToken);
var consumer = new AsyncEventingBasicConsumer(_channel);
consumer.ReceivedAsync += async (_, args) =>
{
try
{
var order = JsonSerializer.Deserialize<OrderMessage>(args.Body.Span)
?? throw new InvalidOperationException("The message body is empty.");
using var scope = _scopeFactory.CreateScope();
var handler = scope.ServiceProvider.GetRequiredService<IOrderHandler>();
await handler.HandleAsync(order, stoppingToken);
await _channel.BasicAckAsync(args.DeliveryTag, multiple: false, stoppingToken);
}
catch (JsonException)
{
await _channel.BasicRejectAsync(args.DeliveryTag, requeue: false, stoppingToken);
}
catch (TemporaryDependencyException)
{
await _channel.BasicNackAsync(args.DeliveryTag, multiple: false, requeue: true, stoppingToken);
}
catch (Exception)
{
await _channel.BasicNackAsync(args.DeliveryTag, multiple: false, requeue: false, stoppingToken);
}
};
await _channel.BasicConsumeAsync("orders", autoAck: false, consumer, stoppingToken);
await Task.Delay(Timeout.InfiniteTimeSpan, stoppingToken);
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
if (_channel is not null)
await _channel.CloseAsync(cancellationToken);
if (_connection is not null)
await _connection.CloseAsync(cancellationToken);
await base.StopAsync(cancellationToken);
}
}
public sealed record OrderMessage(Guid OrderId, decimal Total);The example creates a dependency injection scope for each message. Because the consumer is a singleton hosted service, scoped dependencies should not be captured directly in its constructor. Creating a scope while processing the delivery keeps database contexts and other scoped services within the correct lifetime.
4. Limiting consumer load with prefetch
Prefetch limits how many messages a consumer can receive before acknowledging previous deliveries. With prefetchCount: 4, the consumer can have at most four unacknowledged deliveries in flight. Once those messages are acknowledged, RabbitMQ can deliver more.
A very high prefetch value can increase consumer memory usage and allow unprocessed messages to accumulate inside the application. A very low value can reduce throughput, especially when each operation has noticeable latency. A value of 1 is conservative and easy to reason about, but it is not always the fastest option. Start with a small value such as 4, 8, or 16, then observe processing time, CPU, memory, and queue backlog.
RabbitMQ can apply prefetch per consumer in practical consumer configurations. When multiple consumers share a channel, the scope of the setting should be understood deliberately. For a simpler and more predictable design, one channel per consumer instance is often preferable.
5. Concurrency: how much work should run at once?
Concurrency is not simply about consuming more messages. It determines how much simultaneous pressure is placed on the database, CPU, network, and external services. If two consumer instances are attached to the same queue, RabbitMQ distributes deliveries between them, allowing horizontal scaling.
For example, if each instance uses a prefetch of 4 and two instances are running, up to eight deliveries may be outstanding across the system. This does not necessarily mean that exactly eight operations are completing at the same instant. Task scheduling, client dispatch behavior, database connection limits, and external API rate limits also affect the result.
Before increasing concurrency, answer these questions:
- How many simultaneous writes can the database handle?
- Does the external API impose a rate limit?
- What happens if the same order is processed twice?
- How many messages can remain in consumer memory?
- Can a long-running handler exceed the acknowledgement timeout?
Each message handler should be idempotent. For example, a unique constraint on OrderId can protect an invoice record. When the same message is delivered again, the handler checks for an existing successful result and avoids creating a duplicate.
6. Retry and infinite requeue loops
Using requeue: true is useful for a basic example, but production systems need a more deliberate retry policy. If a dependency remains unavailable, the same message can be delivered repeatedly and prevent the queue from making progress.
A stronger strategy tracks the retry count in message headers or in a separate retry queue. After a fixed number of attempts, the message is routed to a dead-letter queue. Delayed retry can be implemented with a TTL and dead-letter exchange so that a failed message waits before it is attempted again.
The redelivered property indicates that a delivery has been delivered before, but it should not be treated as a complete retry counter. Use an explicit retry-count header or a durable processing record when the business process needs an exact retry limit.
7. Reliable behavior during application shutdown
When an ASP.NET Core hosted service shuts down, StopAsync is called and the host attempts to stop background work gracefully. A consumer should stop accepting new work, give active handlers an opportunity to finish, and then close its channel and connection.
If the process stops before an acknowledgement is sent, RabbitMQ can redeliver the unacknowledged message. This is expected behavior. “The message will not be lost during shutdown” is achieved through the combination of manual acknowledgement, an idempotent handler, and an appropriate shutdown timeout.
Do not acknowledge ownership of a message until the required business operation has actually completed. Otherwise, RabbitMQ may consider the message successful and cannot redeliver it after an application failure.
8. Common mistakes
- Acknowledging before processing: If the process fails after the acknowledgement, the message may be lost.
- Requeueing every failure: Permanent failures can become infinite retry loops.
- Leaving prefetch unlimited: This can create memory pressure in the consumer or broker.
- Sharing a channel carelessly: Delivery tags and acknowledgements are scoped to the delivery channel.
- Ignoring duplicate processing: Redelivery is normal; handlers should be idempotent.
- Injecting scoped services directly into a singleton consumer: Create an appropriate scope for each message.
9. Short practice exercise
Create a queue named reliable-orders. Run its consumer with manual acknowledgement and set the prefetch value to 2. Add three behaviors to the handler:
- Call
BasicAckAsyncwhen processing succeeds. - Simulate a temporary failure and retry it no more than three times.
- Reject invalid JSON with
BasicRejectAsyncand do not requeue it.
Run two instances of the same consumer and publish at least ten messages. Observe that deliveries are distributed between the instances. Stop one instance while it is processing a message, then verify that its unacknowledged message is delivered again to the other instance. Finally, confirm that processing the same OrderId twice does not create duplicate business records.
Conclusion
Reliable message consumption in RabbitMQ involves much more than reading a message. Manual acknowledgements define when processing is complete, BasicNack and BasicReject distinguish temporary and permanent failures, prefetch limits consumer pressure, and multiple instances provide controlled concurrency.
The central design rule is simple: process the message safely, acknowledge it afterward, treat redelivery as normal, and make retry behavior limited and observable. In the next lessons, this foundation will be extended with retry queues, dead-letter exchanges, and failure monitoring.
Sources
- https://www.rabbitmq.com/docs/confirms
- https://www.rabbitmq.com/docs/consumer-prefetch
- https://www.rabbitmq.com/docs/consumers
- https://rabbitmq.github.io/rabbitmq-dotnet-client/api/RabbitMQ.Client.IChannel.html
- https://learn.microsoft.com/en-gb/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-10.0