Introduction
In the previous lesson, we built a basic RabbitMQ producer-consumer flow. A producer published a message, and a consumer received it from a queue. In real systems, however, we usually do not want producers to know the details of individual queues. The same event may need to reach several independent services, a message may need to be delivered to exactly one worker group, or different message categories may need to be routed to different consumers.
This is where exchanges, queue bindings, and routing keys become important. A producer normally publishes to an exchange rather than directly to a queue. The exchange evaluates the message routing key and its binding rules, then routes the message to one or more queues.
In this lesson, we will separate email, notification, and report processing in our sample application. We will use a direct exchange for selective routing, a fanout exchange for broadcasting, and a topic exchange for pattern-based routing.
1. Understanding RabbitMQ Topology
RabbitMQ topology defines the path a message follows inside the broker. Its main parts are:
- Exchange: Receives published messages and routes them.
- Queue: Stores messages until consumers receive them.
- Binding: A routing rule connecting an exchange to a queue.
- Routing key: A text value used by an exchange to evaluate routing rules.
- Consumer group: Multiple consumer instances sharing one queue. A message is delivered to only one consumer on that queue.
An exchange does not store messages by itself. When an exchange is created, it is simply a named routing point with no queue relationships. Queues must be bound to the exchange before messages can reach consumers.
Example topology
Let us publish application events through an exchange named app.events:
| Queue | Binding key | Purpose |
|---|---|---|
email-worker | email | Send email |
notification-worker | notification | Send notifications |
report-worker | report | Generate reports |
When this topology uses a direct exchange, a message with the email routing key goes only to email-worker, while a message with the report routing key goes only to report-worker.
2. Selective Routing with a Direct Exchange
A direct exchange compares the message routing key with the queue binding key. If the values are exactly equal, the message is routed to that queue. If several queues use the same binding key, all of them receive a copy.
Direct exchanges are useful when work categories are clearly defined, such as email, SMS, and report processing.
Declaring the topology in code
The following service creates the exchange, queues, and bindings when the application starts. Declarations are intended to be idempotent, so the same topology can safely be declared again when a service reconnects or restarts.
using RabbitMQ.Client;
public sealed class RabbitTopology
{
public const string ExchangeName = "app.events";
public static async Task ConfigureAsync(IChannel channel)
{
await channel.ExchangeDeclareAsync(
exchange: ExchangeName,
type: ExchangeType.Direct,
durable: true,
autoDelete: false);
await channel.QueueDeclareAsync(
queue: "email-worker",
durable: true,
exclusive: false,
autoDelete: false);
await channel.QueueDeclareAsync(
queue: "notification-worker",
durable: true,
exclusive: false,
autoDelete: false);
await channel.QueueDeclareAsync(
queue: "report-worker",
durable: true,
exclusive: false,
autoDelete: false);
await channel.QueueBindAsync(
"email-worker", ExchangeName, "email");
await channel.QueueBindAsync(
"notification-worker", ExchangeName, "notification");
await channel.QueueBindAsync(
"report-worker", ExchangeName, "report");
}
}The exchange and queues are declared with durable: true. This helps them survive a broker restart. However, a durable queue does not automatically make every message persistent. The publisher must also publish persistent messages.
Publishing with a routing key
public async Task PublishAsync(
IChannel channel,
string routingKey,
string payload,
CancellationToken cancellationToken)
{
var body = Encoding.UTF8.GetBytes(payload);
var properties = new BasicProperties
{
Persistent = true,
ContentType = "application/json"
};
await channel.BasicPublishAsync(
exchange: RabbitTopology.ExchangeName,
routingKey: routingKey,
mandatory: true,
basicProperties: properties,
body: body,
cancellationToken: cancellationToken);
}A call such as PublishAsync(channel, "email", payload, token) targets only the email-worker queue. If the producer uses a routing key such as unknown and no binding matches it, the message may not reach any queue. Production systems should monitor this with publisher confirms, mandatory publishing, or an alternate exchange.
3. Broadcasting with a Fanout Exchange
A fanout exchange ignores the routing key. Every queue bound to the exchange receives a copy of each message. This model is useful when the same event must be processed independently by multiple services.
For example, when an order is created, a notification service may notify the customer, a reporting service may update statistics, and an audit service may record the event. Each service should have its own queue.
await channel.ExchangeDeclareAsync(
"order.events",
ExchangeType.Fanout,
durable: true,
autoDelete: false);
await channel.QueueDeclareAsync("notification-events", true, false, false);
await channel.QueueDeclareAsync("report-events", true, false, false);
await channel.QueueDeclareAsync("audit-events", true, false, false);
await channel.QueueBindAsync("notification-events", "order.events", "");
await channel.QueueBindAsync("report-events", "order.events", "");
await channel.QueueBindAsync("audit-events", "order.events", "");Even if a routing key is supplied to a fanout exchange, it does not affect routing. Each queue acts as an independent consumer group. Multiple consumers on the same queue share the workload, while different queues receive separate copies of the event.
4. Topic Exchanges and Pattern-Based Routing
A topic exchange splits the routing key into segments separated by periods. In a binding pattern, * matches exactly one segment, while # matches zero or more segments.
For example:
order.*matchesorder.created, but notorder.created.eu.order.#can matchorder,order.created, andorder.created.eu.*.createdmatchesorder.createdanduser.created.
Topic exchanges are useful when the routing key contains not only the event name, but also information such as region, severity, or source.
await channel.ExchangeDeclareAsync(
"business.events",
ExchangeType.Topic,
durable: true,
autoDelete: false);
await channel.QueueDeclareAsync("all-orders", true, false, false);
await channel.QueueDeclareAsync("eu-critical-orders", true, false, false);
await channel.QueueDeclareAsync("user-events", true, false, false);
await channel.QueueBindAsync("all-orders", "business.events", "order.#");
await channel.QueueBindAsync("eu-critical-orders", "business.events", "order.eu.critical");
await channel.QueueBindAsync("user-events", "business.events", "user.*");With this topology, order.eu.critical is delivered to both all-orders and eu-critical-orders. A user.created message is delivered to user-events. Topic exchanges become powerful as routing requirements grow, but the routing-key convention should be designed carefully from the beginning.
5. Consumer Groups and Queue Design
Consumer instances that read from the same queue form a consumer group. RabbitMQ delivers a message to only one of the consumers on that queue. Therefore, running multiple worker instances against one queue is a straightforward way to scale processing horizontally.
For example, three email-worker instances sharing one queue can distribute email jobs among themselves. Email and report services should not normally share a queue, because they have different responsibilities, message contracts, and failure policies.
A useful rule is to create a separate queue for every independent work type or consumer group. The exchange determines which services receive an event, while the queue allows each service to control its own processing capacity, acknowledgement behavior, and retry strategy.
6. Preparing Topology in ASP.NET Core
It is safer to centralize topology creation instead of scattering exchange, queue, and binding declarations across producers and consumers. After a RabbitMQ connection is opened, the exchange, queues, and bindings can be declared on the same channel.
builder.Services.AddSingleton<RabbitConnection>();
builder.Services.AddHostedService<EmailConsumer>();
builder.Services.AddHostedService<NotificationConsumer>();
public sealed class EmailConsumer : BackgroundService
{
private readonly RabbitConnection _connection;
public EmailConsumer(RabbitConnection connection)
{
_connection = connection;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await using var channel = await _connection.CreateChannelAsync();
await RabbitTopology.ConfigureAsync(channel);
var consumer = new AsyncEventingBasicConsumer(channel);
consumer.ReceivedAsync += async (_, eventArgs) =>
{
var json = Encoding.UTF8.GetString(eventArgs.Body.ToArray());
Console.WriteLine($"Email event: {json}");
await channel.BasicAckAsync(eventArgs.DeliveryTag, false);
};
await channel.BasicConsumeAsync(
queue: "email-worker",
autoAck: false,
consumer: consumer);
await Task.Delay(Timeout.Infinite, stoppingToken);
}
}If the consumer uses a database context or another scoped dependency, create an appropriate dependency-injection scope for each message or processing unit. Acknowledgement should be sent only after successful processing. Although this lesson focuses on routing, topology, acknowledgement, and retry policies must be designed together.
7. Common Mistakes
- Using queues directly instead of exchanges: This may work in a small demo but reduces routing flexibility later.
- Relying on routing keys with fanout: Fanout ignores routing keys. Use direct or topic exchanges for selective routing.
- Using the wrong topic pattern:
*matches one segment, while#matches multiple segments. - Using one queue for every consumer: Messages are then shared among services instead of being copied to each service.
- Managing topology only by hand: Changes in the management interface can make environments inconsistent with source code.
- Changing declaration properties without migration: Redeclaring an existing exchange or queue with incompatible properties can cause a broker error. Use a new name or a controlled migration.
- Ignoring unroutable messages: Messages that match no binding can disappear from the expected processing path. Add publisher confirmation and monitoring.
8. Short Practice Exercise
Complete the following exercise:
- Create a durable direct exchange named
app.events. - Create
email-worker,notification-worker, andreport-workerqueues. - Bind each queue to the exchange with its own routing key.
- Publish three messages and verify that each message reaches the correct queue.
- Create a topic exchange named
business.events. - Create a queue with the
audit.#binding and publish messages such asaudit.user.createdandaudit.order.paid. - Test the difference between
audit.*andaudit.#using messages with different numbers of segments.
Conclusion
An exchange is RabbitMQ’s routing layer between producers and queues. A direct exchange provides exact matching, a fanout exchange broadcasts messages, and a topic exchange provides pattern-based routing. With carefully designed bindings, email, notification, and report processing can be separated, and each consumer group can scale independently.
In the next stage, we will add acknowledgements, retries, dead-letter queues, and reliable failure handling to this topology. The goal is to build not only a system that routes messages correctly, but also one that handles failed messages in a controlled and observable way.