Skip to content

Step 06 — Make the consumer idempotent with an inbox ​

What you'll do: record every handled message id in an inbox table, in the same transaction as the shipment it creates, so a message that arrives twice is handled once.

Why duplicates happen ​

The outbox gives at-least-once delivery. Copies of the same message are normal, not a bug:

WhereHow a second copy appears
PublisherThe broker confirmed, but the API stopped before saving processed_at. The row is sent again.
BrokerThe worker created the shipment but its connection dropped before the ack. The broker redelivers.
OperatorSomeone re-publishes a message from the management UI or a dead-letter queue.

A handler is idempotent when running it twice has the same effect as running it once. The inbox makes any handler idempotent: before doing the work, check a table of message ids already handled; after the work, add the id to that table, in the same transaction.

Steps ​

  1. Add EF Core to Shipping.Worker.csproj (the versions are already in Directory.Packages.props):

    xml
    <PackageReference Include="EFCore.NamingConventions" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design">
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" />
  2. Add the two entities. InboxMessage.cs:

    csharp
    public sealed class InboxMessage
    {
        public Guid MessageId { get; init; }
        public required string Type { get; init; }
        public DateTimeOffset ProcessedAt { get; init; }
    }

    and Shipment.cs, the work Shipping does for each order.

  3. Map them in ShippingDbContext.cs. The message id is the inbox's primary key, so the database itself refuses a second row for it:

    csharp
    modelBuilder.Entity<InboxMessage>(message =>
    {
        message.HasKey(m => m.MessageId);
        message.Property(m => m.Type).HasMaxLength(200);
    });
    
    modelBuilder.Entity<Shipment>(shipment =>
    {
        shipment.HasKey(s => s.Id);
        shipment.Property(s => s.CustomerEmail).HasMaxLength(254);
        shipment.HasIndex(s => s.OrderId).IsUnique();
    });
  4. Write the handler, OrderPlacedHandler.cs:

    csharp
    if (await db.InboxMessages.AnyAsync(m => m.MessageId == messageId, ct))
    {
        logger.LogInformation("Skipped duplicate message {MessageId} for order {OrderId}", messageId, message.OrderId);
        return;
    }
    
    var now = clock.GetUtcNow();
    db.InboxMessages.Add(new InboxMessage { MessageId = messageId, Type = OrderPlaced.MessageType, ProcessedAt = now });
    db.Shipments.Add(new Shipment
    {
        Id = Guid.CreateVersion7(),
        OrderId = message.OrderId,
        CustomerEmail = message.CustomerEmail,
        ItemCount = message.Lines.Sum(l => l.Quantity),
        CreatedAt = now,
    });
    
    try
    {
        await db.SaveChangesAsync(ct);
    }
    catch (DbUpdateException ex) when (ex.InnerException is PostgresException { SqlState: PostgresErrorCodes.UniqueViolation })
    {
        logger.LogInformation("Skipped duplicate message {MessageId} for order {OrderId}", messageId, message.OrderId);
        return;
    }
  5. Call it from OrderPlacedConsumer.cs. The consumer is a singleton, but a DbContext must live for one unit of work, so each message gets its own DI scope. The message id now must be a valid GUID:

    csharp
    if (!Guid.TryParse(delivery.BasicProperties.MessageId, out var messageId) || TryDeserialize(delivery.Body) is not { } message)
    {
        logger.LogWarning("Rejected unreadable message {MessageId}", delivery.BasicProperties.MessageId);
        await channel.BasicNackAsync(delivery.DeliveryTag, multiple: false, requeue: false, ct);
        return;
    }
    
    try
    {
        await using var scope = scopeFactory.CreateAsyncScope();
        await scope.ServiceProvider.GetRequiredService<OrderPlacedHandler>().HandleAsync(messageId, message, ct);
    }
    catch (Exception ex) when (!ct.IsCancellationRequested)
    {
        logger.LogError(ex, "Failed to handle message {MessageId}, requeueing it", messageId);
        await channel.BasicNackAsync(delivery.DeliveryTag, multiple: false, requeue: true, ct);
        return;
    }
    
    await channel.BasicAckAsync(delivery.DeliveryTag, multiple: false, ct);

    A duplicate is acked too: it was handled before, so the broker can forget it.

  6. Register the database and handler in Program.cs, and migrate in Development as the API does:

    csharp
    builder.Services.AddSingleton(TimeProvider.System);
    
    builder.Services.AddDbContext<ShippingDbContext>(options => options
        .UseNpgsql(builder.Configuration.GetConnectionString("Shipping")
            ?? throw new InvalidOperationException("Connection string 'Shipping' is missing."))
        .UseSnakeCaseNamingConvention());
    
    builder.Services.AddScoped<OrderPlacedHandler>();

    Add the connection string to appsettings.Development.json. It uses the shipping database, never orders:

    json
    "ConnectionStrings": {
      "Shipping": "Host=localhost;Port=5433;Database=shipping;Username=postgres;Password=postgres"
    }
  7. Create the migration:

    bash
    dotnet ef migrations add InitialCreate --project src/Shipping.Worker --output-dir Data/Migrations

