Your First C# Producer & Consumer with RabbitMQ.Client
Quick Answer: Install the RabbitMQ.Client NuGet package to connect C# apps to RabbitMQ. Open one IConnection and one IChannel, declare a queue, and send UTF-8 JSON bytes with BasicPublishAsync. A separate C# worker reads those bytes using AsyncEventingBasicConsumer without slowing down your main app.
Imagine Priya runs a food delivery app in Bengaluru. At 8:00 PM on Friday, 2,000 hungry customers tap Place Order at the same time.
Ravi orders a Masala Dosa and waits for the confirmation screen. If Priya's Order API waits for the Email Service to send an email first, Ravi stares at a loading spinner.
How do we confirm Ravi's order in milliseconds and send the email safely in the background?
1. Why Do We Need a Producer and Consumer?
The problem without a message broker
In a basic setup, the Order API calls the Email Service directly over HTTP. The customer must wait until the email finishes sending.
Example 1: Blocking checkout call in C#
This simple setup works for 10 orders a minute, but fails during dinner rush.
// Order API waits for the email server before replying to Ravi
await SaveOrderToDbAsync(order);
await httpClient.PostAsJsonAsync("https://email-service/send", order); // Takes 2,500 ms
return Results.Ok("Order confirmed!");
Expected output
Order #ORD-1042 saved (15 ms) Waiting for Email Service... (2,500 ms) TimeoutException: Email Service is down! Checkout failed.
This setup works on a quiet afternoon. However, it breaks when real dinner traffic arrives.
- Every checkout slows down by 2 to 3 seconds while waiting for the email server.
- If the Email Service crashes, Ravi's food order fails even though payment succeeded.
- Traffic spikes pile up open HTTP connections and crash the Order API.
Now think about a rainy weekend in Bengaluru with 10,000 orders in five minutes. We need to separate order placement from email sending so each part runs at its own speed.
The solution: C# Producer and Consumer with RabbitMQ
Producer = a C# app that creates a message and sends it to RabbitMQ.
Queue = a safe waiting line inside RabbitMQ that holds messages until a worker reads them.
Consumer = a background C# app that reads messages from the queue and does the slow work.
We update Priya's Order API to drop a small JSON message into RabbitMQ and reply to Ravi immediately. A separate Email Worker reads that message and sends the email.
Live Flow: Priya's Food Delivery Order Notification
Ravi's order is confirmed fast while RabbitMQ delivers the JSON message to the Email Worker.
Each message travels as raw UTF-8 JSON bytes from the C# Producer into the order-notifications queue, where the Consumer picks it up asynchronously.
2. Build Your First Producer and Consumer in C#
Connection = a single TCP network link between your C# app and the RabbitMQ broker.
Channel = a lightweight virtual path inside that connection where you actually publish or consume messages.
First, make sure your local RabbitMQ Docker container is running. Then install the official NuGet package in both your Producer and Consumer .NET console projects.
Step 1: Install RabbitMQ.Client
Run this command in your terminal to add the modern async RabbitMQ client.
dotnet add package RabbitMQ.Client
Example 2: C# Producer (Producer.cs)
This code connects to localhost, declares the order-notifications queue, and publishes Ravi's order as JSON.
using System.Text;
using System.Text.Json;
using RabbitMQ.Client;
var factory = new ConnectionFactory { HostName = "localhost" };
await using var connection = await factory.CreateConnectionAsync();
await using var channel = await connection.CreateChannelAsync();
await channel.QueueDeclareAsync(
queue: "order-notifications",
durable: true,
exclusive: false,
autoDelete: false);
var order = new { OrderId = "ORD-1042", Customer = "Ravi", Item = "Masala Dosa", City = "Bengaluru" };
var body = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(order));
await channel.BasicPublishAsync(
exchange: string.Empty,
routingKey: "order-notifications",
body: body);
Console.WriteLine("Published order ORD-1042 for Ravi.");
Expected output
Published order ORD-1042 for Ravi.
We pass string.Empty as the exchange. This tells RabbitMQ to use the default exchange and route directly to the queue matching routingKey.
Now let us build the Consumer that listens to the same queue and reads the JSON payload.
Example 3: C# Consumer (Consumer.cs)
This worker registers an event handler that fires whenever a new message arrives.
using System.Text;
using System.Text.Json;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
var factory = new ConnectionFactory { HostName = "localhost" };
await using var connection = await factory.CreateConnectionAsync();
await using var channel = await connection.CreateChannelAsync();
await channel.QueueDeclareAsync(
queue: "order-notifications",
durable: true,
exclusive: false,
autoDelete: false);
var consumer = new AsyncEventingBasicConsumer(channel);
consumer.ReceivedAsync += async (sender, ea) =>
{
var json = Encoding.UTF8.GetString(ea.Body.ToArray());
Console.WriteLine($"Sending email for: {json}");
await Task.CompletedTask;
};
await channel.BasicConsumeAsync(
queue: "order-notifications",
autoAck: true,
consumer: consumer);
Console.WriteLine("Waiting for orders. Press Enter to exit.");
Console.ReadLine();
Expected output
Waiting for orders. Press Enter to exit.
Sending email for: {"OrderId":"ORD-1042","Customer":"Ravi","Item":"Masala Dosa","City":"Bengaluru"}
Notice that both apps call QueueDeclareAsync with the exact same settings. This is safe because RabbitMQ only creates the queue if it does not already exist.
| Without RabbitMQ (Direct HTTP) | With RabbitMQ (Producer & Consumer) |
|---|---|
| Ravi waits 2.5 seconds for the email server. | Ravi gets an order confirmation in 15 ms. |
| Email crash breaks the entire checkout. | Orders stay safe in the queue until Email recovers. |
| Order API and Email Service are tightly coupled. | Each C# service scales and deploys independently. |
The important terms to remember
- ConnectionFactory = the configuration object that holds your RabbitMQ host, port, and credentials.
- QueueDeclareAsync = an idempotent command that ensures a queue exists before you use it.
- BasicPublishAsync = sends raw byte arrays (such as UTF-8 JSON) to an exchange.
- AsyncEventingBasicConsumer = a push-based C# listener that triggers
ReceivedAsyncwhen messages arrive.
3. Common Mistakes to Avoid
1. Opening a new connection for every message
Creating a TCP connection takes time and uses up OS sockets quickly. Under heavy load, your .NET app will crash with socket exhaustion.
Better approach: Reuse one long-lived IConnection per application and open lightweight channels as needed.
2. Using autoAck: true in production
With autoAck: true, RabbitMQ deletes the message the instant it leaves the broker. If your Email Worker crashes halfway through sending, Ravi never gets his email.
Better approach: Use manual acknowledgments (autoAck: false) so RabbitMQ only removes the message after your code finishes safely.
4. Next Steps
Previous Article: Running RabbitMQ Locally with Docker & Management UI
Next Article: Connection & Channel Lifecycle Management in .NET – Learn why IConnection should be a singleton and how to manage IChannel instances safely in ASP.NET Core.
Discussion & Comments
0No comments yet
Start the discussion above — ask a question, share a tip, or reply to a comment.