Introduction
In the previous lesson, we explored how to separate long-running work from the lifetime of an HTTP request and introduced the BackgroundService approach. In this lesson, we will learn how work can move between separate applications or services. We will build a simple but realistic producer-consumer flow that runs on RabbitMQ.
In our scenario, an order service will not perform a long-running operation such as sending an email or generating a report directly after creating an order. Instead, it will create a message and send it to RabbitMQ. A separate worker application will receive the message from a queue and process it. The API can therefore respond quickly while the background operation continues independently.
This lesson focuses on the concepts of broker, message, producer, consumer, and queue. Exchanges and routing will be covered in detail in later lessons. In RabbitMQ, messages are delivered to a queue directly or routed to one through an exchange.
The basic RabbitMQ model
Broker
RabbitMQ is a message broker that allows applications to send and receive messages. The broker accepts messages from producers, places them in the appropriate queue, and delivers them to consumer applications. A producer and a consumer do not need to run on the same machine. This separation makes it possible to scale services independently.
Producer
An application that sends messages is called a producer. For example, our ASP.NET Core API may publish an OrderCreated message after an order is created. The producer's responsibility is not to perform the work itself, but to send the required data as a reliable and understandable message.
Consumer
An application that receives and processes messages from a queue is called a consumer. A consumer is commonly implemented as a continuously running worker or BackgroundService. In this lesson, we will use a separate console application so the messaging concepts remain clear.
Queue
A queue is a buffer where messages wait until a consumer receives them. Multiple producers can send messages to the same queue. If multiple consumers listen to the same queue, RabbitMQ can distribute messages among them. This allows the workload to be shared across several worker instances.
| Concept | Purpose |
|---|---|
| Broker | The RabbitMQ server that manages message traffic |
| Message | The data or work instruction being transported |
| Producer | The application that sends a message |
| Consumer | The application that receives and processes a message |
| Queue | The buffer where messages wait |
Preparing the solution
If you started RabbitMQ with Docker in the previous lesson, the broker should be available through localhost:5672. Even if the management interface uses a different port, the application connection uses the AMQP port.
Let us add two console projects to the solution:
dotnet new sln -n AsyncMessaging
dotnet new console -n OrderProducer
dotnet new console -n OrderConsumer
dotnet sln add OrderProducer/OrderProducer.csproj
dotnet sln add OrderConsumer/OrderConsumer.csproj
dotnet add OrderProducer package RabbitMQ.Client
dotnet add OrderConsumer package RabbitMQ.Client
RabbitMQ .NET Client 7.x has an extensively asynchronous public API. We will therefore use await when creating connections, opening channels, declaring queues, publishing, and consuming.
Defining the message contract
The producer and consumer must understand the same message structure. In a real project, this contract can be placed in a shared class library. For this example, we will use the same record definition in both projects:
public sealed record OrderCreatedMessage(
Guid OrderId,
string CustomerEmail,
decimal TotalAmount,
DateTimeOffset CreatedAt);
We cannot send a .NET object directly as a RabbitMQ message. The message body is transported as bytes. We will therefore serialize the object to JSON and then convert the JSON text to UTF-8 bytes.
Building the producer
Update OrderProducer/Program.cs as follows:
using System.Text;
using System.Text.Json;
using RabbitMQ.Client;
const string queueName = "orders.created";
var message = new OrderCreatedMessage(
Guid.NewGuid(),
"customer@example.com",
1499.90m,
DateTimeOffset.UtcNow);
var factory = new ConnectionFactory
{
HostName = "localhost",
Port = 5672,
UserName = "guest",
Password = "guest",
ClientProvidedName = "order-producer"
};
using var connection = await factory.CreateConnectionAsync();
using var channel = await connection.CreateChannelAsync();
await channel.QueueDeclareAsync(
queue: queueName,
durable: true,
exclusive: false,
autoDelete: false,
arguments: null);
var json = JsonSerializer.Serialize(message);
var body = Encoding.UTF8.GetBytes(json);
var properties = new BasicProperties
{
ContentType = "application/json",
ContentEncoding = "utf-8",
DeliveryMode = DeliveryModes.Persistent,
MessageId = message.OrderId.ToString()
};
await channel.BasicPublishAsync(
exchange: string.Empty,
routingKey: queueName,
mandatory: false,
basicProperties: properties,
body: body);
Console.WriteLine($"Message published: {message.OrderId}");
public sealed record OrderCreatedMessage(
Guid OrderId,
string CustomerEmail,
decimal TotalAmount,
DateTimeOffset CreatedAt);
Reviewing the producer
ConnectionFactorydefines how the application connects to RabbitMQ.CreateConnectionAsyncopens a TCP connection to the broker.CreateChannelAsyncopens the channel used for RabbitMQ operations.QueueDeclareAsyncdeclares the queue. Both producer and consumer can declare the same queue; if it already exists, it is not created again.exchange: string.Emptyrefers to the default exchange. In this basic example, the queue name is used directly as the routing key.BasicPropertiesdescribes the content type, persistence preference, and unique message identifier.
durable: true allows the queue to survive a broker restart. However, this option alone does not guarantee that messages can never be lost. Message persistence, publisher confirms, and failure handling will be examined in later lessons.
Building the consumer
Now create OrderConsumer/Program.cs:
using System.Text;
using System.Text.Json;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
const string queueName = "orders.created";
var factory = new ConnectionFactory
{
HostName = "localhost",
Port = 5672,
UserName = "guest",
Password = "guest",
ClientProvidedName = "order-consumer"
};
using var connection = await factory.CreateConnectionAsync();
using var channel = await connection.CreateChannelAsync();
await channel.QueueDeclareAsync(
queue: queueName,
durable: true,
exclusive: false,
autoDelete: false,
arguments: null);
await channel.BasicQosAsync(
prefetchSize: 0,
prefetchCount: 1,
global: false);
var consumer = new AsyncEventingBasicConsumer(channel);
consumer.ReceivedAsync += async (_, eventArgs) =>
{
try
{
var body = eventArgs.Body.ToArray();
var json = Encoding.UTF8.GetString(body);
var message = JsonSerializer.Deserialize<OrderCreatedMessage>(json);
if (message is null)
{
throw new InvalidOperationException("The message could not be deserialized.");
}
Console.WriteLine(
$"Order received: {message.OrderId}, " +
$"customer: {message.CustomerEmail}, " +
$"amount: {message.TotalAmount}");
await Task.Delay(1000);
Console.WriteLine($"Order processed: {message.OrderId}");
await channel.BasicAckAsync(eventArgs.DeliveryTag, multiple: false);
}
catch (Exception exception)
{
Console.WriteLine($"Message processing failed: {exception.Message}");
await channel.BasicNackAsync(
eventArgs.DeliveryTag,
multiple: false,
requeue: false);
}
};
await channel.BasicConsumeAsync(
queue: queueName,
autoAck: false,
consumer: consumer);
Console.WriteLine("Consumer is running. Press Enter to exit.");
Console.ReadLine();
public sealed record OrderCreatedMessage(
Guid OrderId,
string CustomerEmail,
decimal TotalAmount,
DateTimeOffset CreatedAt);
Important consumer details
AsyncEventingBasicConsumer allows us to receive RabbitMQ messages through an asynchronous event handler. In RabbitMQ .NET Client 7.x, the memory represented by eventArgs.Body is valid within the callback's execution context. We therefore copy it with ToArray() before decoding and processing it.
This example uses autoAck: false. The consumer calls BasicAckAsync only after successful processing. If processing fails, it rejects the message with BasicNackAsync. The requeue: false choice prevents RabbitMQ from immediately putting the message back into the same queue. In a production system, a retry or dead-letter strategy should be designed for such messages.
prefetchCount: 1 in BasicQosAsync limits the consumer to one unacknowledged message at a time. This is useful for heavy operations because it prevents one worker from receiving more work than it can reasonably process.
Running the applications
- Verify that the RabbitMQ container is running.
- Start the consumer in one terminal:
dotnet run --project OrderConsumer - Run the producer in another terminal:
dotnet run --project OrderProducer - Observe that the consumer receives and processes the order message.
- Run the producer several times and verify that each run creates a new message.
If the producer runs before the consumer starts, the message waits in the queue. When the consumer starts later, it receives the queued message. This behavior is one of the main advantages of allowing an API and a background worker to operate independently.
Common mistakes
- Using different queue names: If the producer uses
orders.createdwhile the consumer uses another name, they are not working with the same queue. - Changing queue properties: Declaring an existing queue with different
durableorexclusivesettings can cause a channel-level error. - Assuming a message disappeared because the consumer was offline: If the queue exists and the message was accepted, it can remain there until a consumer arrives.
- Using automatic acknowledgement: With
autoAck: true, RabbitMQ considers the message complete as soon as it delivers it. If the application crashes during processing, the message may be lost. - Treating the body as a string: RabbitMQ message bodies are byte arrays. The producer and consumer must use a compatible encoding.
- Using one channel for unlimited concurrent work: Channel lifetime and callback usage must be managed carefully. Heavy workloads require controlled concurrency and an appropriate prefetch value.
- Hard-coding credentials: Credentials are hard-coded here for simplicity. Real applications should use configuration, environment variables, or a secret store.
Short practice exercise
Implement the following improvements:
- Add a
ProductCountproperty toOrderCreatedMessage. - Make the producer read the customer email and total amount from command-line arguments.
- Add a two-second artificial delay while the consumer processes a message.
- Open two consumer terminals and run the producer at least six times. Observe that messages are shared between workers.
- Intentionally create invalid JSON and inspect what happens after
BasicNackAsyncis called.
Conclusion
In this lesson, we built a complete basic RabbitMQ message flow. The producer opened a connection, declared a queue, serialized an object to JSON, and published it. The consumer declared the same queue, received messages asynchronously, converted the JSON back into an object, and sent an acknowledgement after successful processing.
This basic flow will be extended in later lessons with exchanges and routing keys. We will also cover publisher confirms, retries, dead-letter queues, idempotency, and real integration with ASP.NET Core services. The key idea for now is that the API can publish a message instead of performing the work directly, while an independent consumer performs that work later.