Check it works ​

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

Place an order:

bash
curl -X POST localhost:5080/orders -H 'content-type: application/json' \
  -d '{"customerEmail":"alex@contoso.com","items":[{"sku":"BOOK-1","quantity":2},{"sku":"MUG-7","quantity":1}]}'
info: Shipping.Worker.Shipments.OrderPlacedHandler[0]
      Created shipment for order 01a21a8e-f0aa-7969-8d1a-ec27f9243883 from message 01a21a8e-f0ce-7448-85b9-be1df3a4c035

Now simulate the publisher crash from the table above: clear processed_at on that outbox row, so the publisher sends the same message again.

bash
docker compose exec postgres psql -U postgres -d orders -c \
  "update outbox_messages set processed_at = null where id = (select id from outbox_messages order by occurred_at desc limit 1)"

Within a second the worker receives the same message id a second time and skips it:

info: Shipping.Worker.OrderPlacedConsumer[0]
      Received order 01a21a8e-f0aa-7969-8d1a-ec27f9243883 (message 01a21a8e-f0ce-7448-85b9-be1df3a4c035, redelivered: False)
info: Shipping.Worker.Shipments.OrderPlacedHandler[0]
      Skipped duplicate message 01a21a8e-f0ce-7448-85b9-be1df3a4c035 for order 01a21a8e-f0aa-7969-8d1a-ec27f9243883

There is still one shipment and one inbox row:

bash
docker compose exec postgres psql -U postgres -d shipping \
  -c "select message_id, type from inbox_messages" -c "select order_id, item_count from shipments"
              message_id              |          type
--------------------------------------+------------------------
 01a21a8e-f0ce-7448-85b9-be1df3a4c035 | orders.order-placed.v1

               order_id               | item_count
--------------------------------------+------------
 01a21a8e-f0aa-7969-8d1a-ec27f9243883 |          3

You can also re-publish by hand (optional): in the management UI open the orders exchange, Publish message, routing key orders.order-placed.v1, property message_id set to an id from inbox_messages, and the original payload. The worker skips it the same way.

The first time the worker starts on an empty database, EF Core logs a fail for SELECT ... FROM "__EFMigrationsHistory" before Applying migration. That is expected: it checks for the history table before creating it.

Why it works ​

Effect and record in one transaction. The inbox row and the shipment are saved by one SaveChangesAsync, so they commit together. There is no moment where the shipment exists but the message is not recorded (that would allow a second shipment), or the message is recorded but the shipment is missing (that would lose it).

Two layers of protection. The AnyAsync check handles the usual case, a duplicate that arrives later, with a clear log line. If two copies are processed at the same moment (two worker instances, or a redelivery while the first is still running), both pass the check, but only one insert of the same primary key can commit. The other gets PostgreSQL error 23505 (unique_violation), which the handler treats as a duplicate.

Ack after commit. The ack is sent only after SaveChangesAsync returns. If the worker dies in between, the broker redelivers and the inbox recognises the message. The combination of at-least-once delivery and an idempotent consumer is often called effectively once: the message may arrive more than once, but its effect happens once.

Failures go back to the queue. An exception from the handler (for example, the database is down) nacks with requeue: true, so the message is tried again. If the error never goes away, the message loops forever. The next step fixes that with retries that give up and a dead-letter queue.

Alternatives. If the work itself is naturally idempotent (an upsert keyed by order id, or the unique index on shipments.order_id), you could skip the inbox. The inbox is the general solution: it works for any handler, and it records which messages a service has seen.

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