Introduction
In the previous lesson, we examined service health and the basic observability capabilities available through the Aspire Dashboard. In this lesson, we will add asynchronous messaging alongside direct HTTP communication. When an order is created, the Order service will publish an event without waiting for the Inventory service to respond. The Inventory service will consume that event, reserve stock, and publish an InventoryReserved event.
This approach reduces temporal coupling between services. The publisher does not need to know where the consumer runs, how quickly it will respond, or how many instances are currently active. However, asynchronous communication introduces important design decisions: who owns the message contract, when is an event published, what happens when a message is delivered twice, which queue belongs to which consumer group, and how are failed messages inspected?
RabbitMQ messaging model
RabbitMQ is a message broker. A producer does not send a message directly to a service. Instead, it publishes the message to an exchange. The exchange routes the message to one or more queues according to bindings and routing keys. A consumer receives messages from a queue.
| Concept | Representation in this project |
|---|---|
| Publisher | Order Service |
| Event | OrderCreated or InventoryReserved |
| Exchange | orders.events |
| Queue | inventory.order-created |
| Consumer | Inventory Service |
| Routing key | order.created or inventory.reserved |
This lesson uses a topic exchange. Later, the order.created event can be connected to both Notification and Inventory queues. If consumers share one queue, they distribute work across instances. If each consumer has its own queue, every consumer receives its own copy of the event.
Adding RabbitMQ to the Aspire AppHost
Rather than maintaining a separate Docker Compose definition, we will model RabbitMQ as a first-class AppHost resource. The resource is named messaging; this name is also used as the connection-string key inside consuming services.
var builder = DistributedApplication.CreateBuilder(args);
var rabbitMq = builder.AddRabbitMQ("messaging")
.WithManagementPlugin();
var orderService = builder.AddProject<Projects.OrderService>("orders")
.WithReference(rabbitMq);
var inventoryService = builder.AddProject<Projects.InventoryService>("inventory")
.WithReference(rabbitMq);
builder.Build().Run();The WithReference calls make the RabbitMQ connection information available to the selected services. Aspire supplies the connection values through the service environment, so application code does not need hard-coded host names, ports, or development credentials. The management plugin is useful during local development because it provides a convenient way to inspect exchanges, queues, connections, and message flow.
Add the RabbitMQ client package to both consuming projects:
dotnet add package RabbitMQ.ClientThe application will read the connection string from ConnectionStrings:messaging. A local development connection may be placed in appsettings.Development.json when Aspire is not running, but real credentials must never be committed to source control.
Designing the message contract
A message contract is the agreement between a publisher and a consumer. It is not an Entity Framework Core entity. The contract should contain information required by consumers without exposing internal persistence details.
namespace BuildingBlocks.Messaging;
public sealed record OrderCreated(
Guid EventId,
Guid OrderId,
Guid CustomerId,
IReadOnlyList<OrderLine> Lines,
DateTimeOffset OccurredAt,
int Version = 1);
public sealed record OrderLine(
Guid ProductId,
int Quantity);
public sealed record InventoryReserved(
Guid EventId,
Guid OrderId,
DateTimeOffset OccurredAt,
int Version = 1);EventId helps identify duplicate deliveries. OrderId is the business key and can be stored in an idempotency record. The Version field gives the contract room to evolve. Use UTC-based DateTimeOffset values rather than local machine time.
An event name should describe something that has already happened. CreateOrderCommand is a command, while OrderCreated is an event. A command normally targets one handler; an event may have multiple subscribers.
Shared RabbitMQ infrastructure
A small helper can ensure that the publisher and consumer interpret the connection settings consistently.
using RabbitMQ.Client;
public sealed class RabbitMqConnection : IAsyncDisposable
{
private readonly IConnection connection;
private RabbitMqConnection(IConnection connection)
=> this.connection = connection;
public static async Task<RabbitMqConnection> CreateAsync(
string connectionString,
CancellationToken cancellationToken = default)
{
var factory = new ConnectionFactory
{
Uri = new Uri(connectionString),
AutomaticRecoveryEnabled = true,
NetworkRecoveryInterval = TimeSpan.FromSeconds(5)
};
var connection = await factory.CreateConnectionAsync(cancellationToken);
return new RabbitMqConnection(connection);
}
public Task<IChannel> CreateChannelAsync(CancellationToken cancellationToken = default)
=> connection.CreateChannelAsync(cancellationToken: cancellationToken);
public ValueTask DisposeAsync() => connection.DisposeAsync();
}Production systems should also address publisher confirms, TLS, credentials, secret management, initial connection retries, and shutdown behavior. Automatic connection recovery can help after a network interruption, but it does not prove that a message published during the interruption reached the broker. Important events require publisher confirms and an application-level republishing strategy.
Publishing OrderCreated
The Order service should save the order in its own database and then publish the event. The following example focuses on the RabbitMQ publishing operation:
using System.Text.Json;
using RabbitMQ.Client;
public sealed class OrderEventPublisher
{
private const string Exchange = "orders.events";
private readonly IChannel channel;
public OrderEventPublisher(IChannel channel) => this.channel = channel;
public async Task PublishAsync(OrderCreated message)
{
await channel.ExchangeDeclareAsync(
Exchange, ExchangeType.Topic, durable: true, autoDelete: false);
var properties = new BasicProperties
{
ContentType = "application/json",
ContentEncoding = "utf-8",
MessageId = message.EventId.ToString(),
Type = nameof(OrderCreated),
DeliveryMode = DeliveryModes.Persistent
};
var body = JsonSerializer.SerializeToUtf8Bytes(message);
await channel.BasicPublishAsync(
exchange: Exchange,
routingKey: "order.created",
mandatory: true,
basicProperties: properties,
body: body);
}
}The exchange and message are declared as durable or persistent. Persistence alone is not a complete delivery guarantee. Broker policies, disk availability, queue durability, publisher confirms, and consumer acknowledgments must be considered together.
Inventory consumer and queue binding
The Inventory service declares its own queue and binds it only to the order.created routing key.
using System.Text.Json;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
public sealed class OrderCreatedConsumer : BackgroundService
{
private const string Exchange = "orders.events";
private const string Queue = "inventory.order-created";
private readonly IConnection connection;
private readonly ILogger<OrderCreatedConsumer> logger;
public OrderCreatedConsumer(IConnection connection, ILogger<OrderCreatedConsumer> logger)
{
this.connection = connection;
this.logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await using var channel = await connection.CreateChannelAsync();
await channel.ExchangeDeclareAsync(Exchange, ExchangeType.Topic, durable: true);
await channel.QueueDeclareAsync(Queue, durable: true, exclusive: false, autoDelete: false);
await channel.QueueBindAsync(Queue, Exchange, "order.created");
await channel.BasicQosAsync(0, prefetchCount: 10, global: false);
var consumer = new AsyncEventingBasicConsumer(channel);
consumer.ReceivedAsync += async (_, delivery) =>
{
var body = delivery.Body.ToArray();
var message = JsonSerializer.Deserialize<OrderCreated>(body);
if (message is null)
{
await channel.BasicNackAsync(delivery.DeliveryTag, false, requeue: false);
return;
}
try
{
logger.LogInformation("Received OrderCreated: {OrderId}", message.OrderId);
// Reserve stock and perform the idempotency check here.
await channel.BasicAckAsync(delivery.DeliveryTag, multiple: false);
}
catch (Exception exception)
{
logger.LogError(exception, "Message processing failed: {EventId}", message.EventId);
await channel.BasicNackAsync(delivery.DeliveryTag, false, requeue: true);
}
};
await channel.BasicConsumeAsync(Queue, autoAck: false, consumer);
await Task.Delay(Timeout.Infinite, stoppingToken);
}
}With autoAck: false, the consumer acknowledges the message only after successful processing. If processing fails, the message can be requeued. Messages that fail permanently should not be requeued forever; add a retry limit and a dead-letter queue for poison messages.
Publishing order and the Outbox pattern
A common failure is treating the database write and message publication as two unrelated operations. If the Order service commits the order and crashes before publishing, Inventory never receives the event. If the message is published and the database transaction later rolls back, the consumer may process an order that does not exist.
The Transactional Outbox pattern addresses this problem. The Order service writes both the order and an outbox record in the same database transaction. A background worker reads pending outbox rows and publishes them to RabbitMQ. After a publisher confirm is received, the row is marked as sent. If the application restarts, unsent rows can be retried.
The Outbox pattern does not eliminate duplicate delivery. The consumer still needs idempotent processing using EventId or an appropriate business key. If the same OrderCreated event arrives twice, inventory must not be reduced twice.
Common mistakes
- Confusing exchanges and queues: Publishers should focus on the exchange and routing key rather than knowing consumer queue names.
- Opening a connection for every message: Reuse long-lived connections and appropriately scoped channels.
- Using automatic acknowledgment: A message may be lost if the process stops before processing completes.
- Assuming a shared queue broadcasts messages: Consumers on one queue share work. Use a separate queue for every service that must receive its own copy.
- Publishing database entities as contracts: Use small, stable DTOs that are independent of persistence.
- Retrying forever: A poison message can create an infinite loop. Add retry limits, dead-lettering, and monitoring.
- Relying only on logs: Acknowledgments, idempotency records, and business outcomes should be designed together.
Practice exercise
- Add a RabbitMQ resource named
messagingand enable the management plugin in the AppHost. - Connect the Order and Inventory services with
WithReference(rabbitMq). - Move the
OrderCreatedcontract into a shared BuildingBlocks project. - Declare the
orders.eventstopic exchange and publish using theorder.createdrouting key. - Create a durable Inventory queue and use manual acknowledgments.
- Publish the same event twice. Compare the result before and after adding an idempotency check.
- Throw an exception during inventory processing and inspect requeue behavior in the Dashboard and logs.
Conclusion
In this lesson, we added RabbitMQ to the Aspire application model and built asynchronous communication using exchanges, queues, bindings, and routing keys. The OrderCreated and InventoryReserved events allow publishers and consumers to evolve and operate independently.
Asynchronous messaging is not simply replacing HTTP with RabbitMQ. Durable message contracts, acknowledgments, idempotency, retries, dead-letter queues, publisher confirms, and the Outbox pattern must be considered together. In the next stages, we will connect this messaging foundation with resilience, distributed tracing, and more complete failure scenarios.
Sources
- https://learn.microsoft.com/en-us/dotnet/aspire/messaging/rabbitmq-integration
- https://learn.microsoft.com/en-us/dotnet/aspire/service-discovery/overview
- https://www.rabbitmq.com/tutorials/tutorial-one-dotnet
- https://www.rabbitmq.com/tutorials/tutorial-three-dotnet
- https://www.rabbitmq.com/client-libraries/dotnet-api-guide