Skip to content

Step 04 — Publish the outbox to RabbitMQ ​

What you'll do: add a background service that reads pending outbox rows and publishes them to a RabbitMQ exchange, marking each row processed only after the broker confirms it.

A few RabbitMQ words ​

TermMeaning
ExchangeWhere publishers send messages. It does not store them; it routes them to queues.
Topic exchangeRoutes by matching the message's routing key (orders.order-placed.v1) against patterns like orders.#.
QueueStores messages until a consumer takes them.
BindingA rule "this queue wants messages from this exchange whose key matches this pattern".
ChannelA light session inside one TCP connection. You publish and consume on channels.
Publisher confirmThe broker's "I have it" for each message, sent after the message is safely stored.

Steps ​

  1. Add the client library to Directory.Packages.props and Orders.Api.csproj:

    xml
    <PackageVersion Include="RabbitMQ.Client" Version="7.3.0" />
    xml
    <PackageReference Include="RabbitMQ.Client" />

    Version 7 is fully async: every call that talks to the broker is ...Async.

  2. Add two options classes with validation attributes. RabbitMqOptions.cs holds the broker address, credentials and exchange name; OutboxOptions.cs holds how often to poll and how many rows to take:

    csharp
    public sealed class OutboxOptions
    {
        public const string SectionName = "Outbox";
    
        [Range(typeof(TimeSpan), "00:00:00.100", "00:01:00")]
        public TimeSpan PollingInterval { get; init; } = TimeSpan.FromSeconds(1);
    
        [Range(1, 500)]
        public int BatchSize { get; init; } = 20;
    }
  3. Add the settings. appsettings.json has everything except credentials:

    json
    "RabbitMq": {
      "HostName": "localhost",
      "Port": 5672,
      "VirtualHost": "/",
      "Exchange": "orders"
    },
    "Outbox": {
      "PollingInterval": "00:00:01",
      "BatchSize": 20
    }

    appsettings.Development.json adds the container's default guest / guest login. On a real broker, create a user per service and keep its password in user secrets or Key Vault.

  4. Add RabbitMqConnection.cs: one connection per process, opened on first use and kept.

    csharp
    var factory = new ConnectionFactory
    {
        HostName = settings.HostName,
        Port = settings.Port,
        VirtualHost = settings.VirtualHost,
        UserName = settings.UserName,
        Password = settings.Password,
        ClientProvidedName = "Orders.Api",
    };
    _connection = await factory.CreateConnectionAsync(ct);
  5. Add the publisher, OutboxPublisher.cs. It is a BackgroundService that wakes up on a PeriodicTimer:

    csharp
    using var timer = new PeriodicTimer(outboxOptions.Value.PollingInterval, clock);
    while (await timer.WaitForNextTickAsync(stoppingToken))
    {
        try
        {
            await PublishPendingAsync(stoppingToken);
        }
        catch (Exception ex) when (!stoppingToken.IsCancellationRequested)
        {
            logger.LogWarning(ex, "Outbox publishing failed, retrying on the next tick");
        }
    }

    Each tick reads the oldest unprocessed rows, opens a channel with publisher confirms and publishes them one by one:

    csharp
    var batch = await db.OutboxMessages
        .Where(m => m.ProcessedAt == null)
        .OrderBy(m => m.OccurredAt)
        .Take(outboxOptions.Value.BatchSize)
        .ToListAsync(ct);
    
    await using var channel = await connection.CreateChannelAsync(
        new CreateChannelOptions(publisherConfirmationsEnabled: true, publisherConfirmationTrackingEnabled: true), ct);
    await channel.ExchangeDeclareAsync(exchange, ExchangeType.Topic, durable: true, cancellationToken: ct);
    
    foreach (var message in batch)
    {
        var properties = new BasicProperties
        {
            MessageId = message.Id.ToString(),
            Type = message.Type,
            ContentType = "application/json",
            DeliveryMode = DeliveryModes.Persistent,
            Timestamp = new AmqpTimestamp(message.OccurredAt.ToUnixTimeSeconds()),
        };
    
        try
        {
            await channel.BasicPublishAsync(exchange, message.Type, mandatory: true, properties, Encoding.UTF8.GetBytes(message.Payload), ct);
        }
        catch (PublishException ex)
        {
            logger.LogWarning(ex, "Broker did not accept outbox message {MessageId} ({MessageType})", message.Id, message.Type);
            break;
        }
    
        message.ProcessedAt = clock.GetUtcNow();
    }
    
    await db.SaveChangesAsync(CancellationToken.None);
  6. Register everything in Program.cs:

    csharp
    builder.Services.AddOptions<RabbitMqOptions>()
        .BindConfiguration(RabbitMqOptions.SectionName)
        .ValidateDataAnnotations()
        .ValidateOnStart();
    builder.Services.AddOptions<OutboxOptions>()
        .BindConfiguration(OutboxOptions.SectionName)
        .ValidateDataAnnotations()
        .ValidateOnStart();
    
    builder.Services.AddSingleton<RabbitMqConnection>();
    builder.Services.AddHostedService<OutboxPublisher>();

