Skip to content

Step 05 — Consume events in a worker ​

What you'll do: create a Shipping worker service with its own queue that receives OrderPlaced messages and acknowledges each one by hand.

Steps ​

  1. Create the worker and reference the contracts:

    bash
    dotnet new worker -o src/Shipping.Worker -n Shipping.Worker
    dotnet sln OutboxInbox.slnx add src/Shipping.Worker/Shipping.Worker.csproj
    dotnet add src/Shipping.Worker reference src/Orders.Contracts

    The template writes a Version on its package reference, which central package management does not allow (NU1008). Move the versions into Directory.Packages.props:

    xml
    <PackageVersion Include="Microsoft.Extensions.Hosting" Version="10.0.15" />
    <PackageVersion Include="Microsoft.Extensions.Options.DataAnnotations" Version="10.0.15" />

    and make Shipping.Worker.csproj list only names:

    xml
    <ItemGroup>
      <PackageReference Include="Microsoft.Extensions.Hosting" />
      <PackageReference Include="Microsoft.Extensions.Options.DataAnnotations" />
      <PackageReference Include="RabbitMQ.Client" />
    </ItemGroup>
    
    <ItemGroup>
      <ProjectReference Include="..\Orders.Contracts\Orders.Contracts.csproj" />
    </ItemGroup>

    A worker is not a web app, so ValidateDataAnnotations() needs its own package here (ASP.NET Core includes it). Rename the template's Worker.cs to OrderPlacedConsumer.cs; you replace its contents below.

  2. Add RabbitMqOptions.cs for the worker. It has the same connection settings as the API, plus the queue name and prefetch count. Put the settings in appsettings.json and the guest login in appsettings.Development.json:

    json
    "RabbitMq": {
      "HostName": "localhost",
      "Port": 5672,
      "VirtualHost": "/",
      "Exchange": "orders",
      "Queue": "shipping.order-placed",
      "PrefetchCount": 10
    }
  3. Write the consumer, OrderPlacedConsumer.cs. It declares its queue, binds it to the orders exchange and starts consuming:

    csharp
    await channel.ExchangeDeclareAsync(settings.Exchange, ExchangeType.Topic, durable: true, cancellationToken: stoppingToken);
    await channel.QueueDeclareAsync(
        settings.Queue,
        durable: true,
        exclusive: false,
        autoDelete: false,
        arguments: new Dictionary<string, object?> { ["x-queue-type"] = "quorum" },
        cancellationToken: stoppingToken);
    await channel.QueueBindAsync(settings.Queue, settings.Exchange, OrderPlaced.MessageType, cancellationToken: stoppingToken);
    await channel.BasicQosAsync(prefetchSize: 0, prefetchCount: settings.PrefetchCount, global: false, stoppingToken);
    
    var consumer = new AsyncEventingBasicConsumer(channel);
    consumer.ReceivedAsync += (_, delivery) => HandleAsync(channel, delivery, stoppingToken);
    await channel.BasicConsumeAsync(settings.Queue, autoAck: false, consumer, stoppingToken);

    Each message is read, logged and then acknowledged. A body that is not valid OrderPlaced JSON is rejected without requeueing:

    csharp
    var message = TryDeserialize(delivery.Body);
    if (message is null)
    {
        logger.LogWarning("Rejected unreadable message {MessageId}", delivery.BasicProperties.MessageId);
        await channel.BasicNackAsync(delivery.DeliveryTag, multiple: false, requeue: false, ct);
        return;
    }
    
    logger.LogInformation(
        "Received order {OrderId} (message {MessageId}, redelivered: {Redelivered}) with {LineCount} lines",
        message.OrderId, delivery.BasicProperties.MessageId, delivery.Redelivered, message.Lines.Count);
    
    await channel.BasicAckAsync(delivery.DeliveryTag, multiple: false, ct);

    TryDeserialize reads the body with JsonSerializerOptions.Web plus two strict settings:

    csharp
    private static readonly JsonSerializerOptions StrictJson = new(JsonSerializerOptions.Web)
    {
        RespectNullableAnnotations = true,
        RespectRequiredConstructorParameters = true,
    };

    Without them, {} would deserialize into an OrderPlaced whose Lines is null, and the code would crash later instead of rejecting the message here.

  4. Register it in Program.cs:

    csharp
    builder.Services.AddOptions<RabbitMqOptions>()
        .BindConfiguration(RabbitMqOptions.SectionName)
        .ValidateDataAnnotations()
        .ValidateOnStart();
    
    builder.Services.AddHostedService<OrderPlacedConsumer>();

Check it works ​

Build, then start both apps in two terminals:

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

Place an order with the usual curl -X POST localhost:5080/orders ... command. The worker logs:

info: Shipping.Worker.OrderPlacedConsumer[0]
      Consuming shipping.order-placed
info: Shipping.Worker.OrderPlacedConsumer[0]
      Received order 01a21a8d-0437-7cc9-ab86-9b884ff991a0 (message 01a21a8d-0459-78d0-90fc-5f4ec06c614f, redelivered: False) with 1 lines

Now send a message that is not JSON, straight to the exchange:

bash
curl -u guest:guest -X POST localhost:15672/api/exchanges/%2F/orders/publish \
  -H 'content-type: application/json' \
  -d '{"properties":{"message_id":"bad-1"},"routing_key":"orders.order-placed.v1","payload":"not json","payload_encoding":"string"}'
warn: Shipping.Worker.OrderPlacedConsumer[0]
      Rejected unreadable message bad-1

In the management UI, Queues and Streams shows shipping.order-placed with type quorum, one consumer and 0 messages waiting.

Try this (optional): stop the worker, place two orders, and look at the queue: the messages wait there (Ready: 2). Start the worker again and it receives both.

Why it works ​

Each service owns its queue. The API publishes to an exchange and knows nothing about who listens. Shipping declares shipping.order-placed and binds it with the routing key orders.order-placed.v1. A future Billing service would bind its own queue and get its own copy of every event, without any change to the API.

Manual acks. With autoAck: false the broker keeps each delivered message until the consumer sends an ack (acknowledgement): "done, delete it". If the worker crashes or the connection drops before the ack, the broker delivers the message again, with Redelivered set to true. So the consumer acks after its work, never before. A nack ("negative ack") with requeue: false tells the broker to drop the message: retrying a message nobody can read only loops forever. Step 07 sends such messages somewhere you can inspect them instead.

Prefetch. BasicQosAsync(prefetchCount: 10) lets the broker push at most 10 unacknowledged messages to this consumer at once. Too high and one slow worker hoards messages that another instance could process; too low and the worker waits on the network between messages.

Quorum queue. x-queue-type: quorum creates a quorum queue, the queue type RabbitMQ recommends for data you care about. It keeps copies on several nodes in a cluster (here there is one node) and tracks how often each message has been redelivered.

What is still wrong. Because delivery is at-least-once, the same message can arrive twice: the publisher may resend after a crash, and the broker redelivers after a lost ack. Right now the worker would handle both copies. The next step fixes that.

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