Check it works ​

bash
dotnet build OutboxInbox.slnx -warnaserror
dotnet run --project src/Orders.Api

There is no queue yet (the Shipping worker comes in the next step), so the broker has nowhere to put the message from step 03. Because the publisher sets mandatory: true, the broker hands it back instead of dropping it, and the row stays in the outbox. The log repeats once per second:

warn: Orders.Api.Outbox.OutboxPublisher[0]
      Broker did not accept outbox message 01a21a88-f915-7e89-be87-8e0b0a292305 (orders.order-placed.v1)
      RabbitMQ.Client.Exceptions.PublishReturnException: 312 NO_ROUTE Exchange: orders Routing Key: orders.order-placed.v1

Create a temporary queue named demo and bind it to the exchange, using the management HTTP API (or the Queues and Streams tab at http://localhost:15672):

bash
curl -u guest:guest -X PUT localhost:15672/api/queues/%2F/demo \
  -H 'content-type: application/json' -d '{"durable":true}'
curl -u guest:guest -X POST localhost:15672/api/bindings/%2F/e/orders/q/demo \
  -H 'content-type: application/json' -d '{"routing_key":"orders.#"}'

Within a second the API logs:

info: Orders.Api.Outbox.OutboxPublisher[0]
      Published outbox message 01a21a88-f915-7e89-be87-8e0b0a292305 (orders.order-placed.v1)

Place another order with the curl -X POST localhost:5080/orders ... command from step 03, then read the queue:

bash
curl -u guest:guest -X POST localhost:15672/api/queues/%2F/demo/get \
  -H 'content-type: application/json' -d '{"count":5,"ackmode":"ack_requeue_false","encoding":"auto"}'

Each message has the outbox row's id as message_id, the event type, and the JSON payload:

json
{
  "exchange": "orders",
  "routing_key": "orders.order-placed.v1",
  "properties": {
    "type": "orders.order-placed.v1",
    "message_id": "01a21a88-f915-7e89-be87-8e0b0a292305",
    "delivery_mode": 2,
    "content_type": "application/json"
  },
  "payload": "{\"lines\": [{\"sku\": \"BOOK-1\", \"quantity\": 2}, ...], \"orderId\": \"01a21a88-...\", ...}"
}

In the database every row now has a processed_at:

bash
docker compose exec postgres psql -U postgres -d orders -c "select id, processed_at from outbox_messages order by occurred_at"

Delete the demo queue when you are done:

bash
curl -u guest:guest -X DELETE localhost:15672/api/queues/%2F/demo

Why it works ​

Confirm, then mark. With publisherConfirmationTrackingEnabled: true, BasicPublishAsync waits for the broker's confirm. If the broker refuses (basic.nack) or returns the message, it throws a PublishException. Only after it returns does the code set ProcessedAt. If the process crashes after the publish but before SaveChangesAsync, the row is still unprocessed and will be sent again. This is at-least-once delivery: a message may arrive twice, but it is never lost. Step 06 makes the consumer handle the second copy.

mandatory: true. By default a broker silently drops a message that matches no binding, and still confirms it. With mandatory, it returns the message (312 NO_ROUTE) and the client throws PublishReturnException. A typo in a routing key then shows up in your logs instead of as lost events.

Persistent messages on a durable exchange. DeliveryModes.Persistent asks the broker to write the message to disk, so it survives a broker restart once it is in a durable queue.

Ordering. On a failure the loop stops (break) instead of skipping ahead, so events for the same order are never sent out of order. The next tick tries again from the same row.

Why a background service. The HTTP request never waits for the broker. If RabbitMQ is down, POST /orders still returns 201; the rows wait in the outbox. PeriodicTimer with the injected TimeProvider ticks at a fixed rate without overlapping runs.

Validated options. ValidateDataAnnotations() checks the [Required] and [Range] attributes, and ValidateOnStart() does it when the app starts. A missing password fails the start with a clear OptionsValidationException, instead of failing on the first publish minutes later.

MIT licensed. Every step is a commit: git checkout step-01.