This blog post explores how to use the Dapr Outbox and MassTransit Outbox to keep a business change and its intent to publish an event together.

Saving an order and publishing its OrderPlaced event as separate operations leaves a gap: the order may be saved even if publishing fails, or the event may reach a consumer before the order commits. A transactional outbox addresses this by committing the business change and the publication intent in the same transaction, then delivering the event to the broker after the commit.

The demo app lets us place an order and track it through fulfilment, using either Dapr or MassTransit behind the same Web App. Dapr uses its transactional state API and outbox component configuration, while MassTransit uses its Entity Framework Core outbox. The Web app shows Saved ยท awaiting fulfilment once the order transaction commits and Fulfilled once the consumer persists its result, making the two stages visible as we explore delivery and recovery when a dependency is unavailable.

Aspire orchestrates the application in both modes, while Docker Compose manages the external dependencies: PostgreSQL, MySQL, RabbitMQ, and their management UIs.

Here's a glimpse of the demo web app, built up incrementally throughout this post.

The order flow in the Blazor app

Prerequisites

  • Docker Desktop - Docker Desktop provides the local container runtime used by the backing services and management UI.
  • .NET Aspire - Aspire composes, runs, and observes the local distributed application.
  • Dapr CLI - the CLI installs and initializes the local Dapr runtime, including Dapr Scheduler and Redis.

NOTE: The demo app uses containerised PostgreSQL, MySQL and RabbitMQ, each with a supported Management UI for exploring its data. Refer to the Local Infrastructure section for details.

Demo App

The demo app is based on the Aspire starter template, which includes a frontend (ASP.NET Core Blazor app), an ApiService (ASP.NET Core Minimal API), a ServiceDefaults project and an AppHost project.

dotnet new aspire-starter --output Aspire-Outbox

It has been extended to showcase the outbox pattern using both Dapr and MassTransit. I renamed the existing ApiService to OrderService, added a Minimal API project called FulfilmentService, and introduced a Contracts class library for shared types.

The solution structure should look similar to the one below.

Aspire Outbox solution structure

NOTE: The screenshot above shows two additional folders, dapr-outbox-diagnostics and docker. Later sections explain what each one contains and how to use it.

With the initial structure in place, let's move on to the AppHost.

App Host

Aspire's AppHost declares and runs the OrderService, FulfilmentService, and Blazor web app. It adds /health checks to both backend services and uses WithReference to supply their service discovery configuration to the Web app.

The Outbox:Mode setting selects Dapr or MassTransit and is passed to both backend services. In Dapr mode, the AppHost attaches a sidecar to each backend, sets its application ID, and supplies the component directory and tracing configuration. In MassTransit mode, it supplies the PostgreSQL order database, MySQL fulfilment database, and RabbitMQ, using the configured infrastructure credentials.

Docker Compose starts PostgreSQL, MySQL, RabbitMQ, and their management UIs before the AppHost runs. The AppHost registers pgAdmin, phpMyAdmin, and RabbitMQ Management as external services so their URLs appear in the Aspire dashboard.

In Dapr mode, Outbox:CaptureDiagnostics also adds the dapr-outbox-capture executable. It waits for the order service's health check to pass, which ensurs Dapr has initialized the state table before installing the audit trigger and starting the RabbitMQ trace. The sample enables this setting by default; set it to false to disable capture. The Dapr Outbox Diagnostics section explains its purpose.

Start by adding the CommunityToolkit.Aspire.Hosting.Dapr NuGet package to the AppHost project. It provides extension methods and resource definitions that let an Aspire AppHost to configure Dapr resources.

dotnet add package CommunityToolkit.Aspire.Hosting.Dapr

The AppHost structure should look similar to the one below.

AppHost project structure

The five Dapr components files below configure tracing, two state stores, RabbitMQ pub/sub, and inbound retry. Only the order state store enables outbox publishing; the fulfilment store saves the result after delivery.

components/dapr-tracing.yaml

apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
  name: tracing
spec:
  tracing:
    samplingRate: "1"

components/fulfilmentstatestore.yaml

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: fulfilmentstatestore
spec:
  type: state.mysql
  version: v1
  metadata:
    - name: connectionString
      value: "sample:SamplePassw0rd@tcp(127.0.0.1:53306)/"
    - name: schemaName
      value: "fulfilmentdb"
    - name: tableName
      value: "fulfilment_state"
scopes:
  - fulfilment-service

components/orderpubsub-resiliency.yaml

# Bound each Dapr delivery attempt; RabbitMQ requeues after this policy is exhausted.
apiVersion: dapr.io/v1alpha1
kind: Resiliency
metadata:
  name: orderpubsub-resiliency
spec:
  policies:
    retries:
      orderDeliveryRetry:
        policy: constant
        duration: 5s
        maxRetries: 12
  targets:
    components:
      orderpubsub:
        inbound:
          retry: orderDeliveryRetry
scopes:
  - fulfilment-service

components/orderpubsub.yaml

# RabbitMQ pub/sub shared by both services.
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: orderpubsub
spec:
  type: pubsub.rabbitmq
  version: v1
  metadata:
    - name: connectionString
      value: "amqp://sample:SamplePassw0rd@localhost:55672"
    - name: durable
      value: "true"
    - name: autoAck
      value: "false"
    - name: requeueInFailure
      value: "true"
    - name: deletedWhenUnused
      value: "false"
scopes:
  - order-service
  - fulfilment-service

components/orderstatestore.yaml

# Transactional state store with the Dapr outbox enabled.
# Saving state through the transaction API commits the order and an outbox marker atomically.
# Dapr publishes the event through the pub/sub component after that commit.
# Component connection settings match compose.yaml.
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: orderstatestore
spec:
  type: state.postgresql
  version: v2
  metadata:
    - name: connectionString
      value: "host=localhost user=sample password=SamplePassw0rd port=55432 connect_timeout=10 database=ordersdb"
    - name: outboxPublishPubsub # The pub/sub component name to use for publishing events.
      value: "orderpubsub" # This is the name of the pub/sub component defined in the same directory (orderpubsub.yaml).
    - name: outboxPublishTopic # The pub/sub topic to publish events to.
      value: "dapr.orders.order-placed" # The fulfilment service subscribes to this topic.
scopes:
  - order-service

AppHost.cs

using Aspire_Outbox.Contracts;
using CommunityToolkit.Aspire.Hosting.Dapr;
using Microsoft.Extensions.Configuration;
 
const int PostgresPort = 55432;
const int MySqlPort = 53306;
const int RabbitMqPort = 55672;
 
var builder = DistributedApplication.CreateBuilder(args);
builder.AddDapr();
var daprComponentsPath = Path.Combine(builder.Environment.ContentRootPath, "components");
var daprTracingConfigPath = Path.Combine(daprComponentsPath, "dapr-tracing.yaml");
 
// Management UIs run in Docker Compose and are linked from the Aspire dashboard.
AddManagementUi("pgadmin", "http://127.0.0.1:5050", "pgAdmin");
AddManagementUi("phpmyadmin", "http://127.0.0.1:5051", "phpMyAdmin");
AddManagementUi("rabbitmq-management", "http://127.0.0.1:55673", "RabbitMQ Management");
 
void AddManagementUi(string name, string url, string displayText)
{
    builder.AddExternalService(name, url)
        .WithAnnotation(new ResourceUrlAnnotation { Url = new Uri(url).ToString(), DisplayText = displayText },
            ResourceAnnotationMutationBehavior.Replace);
}
 
var infrastructure = builder.Configuration.GetRequiredSection("Infrastructure");
var infraUser = infrastructure["Username"]
    ?? throw new InvalidOperationException("Infrastructure:Username is required.");
var infraPassword = infrastructure["Password"]
    ?? throw new InvalidOperationException("Infrastructure:Password is required.");
 
// Outbox:Mode selects the implementation: "Dapr" or "MassTransit".
// Set it with a launch profile, the command line (--Outbox:Mode=MassTransit) or appsettings.json.
var modeValue = builder.Configuration.GetRequiredSection("Outbox:Mode").Value
    ?? throw new InvalidOperationException("Outbox:Mode is required.");
 
if (!Enum.TryParse<OutboxMode>(modeValue, ignoreCase: true, out var mode))
    throw new InvalidOperationException(
        $"Outbox:Mode must be one of: {string.Join(", ", Enum.GetNames<OutboxMode>())}.");
 
var rabbitMqConnectionString = $"amqp://{infraUser}:{infraPassword}@127.0.0.1:{RabbitMqPort}";
var orderService = builder.AddProject<Projects.Aspire_Outbox_OrderService>(ServiceNames.OrderService)
    .WithHttpHealthCheck("/health")
    .WithEnvironment("ConnectionStrings__rabbitmq", rabbitMqConnectionString)
    .WithEnvironment("Outbox__Mode", mode.ToString())
    .WithUrlForEndpoint("http", url =>
    {
        url.Url = "/";
        url.DisplayText = "Order service";
    });
 
var fulfilmentService = builder.AddProject<Projects.Aspire_Outbox_FulfilmentService>(ServiceNames.FulfilmentService)
    .WithHttpHealthCheck("/health")
    .WithEnvironment("Outbox__Mode", mode.ToString())
    .WithUrlForEndpoint("http", url =>
    {
        url.Url = "/";
        url.DisplayText = "Fulfilment service";
    });
 
if (mode == OutboxMode.Dapr)
{
    orderService.WithDaprSidecar(sidecar =>
    {
        sidecar.WithOptions(new DaprSidecarOptions
        {
            AppId = ServiceNames.OrderService,
            Config = daprTracingConfigPath,
            ResourcesPaths = [daprComponentsPath]
        });
    });
    fulfilmentService.WithDaprSidecar(sidecar =>
    {
        sidecar.WithOptions(new DaprSidecarOptions
        {
            AppId = ServiceNames.FulfilmentService,
            Config = daprTracingConfigPath,
            ResourcesPaths = [daprComponentsPath]
        });
    });
 
    if (builder.Configuration.GetValue<bool>("Outbox:CaptureDiagnostics"))
    {
        var repositoryRoot = Path.GetFullPath(Path.Combine(builder.Environment.ContentRootPath, ".."));
        // The order health check proves Dapr has initialized ordersdb.state before the audit trigger is installed.
        builder.AddExecutable("dapr-outbox-capture", "bash", repositoryRoot,
                Path.Combine(repositoryRoot, "dapr-outbox-diagnostics", "dapr-outbox-capture.sh"), "run")
            .WaitFor(orderService);
    }
}
else
{
    var mySqlConnectionString = $"Server=127.0.0.1;Port={MySqlPort};User ID={infraUser};Password={infraPassword};Database=fulfilment-masstransit;SslMode=Disabled";
    orderService
        .WithEnvironment("ConnectionStrings__orders-masstransit", PostgresConnectionString("orders-masstransit"));
    fulfilmentService
        .WithEnvironment("ConnectionStrings__rabbitmq", rabbitMqConnectionString)
        .WithEnvironment("ConnectionStrings__fulfilment-masstransit", mySqlConnectionString);
 
    string PostgresConnectionString(string database) =>
        $"Host=127.0.0.1;Port={PostgresPort};Username={infraUser};Password={infraPassword};Database={database};SSL Mode=Disable";
}
 
builder.AddProject<Projects.Aspire_Outbox_Web>("web")
    .WithExternalHttpEndpoints()
    .WithUrlForEndpoint("http", url =>
    {
        url.Url = "/";
        url.DisplayText = "Web app";
    })
    .WithReference(orderService)
    .WithReference(fulfilmentService);
 
builder.Build().Run();

Contracts

Both modes share request and response models, the OrderPlaced integration event, OrderStatus, mode information, and service and messaging names. These names cover services, state stores, pub/sub components, topics, exchanges, and queues. The order services validate a request, trim its text fields, calculate the total, and assign an ID. They return 201 Created only after the order transaction succeeds.

The contracts structure should look similar to the one below.

Shared contracts

The event carries the order ID and the values needed for fulfilment. That ID becomes the idempotency key in the Dapr fulfilment store and the unique order key in MassTransit mode.

Names.cs

namespace Aspire_Outbox.Contracts;
 
public static class ServiceNames
{
    public const string OrderService = "order-service";
    public const string FulfilmentService = "fulfilment-service";
}
 
public static class MessagingNames
{
    public const string DaprStateStore = "orderstatestore";
    public const string DaprFulfilmentStore = "fulfilmentstatestore";
    public const string DaprPubSub = "orderpubsub";
    public const string DaprOrderPlacedTopic = "dapr.orders.order-placed";
    // Generated by Dapr from namespace, app ID, and the publish topic.
    public const string DaprInternalOutboxTopic = "defaultorder-servicedapr.orders.order-placed.outbox";
    public const string DaprFulfilmentQueue = "dapr.fulfilment.order-placed.q";
    
    public const string MassTransitOrderPlacedExchange = "mt.orders.order-placed.e";
    public const string MassTransitFulfilmentExchange = "mt.fulfilment.order-placed.e";
    public const string MassTransitFulfilmentQueue = "mt.fulfilment.order-placed.q";
}

OrderModels.cs

using System.ComponentModel.DataAnnotations;
 
namespace Aspire_Outbox.Contracts;
 
public sealed record OrderPlaced(
    Guid OrderId,
    string CustomerName,
    string Sku,
    int Quantity,
    decimal TotalAmount,
    DateTimeOffset PlacedAt);
 
public sealed class PlaceOrderRequest
{
    [Required, StringLength(100)]
    public string CustomerName { get; set; } = "";
 
    [Required, StringLength(80)]
    public string Sku { get; set; } = "";
 
    [Range(1, 10000)]
    public int Quantity { get; set; } = 1;
 
    [Range(typeof(decimal), "0.01", "1000000")]
    public decimal UnitPrice { get; set; } = 25;
}
 
public enum OrderStatus
{
    Placed,
    Fulfilled
}
 
public sealed record OrderDto(
    Guid OrderId,
    string CustomerName,
    string Sku,
    int Quantity,
    decimal TotalAmount,
    DateTimeOffset PlacedAt,
    OrderStatus Status);

OutboxMode selects the outbox implementation once, through configuration, when the AppHost starts.

OutboxMode.cs

namespace Aspire_Outbox.Contracts;
 
public enum OutboxMode
{
    Dapr,
 
    MassTransit
}

ServiceInfo exposes the service name and active mode through each service's root endpoint (GET /).

ServiceInfo.cs

namespace Aspire_Outbox.Contracts;
 
public sealed record ServiceInfo(string Service, string OutboxMode);

Order Service

Both implementations e.g., Dapr and MassTransit coordinate order persistence with reliable event delivery, but use different mechanisms.

The Dapr implementation sends two operations for the same key to its state transaction API. One stores OrderDto; the other supplies OrderPlaced with outbox.projection metadata. The projected event is not a second permanent order row.

Behind the scenes, the sidecar sends an internal outbox intent to RabbitMQ, then commits the order and a temporary marker together in PostgreSQL. Its internal subscriber checks the marker before publishing the projected event. Marker cleanup happens in a later transaction. A lost broker confirmation can lead to another publication, so delivery is at least once.

The diagram below walks through the Dapr outbox flow.

Dapr Outbox

The MassTransit implementation adds an Orders row and calls IPublishEndpoint.Publish. UseBusOutbox captures the event in the order service's EF context. One SaveChangesAsync commits the order, OutboxMessage, and OutboxState in PostgreSQL. The bus outbox publishes after that commit and then advances its delivery state.

The diagram below walks through the MassTransit outbox flow.

MassTransit Outbox

Dapr requires RabbitMQ to accept the internal intent before committing a new order. MassTransit can commit the order and outbox message while RabbitMQ is unavailable, then deliver after recovery. In both modes, 201 Created confirms order persistence; fulfilment happens asynchronously.

The order service structure should look similar to the one below.

Order service project structure

Start by adding the MassTransit.EntityFrameworkCore, MassTransit.RabbitMQ and Npgsql.EntityFrameworkCore.PostgreSQL NuGet packages to the Order Service project.

Dapr/DaprOrderEndpoints.cs

using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using Aspire_Outbox.Contracts;
 
namespace Aspire_Outbox.OrderService.Dapr;
 
internal sealed class DaprOrderEndpoints : IOrderEndpoints
{
    public void MapEndpoints(IEndpointRouteBuilder app)
    {
        app.MapPost("/orders", async (PlaceOrderRequest request, DaprOrderStateStore store, CancellationToken ct) =>
        {
            var errors = new List<ValidationResult>();
            if (!Validator.TryValidateObject(request, new ValidationContext(request), errors, true))
                return Results.ValidationProblem(errors
                    .SelectMany(e => e.MemberNames.Select(name => (name, message: e.ErrorMessage ?? "Invalid value.")))
                    .GroupBy(e => e.name).ToDictionary(g => g.Key, g => g.Select(e => e.message).ToArray()));
 
            var order = new OrderDto(Guid.NewGuid(), request.CustomerName.Trim(), request.Sku.Trim(),
                request.Quantity, decimal.Round(request.Quantity * request.UnitPrice, 2), DateTimeOffset.UtcNow, OrderStatus.Placed);
            Activity.Current?.SetTag("order.id", order.OrderId.ToString());
            var message = new OrderPlaced(order.OrderId, order.CustomerName, order.Sku, order.Quantity, order.TotalAmount, order.PlacedAt);
            // One transaction persists the order and projects its event to the configured outbox topic.
            await store.SaveWithEventAsync(MessagingNames.DaprStateStore, order.OrderId.ToString(), order, message, ct);
            return Results.Created($"/orders/{order.OrderId}", order);
        });
 
        app.MapGet("/orders/{id:guid}", async (Guid id, DaprOrderStateStore store, CancellationToken ct) =>
        {
            var order = await store.GetAsync<OrderDto>(MessagingNames.DaprStateStore, id.ToString(), ct);
            return order is null ? Results.NotFound() : Results.Ok(order);
        });
    }
}

Dapr/DaprOrderStateStore.cs

using System.Net;
 
namespace Aspire_Outbox.OrderService.Dapr;
 
public sealed class DaprOrderStateStore(HttpClient http)
{
    public async Task<T?> GetAsync<T>(string store, string key, CancellationToken cancellationToken)
    {
        using var response = await http.GetAsync($"v1.0/state/{store}/{Uri.EscapeDataString(key)}", cancellationToken);
        if (response.StatusCode is HttpStatusCode.NoContent or HttpStatusCode.NotFound)
            return default;
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadFromJsonAsync<T>(cancellationToken);
    }
 
    public async Task SaveWithEventAsync<TState, TEvent>(string store, string key, TState state, TEvent message,
        CancellationToken cancellationToken)
    {
        object[] operations =
        [
            new { operation = "upsert", request = new { key, value = state } },
            new { operation = "upsert", request = new
            {
                key, value = message, contentType = "application/json",
                metadata = new Dictionary<string, string> { ["outbox.projection"] = "true" }
            } }
        ];
        using var response = await http.PostAsJsonAsync($"v1.0/state/{store}/transaction",
            new { operations }, cancellationToken);
        response.EnsureSuccessStatusCode();
    }
}

MassTransit/MassTransitOrderEndpoints.cs

using System.ComponentModel.DataAnnotations;
using Aspire_Outbox.Contracts;
using MassTransit;
using Microsoft.EntityFrameworkCore;
 
namespace Aspire_Outbox.OrderService.MassTransit;
 
internal sealed class MassTransitOrderEndpoints : IOrderEndpoints
{
    public void MapEndpoints(IEndpointRouteBuilder app)
    {
        app.MapPost("/orders", async (PlaceOrderRequest request, OrderDbContext db,
            IPublishEndpoint publish, CancellationToken ct) =>
        {
            var errors = new List<System.ComponentModel.DataAnnotations.ValidationResult>();
            if (!Validator.TryValidateObject(request, new ValidationContext(request), errors, true))
                return Results.ValidationProblem(errors
                    .SelectMany(e => e.MemberNames.Select(name => (name, message: e.ErrorMessage ?? "Invalid value.")))
                    .GroupBy(e => e.name).ToDictionary(g => g.Key, g => g.Select(e => e.message).ToArray()));
 
            var order = new Order
            {
                OrderId = Guid.NewGuid(), CustomerName = request.CustomerName.Trim(), Sku = request.Sku.Trim(),
                Quantity = request.Quantity, TotalAmount = decimal.Round(request.Quantity * request.UnitPrice, 2),
                PlacedAt = DateTimeOffset.UtcNow
            };
            db.Orders.Add(order);
            await publish.Publish(new OrderPlaced(order.OrderId, order.CustomerName, order.Sku,
                order.Quantity, order.TotalAmount, order.PlacedAt), ct);
            // The bus outbox and order are committed by this one database save.
            await db.SaveChangesAsync(ct);
            return Results.Created($"/orders/{order.OrderId}", order.ToDto());
        });
 
        app.MapGet("/orders/{id:guid}", async (Guid id, OrderDbContext db, CancellationToken ct) =>
        {
            var order = await db.Orders.AsNoTracking().SingleOrDefaultAsync(o => o.OrderId == id, ct);
            return order is null ? Results.NotFound() : Results.Ok(order.ToDto());
        });
    }
}

MassTransit/OrderDbContext.cs

using Aspire_Outbox.Contracts;
using MassTransit;
using Microsoft.EntityFrameworkCore;
 
namespace Aspire_Outbox.OrderService.MassTransit;
 
internal sealed class OrderDbContext(DbContextOptions<OrderDbContext> options) : DbContext(options)
{
    public DbSet<Order> Orders => Set<Order>();
 
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Order>().HasKey(order => order.OrderId);
        modelBuilder.AddInboxStateEntity();
        modelBuilder.AddOutboxMessageEntity();
        modelBuilder.AddOutboxStateEntity();
    }
}
 
internal sealed class Order
{
    public Guid OrderId { get; set; }
    public string CustomerName { get; set; } = "";
    public string Sku { get; set; } = "";
    public int Quantity { get; set; }
    public decimal TotalAmount { get; set; }
    public DateTimeOffset PlacedAt { get; set; }
 
    public OrderDto ToDto() => new(OrderId, CustomerName, Sku, Quantity, TotalAmount, PlacedAt, OrderStatus.Placed);
}

MassTransit/OrderSchemaInitializer.cs

namespace Aspire_Outbox.OrderService.MassTransit;
 
internal sealed class OrderSchemaInitializer(IServiceScopeFactory scopes, ILogger<OrderSchemaInitializer> logger) : IHostedService
{
    public async Task StartAsync(CancellationToken cancellationToken)
    {
        using var window = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
        window.CancelAfter(TimeSpan.FromSeconds(30));
        Exception? lastError = null;
        while (!window.IsCancellationRequested)
        {
            try
            {
                await using var scope = scopes.CreateAsyncScope();
                await scope.ServiceProvider.GetRequiredService<OrderDbContext>().Database.EnsureCreatedAsync(window.Token);
                return;
            }
            catch (Exception exception) when (!cancellationToken.IsCancellationRequested)
            {
                lastError = exception;
                if (window.IsCancellationRequested) break;
                try { await Task.Delay(TimeSpan.FromSeconds(3), window.Token); }
                catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) { break; }
            }
        }
        cancellationToken.ThrowIfCancellationRequested();
        logger.LogError(lastError, "Order database schema initialization did not succeed within 30 seconds");
        throw new InvalidOperationException("Order database schema initialization timed out.", lastError);
    }
 
    public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}

IOrderEndpoints.cs

namespace Aspire_Outbox.OrderService;
 
internal interface IOrderEndpoints
{
    void MapEndpoints(IEndpointRouteBuilder endpoints);
}

OrderDatabaseHealthCheck.cs

using Aspire_Outbox.Contracts;
using Aspire_Outbox.OrderService.MassTransit;
using Aspire_Outbox.OrderService.Dapr;
using Microsoft.Extensions.Diagnostics.HealthChecks;
 
namespace Aspire_Outbox.OrderService;
 
internal sealed class OrderDatabaseHealthCheck(
    IServiceScopeFactory scopes, IConfiguration configuration) : IHealthCheck
{
    public async Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context, CancellationToken cancellationToken = default)
    {
        using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
        timeout.CancelAfter(TimeSpan.FromSeconds(3));
        try
        {
            if (configuration.GetRequiredSection("Outbox:Mode").Get<OutboxMode>() == OutboxMode.Dapr)
            {
                await using var scope = scopes.CreateAsyncScope();
                await scope.ServiceProvider.GetRequiredService<DaprOrderStateStore>()
                    .GetAsync<object>("orderstatestore", "__health_probe__", timeout.Token);
            }
            else
            {
                await using var scope = scopes.CreateAsyncScope();
                if (!await scope.ServiceProvider.GetRequiredService<OrderDbContext>()
                    .Database.CanConnectAsync(timeout.Token))
                    return HealthCheckResult.Unhealthy("Order database is unavailable.");
            }
            return HealthCheckResult.Healthy();
        }
        catch (Exception exception) when (exception is not OperationCanceledException || !cancellationToken.IsCancellationRequested)
        {
            return HealthCheckResult.Unhealthy("Order database is unavailable.", exception);
        }
    }
}

OutboxRegistration.cs

using Aspire_Outbox.Contracts;
using Aspire_Outbox.OrderService.Dapr;
using Aspire_Outbox.OrderService.MassTransit;
using MassTransit;
using Microsoft.EntityFrameworkCore;
 
namespace Aspire_Outbox.OrderService;
 
internal static class OutboxRegistration
{
    public static IServiceCollection AddOrderOutbox(this IServiceCollection services,
        OutboxMode mode, IConfiguration configuration)
    {
        if (mode == OutboxMode.Dapr)
        {
            services.AddHttpClient<DaprOrderStateStore>(http =>
            {
                var endpoint = configuration["DAPR_HTTP_ENDPOINT"]
                    ?? $"http://127.0.0.1:{configuration["DAPR_HTTP_PORT"] ?? "3500"}";
                http.BaseAddress = new Uri(endpoint.TrimEnd('/') + "/");
                http.Timeout = TimeSpan.FromSeconds(10);
                if (configuration["DAPR_API_TOKEN"] is { Length: > 0 } token)
                    http.DefaultRequestHeaders.Add("dapr-api-token", token);
            });
            services.AddSingleton<IOrderEndpoints, DaprOrderEndpoints>();
        }
        else
        {
            services.AddDbContext<OrderDbContext>(options => options.UseNpgsql(
                configuration.GetConnectionString("orders-masstransit")));
            services.AddHostedService<OrderSchemaInitializer>();
            services.AddMassTransit(bus =>
            {
                bus.AddEntityFrameworkOutbox<OrderDbContext>(outbox =>
                {
                    outbox.UsePostgres();
                    outbox.UseBusOutbox();
                });
                bus.UsingRabbitMq((_, rabbit) =>
                {
                    rabbit.Host(configuration.GetConnectionString("rabbitmq")
                        ?? throw new InvalidOperationException("RabbitMQ connection string is missing."));
                    rabbit.Message<OrderPlaced>(message =>
                        message.SetEntityName(MessagingNames.MassTransitOrderPlacedExchange));
                });
            });
            services.AddSingleton<IOrderEndpoints, MassTransitOrderEndpoints>();
        }
 
        return services;
    }
}

Program.cs

using Aspire_Outbox.Contracts;
using Aspire_Outbox.OrderService;
 
var builder = WebApplication.CreateBuilder(args);
 
builder.AddServiceDefaults();
builder.Services.AddProblemDetails();
 
var mode = builder.Configuration.GetRequiredSection("Outbox:Mode").Get<OutboxMode>();
builder.Services.AddOrderOutbox(mode, builder.Configuration);
builder.Services.AddHealthChecks().AddCheck<OrderDatabaseHealthCheck>("order-database", tags: ["ready"], timeout: TimeSpan.FromSeconds(4));
builder.Services.AddHealthChecks().AddCheck<RabbitMqDeliveryHealthCheck>("rabbitmq-delivery", tags: ["delivery"], timeout: TimeSpan.FromSeconds(4));
 
var app = builder.Build();
app.UseExceptionHandler();
app.MapDefaultEndpoints();
if (app.Environment.IsDevelopment())
    app.MapHealthChecks("/health/delivery", new Microsoft.AspNetCore.Diagnostics.HealthChecks.HealthCheckOptions
    {
        Predicate = check => check.Tags.Contains("delivery")
    });
 
var endpoints = app.Services.GetRequiredService<IOrderEndpoints>();
 
app.MapGet("/", () => new ServiceInfo(ServiceNames.OrderService, mode.ToString()));
 
endpoints.MapEndpoints(app);
 
app.Run();
 
public partial class Program { }

RabbitMqDeliveryHealthCheck.cs

using System.Net.Sockets;
using Microsoft.Extensions.Diagnostics.HealthChecks;
 
namespace Aspire_Outbox.OrderService;
 
internal sealed class RabbitMqDeliveryHealthCheck(IConfiguration configuration) : IHealthCheck
{
    public async Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context, CancellationToken cancellationToken = default)
    {
        var address = configuration.GetConnectionString("rabbitmq");
        if (!Uri.TryCreate(address, UriKind.Absolute, out var uri))
            return HealthCheckResult.Unhealthy("RabbitMQ address is missing.");
 
        using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
        timeout.CancelAfter(TimeSpan.FromSeconds(3));
        try
        {
            using var client = new TcpClient();
            await client.ConnectAsync(uri.Host, uri.Port, timeout.Token);
            return HealthCheckResult.Healthy();
        }
        catch (Exception exception) when (exception is not OperationCanceledException || !cancellationToken.IsCancellationRequested)
        {
            return HealthCheckResult.Unhealthy("RabbitMQ is unreachable; delivery may be pending.", exception);
        }
    }
}

Fulfilment Service

In Dapr mode, the fulfilment sidecar delivers OrderPlaced to POST /events/order-placed. The handler saves a Fulfilled value in MySQL under the order ID and returns SUCCESS only once that save has completed. Because a repeated event overwrites the same key with the same result, redelivery is harmless.

On failure, Dapr retries the inbound delivery twelve times at five-second intervals. If those retries are exhausted, RabbitMQ requeues the unacknowledged message, so the event is attempted again rather than lost.

In MassTransit mode, the consumer keeps the RabbitMQ delivery unacknowledged while it works. Its EF inbox records the message and consumer IDs, and the handler also checks for an existing fulfilment with the same order ID. The inbox entry and the Fulfilments row commit together in MySQL before the delivery is acknowledged, so redelivery stays safe even if a broker acknowledgement is lost. Inbox deduplication holds for the configured duplicate detection window. Once inbox entries expire, the order-ID check continues to protect existing fulfilments.

On failure, MassTransit retries up to 25 times after the initial attempt, which gives 26 attempts in total, with exponential intervals. If it exhausts them, it moves the message to the endpointโ€™s _error queue and acknowledges the original delivery. Fulfilment then needs a manual replay once the underlying fault has been fixed.

The fulfilment service structure should look similar to the one below. Fulfilment service project structure

Start by adding the MassTransit.EntityFrameworkCore, MassTransit.RabbitMQ and MySql.EntityFrameworkCore NuGet packages to the Fulfilment Service project.

Dapr/DaprFulfilmentEndpoints.cs

using System.Diagnostics;
using Aspire_Outbox.Contracts;
 
namespace Aspire_Outbox.FulfilmentService.Dapr;
 
internal sealed class DaprFulfilmentEndpoints : IFulfilmentEndpoints
{
    public void MapEndpoints(IEndpointRouteBuilder app)
    {
        app.MapGet("/dapr/subscribe", () => new[]
        {
            new { pubsubname = MessagingNames.DaprPubSub, topic = MessagingNames.DaprOrderPlacedTopic,
                routes = new { @default = "/events/order-placed" },
                metadata = new { queueName = MessagingNames.DaprFulfilmentQueue } }
        });
 
        app.MapPost("/events/order-placed", async (OrderCloudEvent envelope, DaprFulfilmentStateStore store, CancellationToken ct) =>
        {
            if (envelope.Data is not { } message || message.OrderId == Guid.Empty)
                return Results.BadRequest();
            Activity.Current?.SetTag("order.id", message.OrderId.ToString());
            var fulfilled = new OrderDto(message.OrderId, message.CustomerName, message.Sku, message.Quantity,
                message.TotalAmount, message.PlacedAt, OrderStatus.Fulfilled);
            // Delivery is at least once. Replacing the same deterministic value is idempotent,
            // including concurrent redeliveries; acknowledge only after persistence succeeds.
            await store.SaveAsync(MessagingNames.DaprFulfilmentStore, message.OrderId.ToString(), fulfilled, ct);
            return Results.Ok(new { status = "SUCCESS" });
        });
 
        app.MapGet("/orders/{id:guid}", async (Guid id, DaprFulfilmentStateStore store, CancellationToken ct) =>
        {
            var order = await store.GetAsync<OrderDto>(MessagingNames.DaprFulfilmentStore, id.ToString(), ct);
            return order is null ? Results.NotFound() : Results.Ok(order);
        });
    }
}

Dapr/DaprFulfilmentStateStore.cs

using System.Net;
 
namespace Aspire_Outbox.FulfilmentService.Dapr;
 
public sealed class DaprFulfilmentStateStore(HttpClient http)
{
    public async Task<T?> GetAsync<T>(string store, string key, CancellationToken cancellationToken)
    {
        using var response = await http.GetAsync($"v1.0/state/{store}/{Uri.EscapeDataString(key)}", cancellationToken);
        if (response.StatusCode is HttpStatusCode.NoContent or HttpStatusCode.NotFound)
            return default;
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadFromJsonAsync<T>(cancellationToken);
    }
 
    public async Task SaveAsync<T>(string store, string key, T value, CancellationToken cancellationToken)
    {
        using var response = await http.PostAsJsonAsync($"v1.0/state/{store}",
            new[] { new { key, value } }, cancellationToken);
        response.EnsureSuccessStatusCode();
    }
}

Dapr/OrderCloudEvent.cs

using Aspire_Outbox.Contracts;
 
public sealed record OrderCloudEvent(OrderPlaced? Data);

MassTransit/FulfilmentDbContext.cs

using Aspire_Outbox.Contracts;
using MassTransit;
using Microsoft.EntityFrameworkCore;
 
namespace Aspire_Outbox.FulfilmentService.MassTransit;
 
internal sealed class FulfilmentDbContext(DbContextOptions<FulfilmentDbContext> options) : DbContext(options)
{
    public DbSet<Fulfilment> Fulfilments => Set<Fulfilment>();
 
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Fulfilment>().HasKey(order => order.OrderId);
        modelBuilder.AddInboxStateEntity();
        modelBuilder.AddOutboxMessageEntity();
        modelBuilder.AddOutboxStateEntity();
    }
}
 
internal sealed class Fulfilment
{
    public Guid OrderId { get; set; }
    public string CustomerName { get; set; } = "";
    public string Sku { get; set; } = "";
    public int Quantity { get; set; }
    public decimal TotalAmount { get; set; }
    public DateTimeOffset PlacedAt { get; set; }
 
    public OrderDto ToDto() => new(OrderId, CustomerName, Sku, Quantity, TotalAmount, PlacedAt, OrderStatus.Fulfilled);
}

MassTransit/FulfilmentSchemaInitializer.cs

namespace Aspire_Outbox.FulfilmentService.MassTransit;
 
internal sealed class FulfilmentSchemaInitializer(IServiceScopeFactory scopes, ILogger<FulfilmentSchemaInitializer> logger) : IHostedService
{
    public async Task StartAsync(CancellationToken cancellationToken)
    {
        using var window = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
        window.CancelAfter(TimeSpan.FromSeconds(30));
        Exception? lastError = null;
        while (!window.IsCancellationRequested)
        {
            try
            {
                await using var scope = scopes.CreateAsyncScope();
                await scope.ServiceProvider.GetRequiredService<FulfilmentDbContext>().Database.EnsureCreatedAsync(window.Token);
                return;
            }
            catch (Exception exception) when (!cancellationToken.IsCancellationRequested)
            {
                lastError = exception;
                if (window.IsCancellationRequested) break;
                try { await Task.Delay(TimeSpan.FromSeconds(3), window.Token); }
                catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) { break; }
            }
        }
        cancellationToken.ThrowIfCancellationRequested();
        logger.LogError(lastError, "Fulfilment database schema initialization did not succeed within 30 seconds");
        throw new InvalidOperationException("Fulfilment database schema initialization timed out.", lastError);
    }
 
    public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}

MassTransit/MassTransitFulfilmentEndpoints.cs

using Aspire_Outbox.Contracts;
using MassTransit;
using Microsoft.EntityFrameworkCore;
 
namespace Aspire_Outbox.FulfilmentService.MassTransit;
 
internal sealed class MassTransitFulfilmentEndpoints : IFulfilmentEndpoints
{
    public void MapEndpoints(IEndpointRouteBuilder app)
    {
        app.MapGet("/orders/{id:guid}", async (Guid id, FulfilmentDbContext db, CancellationToken ct) =>
        {
            var order = await db.Fulfilments.AsNoTracking().SingleOrDefaultAsync(o => o.OrderId == id, ct);
            return order is null ? Results.NotFound() : Results.Ok(order.ToDto());
        });
    }
}
 
internal sealed class OrderPlacedConsumer(FulfilmentDbContext db) : IConsumer<OrderPlaced>
{
    public async Task Consume(ConsumeContext<OrderPlaced> context)
    {
        var message = context.Message;
        if (message.OrderId == Guid.Empty)
            throw new ArgumentException("Order ID is required.");
 
        if (await db.Fulfilments.AnyAsync(o => o.OrderId == message.OrderId, context.CancellationToken))
            return;
 
        db.Fulfilments.Add(new Fulfilment
        {
            OrderId = message.OrderId, CustomerName = message.CustomerName, Sku = message.Sku,
            Quantity = message.Quantity, TotalAmount = message.TotalAmount, PlacedAt = message.PlacedAt
        });
    }
}

MassTransit/MySqlInboxCleanupService.cs

This worker replaces MassTransit's default inbox cleanup worker to avoid MySQL's unsupported LIMIT inside an IN subquery. It first selects expired inbox IDs, then deletes those entries in a separate query, preserving entries that still have outbox messages awaiting delivery.

using MassTransit;
using MassTransit.EntityFrameworkCoreIntegration;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
 
namespace Aspire_Outbox.FulfilmentService.MassTransit;
 
internal sealed class MySqlInboxCleanupService(
    IServiceScopeFactory scopeFactory,
    IOptions<InboxCleanupServiceOptions> options,
    ILogger<MySqlInboxCleanupService> logger) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        var settings = options.Value;
        var databaseUnavailable = false;
 
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                using var scope = scopeFactory.CreateScope();
                var db = scope.ServiceProvider.GetRequiredService<FulfilmentDbContext>();
                var cutoff = DateTime.UtcNow - settings.DuplicateDetectionWindow;
 
                var ids = await db.Set<InboxState>()
                    .Where(inbox => inbox.Delivered != null && inbox.Delivered < cutoff)
                    .Where(inbox => !db.Set<OutboxMessage>().Any(message =>
                        message.InboxMessageId == inbox.MessageId &&
                        message.InboxConsumerId == inbox.ConsumerId))
                    .OrderBy(inbox => inbox.Delivered)
                    .Select(inbox => inbox.Id)
                    .Take(settings.QueryMessageLimit)
                    .ToListAsync(stoppingToken);
 
                if (ids.Count > 0)
                    await db.Set<InboxState>()
                        .Where(inbox => ids.Contains(inbox.Id))
                        .ExecuteDeleteAsync(stoppingToken);
                if (databaseUnavailable)
                {
                    databaseUnavailable = false;
                    logger.LogInformation("MySQL inbox cleanup resumed");
                }
            }
            catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
            {
                break;
            }
            catch (Exception exception)
            {
                if (!databaseUnavailable)
                {
                    databaseUnavailable = true;
                    logger.LogWarning(exception, "MySQL inbox cleanup paused while the database is unavailable");
                }
            }
 
            await Task.Delay(settings.QueryDelay, stoppingToken);
        }
    }
}

FulfilmentDatabaseHealthCheck.cs

using Aspire_Outbox.Contracts;
using Aspire_Outbox.FulfilmentService.MassTransit;
using Aspire_Outbox.FulfilmentService.Dapr;
using Microsoft.Extensions.Diagnostics.HealthChecks;
 
namespace Aspire_Outbox.FulfilmentService;
 
internal sealed class FulfilmentDatabaseHealthCheck(
    IServiceScopeFactory scopes, IConfiguration configuration) : IHealthCheck
{
    public async Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context, CancellationToken cancellationToken = default)
    {
        using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
        timeout.CancelAfter(TimeSpan.FromSeconds(3));
        try
        {
            if (configuration.GetRequiredSection("Outbox:Mode").Get<OutboxMode>() == OutboxMode.Dapr)
            {
                await using var scope = scopes.CreateAsyncScope();
                await scope.ServiceProvider.GetRequiredService<DaprFulfilmentStateStore>()
                    .GetAsync<object>("fulfilmentstatestore", "__health_probe__", timeout.Token);
            }
            else
            {
                await using var scope = scopes.CreateAsyncScope();
                if (!await scope.ServiceProvider.GetRequiredService<FulfilmentDbContext>()
                    .Database.CanConnectAsync(timeout.Token))
                    return HealthCheckResult.Unhealthy("Fulfilment database is unavailable.");
            }
            return HealthCheckResult.Healthy();
        }
        catch (Exception exception) when (exception is not OperationCanceledException || !cancellationToken.IsCancellationRequested)
        {
            return HealthCheckResult.Unhealthy("Fulfilment database is unavailable.", exception);
        }
    }
}

IFulfilmentEndpoints.cs

namespace Aspire_Outbox.FulfilmentService;
 
internal interface IFulfilmentEndpoints
{
    void MapEndpoints(IEndpointRouteBuilder endpoints);
}

OutboxRegistration.cs

using Aspire_Outbox.Contracts;
using Aspire_Outbox.FulfilmentService.Dapr;
using Aspire_Outbox.FulfilmentService.MassTransit;
using MassTransit;
using MassTransit.RabbitMqTransport.Configuration;
using Microsoft.EntityFrameworkCore;
 
namespace Aspire_Outbox.FulfilmentService;
 
internal static class OutboxRegistration
{
    public static IServiceCollection AddFulfilmentOutbox(this IServiceCollection services,
        OutboxMode mode, IConfiguration configuration)
    {
        if (mode == OutboxMode.Dapr)
        {
            services.AddHttpClient<DaprFulfilmentStateStore>(http =>
            {
                var endpoint = configuration["DAPR_HTTP_ENDPOINT"]
                    ?? $"http://127.0.0.1:{configuration["DAPR_HTTP_PORT"] ?? "3500"}";
                http.BaseAddress = new Uri(endpoint.TrimEnd('/') + "/");
                http.Timeout = TimeSpan.FromSeconds(10);
                if (configuration["DAPR_API_TOKEN"] is { Length: > 0 } token)
                    http.DefaultRequestHeaders.Add("dapr-api-token", token);
            });
            services.AddSingleton<IFulfilmentEndpoints, DaprFulfilmentEndpoints>();
        }
        else
        {
            services.AddDbContext<FulfilmentDbContext>(options => options.UseMySQL(
                configuration.GetConnectionString("fulfilment-masstransit")
                    ?? throw new InvalidOperationException("MySQL connection string is missing.")));
            services.AddHostedService<FulfilmentSchemaInitializer>();
            services.AddMassTransit(bus =>
            {
                bus.AddConsumer<OrderPlacedConsumer>();
                bus.AddEntityFrameworkOutbox<FulfilmentDbContext>(outbox =>
                {
                    outbox.UseMySql();
                    outbox.DisableInboxCleanupService();
                });
                bus.UsingRabbitMq((context, rabbit) =>
                {
                    rabbit.Host(configuration.GetConnectionString("rabbitmq")
                        ?? throw new InvalidOperationException("RabbitMQ connection string is missing."));
                    rabbit.Message<OrderPlaced>(message =>
                        message.SetEntityName(MessagingNames.MassTransitOrderPlacedExchange));
                    rabbit.ReceiveEndpoint(MessagingNames.MassTransitFulfilmentQueue, endpoint =>
                    {
                        ((RabbitMqReceiveSettings)((RabbitMqReceiveEndpointConfiguration)endpoint).Settings)
                            .ExchangeName = MessagingNames.MassTransitFulfilmentExchange;
                        endpoint.UseMessageRetry(retry => retry.Exponential(
                            25, TimeSpan.FromSeconds(1), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(2)));
                        endpoint.UseEntityFrameworkOutbox<FulfilmentDbContext>(context);
                        endpoint.ConfigureConsumer<OrderPlacedConsumer>(context);
                    });
                });
            });
            services.AddHostedService<MySqlInboxCleanupService>();
            services.AddSingleton<IFulfilmentEndpoints, MassTransitFulfilmentEndpoints>();
        }
 
        return services;
    }
}

Program.cs

using Aspire_Outbox.Contracts;
using Aspire_Outbox.FulfilmentService;
 
var builder = WebApplication.CreateBuilder(args);
builder.AddServiceDefaults();
builder.Services.AddProblemDetails();
var mode = builder.Configuration.GetRequiredSection("Outbox:Mode").Get<OutboxMode>();
builder.Services.AddFulfilmentOutbox(mode, builder.Configuration);
builder.Services.AddHealthChecks().AddCheck<FulfilmentDatabaseHealthCheck>("fulfilment-database", tags: ["ready"], timeout: TimeSpan.FromSeconds(4));
 
var app = builder.Build();
app.UseExceptionHandler();
app.MapDefaultEndpoints();
var endpoints = app.Services.GetRequiredService<IFulfilmentEndpoints>();
app.MapGet("/", () => new ServiceInfo(ServiceNames.FulfilmentService, mode.ToString()));
endpoints.MapEndpoints(app);
 
app.Run();
 
public partial class Program { }

Service Defaults

ServiceDefaults configures shared health endpoints, service discovery, HTTP resilience, and telemetry. Each backend's readiness check probes its active database path. The order service exposes a separate RabbitMQ delivery health check, so a broker outage does not turn a durable order write into a failed readiness check. In MassTransit mode, EF Core command spans make database and inbox timing visible; SQL text and row values are not captured by default.

The Service Defaults structure should look similar to the one below. Blog image

Start by adding the OpenTelemetry.Instrumentation.EntityFrameworkCore NuGet package to the Service Defaults project.

Extensions.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Logging;
using OpenTelemetry;
using OpenTelemetry.Metrics;
using OpenTelemetry.Trace;
using Microsoft.Extensions.Http.Resilience;
 
namespace Microsoft.Extensions.Hosting;
 
public static class Extensions
{
    private const string HealthEndpointPath = "/health";
    private const string AlivenessEndpointPath = "/alive";
 
    public static TBuilder AddServiceDefaults<TBuilder>(this TBuilder builder) where TBuilder : IHostApplicationBuilder
    {
        builder.ConfigureOpenTelemetry();
 
        builder.AddDefaultHealthChecks();
 
        builder.Services.AddServiceDiscovery();
 
        builder.Services.ConfigureHttpClientDefaults(http =>
        {
            http.AddStandardResilienceHandler(options => options.Retry.DisableForUnsafeHttpMethods());
            http.AddServiceDiscovery();
        });
 
        return builder;
    }
 
    public static TBuilder ConfigureOpenTelemetry<TBuilder>(this TBuilder builder) where TBuilder : IHostApplicationBuilder
    {
        builder.Logging.AddOpenTelemetry(logging =>
        {
            logging.IncludeFormattedMessage = true;
            logging.IncludeScopes = true;
        });
 
        builder.Services.AddOpenTelemetry()
            .WithMetrics(metrics =>
            {
                metrics.AddAspNetCoreInstrumentation()
                    .AddHttpClientInstrumentation()
                    .AddRuntimeInstrumentation();
            })
            .WithTracing(tracing =>
            {
                tracing.AddSource(builder.Environment.ApplicationName)
                    // MassTransit publishes its own spans (publish, consume, outbox delivery) on this source.
                    // It is harmless in Dapr mode, where nothing emits on it.
                    .AddSource("MassTransit")
                    .AddAspNetCoreInstrumentation(options =>
                        // Keep health check requests out of the traces.
                        options.Filter = context =>
                            !context.Request.Path.StartsWithSegments(HealthEndpointPath)
                            && !context.Request.Path.StartsWithSegments(AlivenessEndpointPath))
                    .AddHttpClientInstrumentation()
                    // Captures EF command timing in MassTransit mode; SQL text stays off by default.
                    .AddEntityFrameworkCoreInstrumentation();
            });
 
        builder.AddOpenTelemetryExporters();
 
        return builder;
    }
 
    private static TBuilder AddOpenTelemetryExporters<TBuilder>(this TBuilder builder) where TBuilder : IHostApplicationBuilder
    {
        var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]);
 
        if (useOtlpExporter)
        {
            builder.Services.AddOpenTelemetry().UseOtlpExporter();
        }
 
        return builder;
    }
 
    public static TBuilder AddDefaultHealthChecks<TBuilder>(this TBuilder builder) where TBuilder : IHostApplicationBuilder
    {
        builder.Services.AddHealthChecks()
            // A trivial liveness check: if the process can answer, it is alive.
            .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]);
 
        return builder;
    }
 
    public static WebApplication MapDefaultEndpoints(this WebApplication app)
    {
        // Health endpoints expose operational detail, so they are mapped in Development only.
        if (app.Environment.IsDevelopment())
        {
            // All health checks must pass for the app to be considered ready for traffic.
            app.MapHealthChecks(HealthEndpointPath, new HealthCheckOptions
            {
                Predicate = registration => !registration.Tags.Contains("delivery")
            });
 
            // Only the "live" checks must pass for the app to be considered alive.
            app.MapHealthChecks(AlivenessEndpointPath, new HealthCheckOptions
            {
                Predicate = registration => registration.Tags.Contains("live")
            });
        }
 
        return app;
    }
}

Web App

The Web app lets you place orders and track fulfilment in Dapr or MassTransit mode. It shows Saved ยท awaiting fulfilment until the fulfilment record is readable, then Fulfilled.

The UI code is omitted here to keep the focus on the Outbox. If you'd like access to it, feel free to get in touch.

Dapr Outbox Diagnostics

The Dapr marker normally disappears too quickly to inspect manually. This optional local capture installs an audit trigger on ordersdb.state and starts a RabbitMQ trace. The audit groups committed order and marker changes by transaction ID. The broker trace records the internal outbox intent and external event, including their payloads. The dapr-outbox-capture resource starts after the order service is healthy when Outbox:CaptureDiagnostics is enabled.

The dapr outbox diagnostics structure should look similar to the one below. Dapr outbox diagnostic files

dapr-outbox-audit-start.sql

-- Run after Dapr has created ordersdb.state. Audit rows commit or roll back with
-- the state change, preserving only transitions that actually committed.
CREATE TABLE IF NOT EXISTS public.dapr_outbox_state_audit (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    captured_at timestamptz NOT NULL DEFAULT clock_timestamp(),
    transaction_id xid8 NOT NULL,
    operation text NOT NULL,
    state_key text NOT NULL,
    state_value bytea
);
 
CREATE OR REPLACE FUNCTION public.capture_dapr_outbox_state()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
    IF TG_OP = 'DELETE' THEN
        INSERT INTO public.dapr_outbox_state_audit (transaction_id, operation, state_key, state_value)
        VALUES (pg_current_xact_id(), TG_OP, OLD.key, OLD.value);
    ELSE
        INSERT INTO public.dapr_outbox_state_audit (transaction_id, operation, state_key, state_value)
        VALUES (pg_current_xact_id(), TG_OP, NEW.key, NEW.value);
    END IF;
    RETURN NULL;
END;
$$;
 
DROP TRIGGER IF EXISTS capture_dapr_outbox_state ON public.state;
CREATE TRIGGER capture_dapr_outbox_state
AFTER INSERT OR UPDATE OR DELETE ON public.state
FOR EACH ROW EXECUTE FUNCTION public.capture_dapr_outbox_state();

dapr-outbox-audit-stop.sql

-- Leave the captured rows available for inspection after recording stops.
DROP TRIGGER IF EXISTS capture_dapr_outbox_state ON public.state;
DROP FUNCTION IF EXISTS public.capture_dapr_outbox_state();

dapr-outbox-capture.sh

#!/usr/bin/env bash
set -euo pipefail
 
cd "$(dirname "$0")/.."
 
rabbit_api='http://127.0.0.1:55673/api'
rabbit_auth='sample:SamplePassw0rd'
trace_name='dapr-outbox-diagnostic'
 
case "${1:-}" in
    run)
        bash "$0" start
        trap 'bash "$0" stop' EXIT
        trap 'exit 0' INT TERM
        echo 'Capture running under Aspire. Use report to inspect the retained transition.'
        while :; do sleep 1; done
        ;;
    start)
        docker compose exec -T postgres psql -v ON_ERROR_STOP=1 -U sample -d ordersdb \
            < dapr-outbox-diagnostics/dapr-outbox-audit-start.sql
        docker compose exec -T rabbitmq rabbitmq-plugins enable rabbitmq_tracing
        # The tracing plugin defaults to guest/guest, which this sample does not create.
        docker compose exec -T rabbitmq rabbitmqctl eval \
            'application:set_env(rabbitmq_tracing, username, <<"sample">>), application:set_env(rabbitmq_tracing, password, <<"SamplePassw0rd">>).'
        if ! curl --fail-with-body --silent --show-error --max-time 15 \
            --user "$rabbit_auth" --request PUT \
            --header 'Content-Type: application/json' \
            --data '{"format":"json","pattern":"#","max_payload_bytes":50000}' \
            "$rabbit_api/traces/%2F/$trace_name"; then
            docker compose exec -T postgres psql -v ON_ERROR_STOP=1 -U sample -d ordersdb \
                < dapr-outbox-diagnostics/dapr-outbox-audit-stop.sql
            exit 1
        fi
        echo 'Capture active. Place one order in Dapr mode, then run report.'
        ;;
    report)
        echo 'PostgreSQL committed state changes:'
        docker compose exec -T postgres psql -U sample -d ordersdb -P pager=off \
            -c "SELECT id, captured_at, transaction_id, operation, state_key, encode(state_value, 'escape') AS value FROM public.dapr_outbox_state_audit ORDER BY id"
        command -v jq >/dev/null || { echo 'jq is required to decode RabbitMQ payloads.' >&2; exit 1; }
        echo 'Dapr outbox RabbitMQ messages (decoded JSON lines):'
        curl --fail-with-body --silent --show-error --max-time 15 \
            --user "$rabbit_auth" "$rabbit_api/trace-files/$trace_name.log" \
            | jq -c 'select(.exchange == "defaultorder-servicedapr.orders.order-placedoutbox" or .exchange == "dapr.orders.order-placed") | {timestamp, type, exchange, queue, routed_queues, payload: (.payload | @base64d | fromjson?)}'
        ;;
    stop)
        curl --fail-with-body --silent --show-error --max-time 15 \
            --user "$rabbit_auth" --request DELETE "$rabbit_api/traces/%2F/$trace_name"
        docker compose exec -T postgres psql -v ON_ERROR_STOP=1 -U sample -d ordersdb \
            < dapr-outbox-diagnostics/dapr-outbox-audit-stop.sql
        echo 'Capture stopped. Audit rows and the RabbitMQ trace file remain available for report.'
        ;;
    *)
        echo "Usage: $0 start|report|stop" >&2
        exit 2
        ;;
esac

Local Infrastructure (Docker)

The compose.yaml file supplies PostgreSQL for both order databases, MySQL for both fulfilment databases, and RabbitMQ as the message transport. It also starts pgAdmin and phpMyAdmin, which the AppHost links from its dashboard. Named volumes retain data across an ordinary docker compose down and later restart.

Blog image

mysql/init.sql

CREATE DATABASE IF NOT EXISTS `fulfilment-masstransit`;
GRANT ALL PRIVILEGES ON `fulfilment-masstransit`.* TO 'sample'@'%';

pgadmin/servers.json

{
  "Servers": {
    "1": {
      "Name": "Aspire Outbox PostgreSQL",
      "Group": "Local",
      "Host": "postgres",
      "Port": 5432,
      "MaintenanceDB": "postgres",
      "Username": "sample",
      "SSLMode": "disable",
      "PasswordExecCommand": "printenv POSTGRES_PASSWORD"
    }
  }
}

postgres/init.sql

CREATE DATABASE ordersdb;
CREATE DATABASE "orders-masstransit";

compose.yaml

services:
  postgres:
    image: postgres:17
    container_name: aspire-outbox-postgres
    environment:
      POSTGRES_USER: sample
      POSTGRES_PASSWORD: &postgres-password SamplePassw0rd
    ports:
      - "127.0.0.1:55432:5432"
    volumes:
      - postgres-data:/var/lib/postgresql/data
      - ./docker/postgres/init.sql:/docker-entrypoint-initdb.d/init.sql:ro
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -h 127.0.0.1 -U sample -d postgres"]
      interval: 2s
      timeout: 3s
      retries: 30
 
  pgadmin:
    image: dpage/pgadmin4:latest
    container_name: pgadmin
    environment:
      PGADMIN_DEFAULT_EMAIL: admin@example.com
      PGADMIN_DEFAULT_PASSWORD: *postgres-password
      PGADMIN_CONFIG_SERVER_MODE: "False"
      PGADMIN_CONFIG_MASTER_PASSWORD_REQUIRED: "False"
      POSTGRES_PASSWORD: *postgres-password
    ports:
      - "127.0.0.1:5050:80"
    volumes:
      - ./docker/pgadmin/servers.json:/pgadmin4/servers.json:ro
    depends_on:
      postgres:
        condition: service_healthy
 
  mysql:
    image: mysql:8.4
    container_name: aspire-outbox-mysql
    environment:
      MYSQL_ROOT_PASSWORD: SamplePassw0rd
      MYSQL_USER: sample
      MYSQL_PASSWORD: SamplePassw0rd
      MYSQL_DATABASE: fulfilmentdb
    ports:
      - "127.0.0.1:53306:3306"
    volumes:
      - mysql-data:/var/lib/mysql
      - ./docker/mysql/init.sql:/docker-entrypoint-initdb.d/init.sql:ro
    healthcheck:
      test: ["CMD-SHELL", "mysqladmin ping -h 127.0.0.1 -u sample -p$$MYSQL_PASSWORD --silent"]
      interval: 2s
      timeout: 3s
      retries: 30
 
  phpmyadmin:
    image: phpmyadmin:5.2
    container_name: aspire-outbox-phpmyadmin
    environment:
      PMA_HOST: mysql
      PMA_USER: sample
      PMA_PASSWORD: SamplePassw0rd
    ports:
      - "127.0.0.1:5051:80"
    depends_on:
      mysql:
        condition: service_healthy
 
  rabbitmq:
    image: rabbitmq:4-management
    container_name: aspire-outbox-rabbitmq
    hostname: rabbitmq
    environment:
      RABBITMQ_DEFAULT_USER: sample
      RABBITMQ_DEFAULT_PASS: SamplePassw0rd
    ports:
      - "127.0.0.1:55672:5672"
      - "127.0.0.1:55673:15672"
    volumes:
      - rabbitmq-data:/var/lib/rabbitmq
    healthcheck:
      test: ["CMD", "rabbitmq-diagnostics", "-q", "check_port_connectivity", "--address", "127.0.0.1"]
      interval: 2s
      timeout: 5s
      retries: 30
 
volumes:
  postgres-data:
  mysql-data:
  rabbitmq-data:

Running the App

With almost everything in place, let's run the application.

aspire run

Open the Aspire dashboard, select the web resource and place an order. Save its ID, watch it move from Saved to Fulfilled, then reload and look it up again. To try the other implementation, stop the AppHost and change the mode and observe how the application behaves.

NOTE: Depending on the run mode, the Aspire dashboard displays different resources. Refer to the diagram below to see the resources when the run mode is Dapr.

Aspire dashboard in Dapr mode Order flow in Dapr mode

Refer to the diagram below to see the resources when the run mode is MassTransit.

Aspire dashboard in MassTransit mode Order flow in MassTransit mode

To see recovery, stop fulfilment-service from the Aspire dashboard, place another order, and confirm it remains Saved ยท awaiting fulfilment. Restart the service and watch for the fulfilment record.

Inspecting the outbox

In MassTransit mode, pgAdmin shows Orders, OutboxMessage, and OutboxState in orders-masstransit. phpMyAdmin shows Fulfilments and InboxState in fulfilment-masstransit. A completed run may leave no pending outbox message, so an empty outbox table after delivery does not mean that no event was sent.

MassTransit RabbitMQ topology MassTransit order data in PostgreSQL MassTransit fulfilment data in MySQL

In Dapr mode, pgAdmin shows the order in ordersdb.state, and phpMyAdmin shows the final value in fulfilmentdb.fulfilment_state. RabbitMQ Management shows both Dapr's internal outbox path and the fulfilment topic and queue. Wait for the Capture active log before placing an order if you want the optional audit and broker trace to record its short-lived marker.

Dapr RabbitMQ topology Dapr order state in PostgreSQL Dapr fulfilment state in MySQL

Conclusion

Dapr lets applications already using its transactional state API enable outbox publishing through component configuration, without application-owned coordination or cleanup workers. The runtime handles retries and marker cleanup across supported state stores and pub/sub brokers; projections let event payloads differ from stored data. Internal coordination and external publishing can use separate pub/sub components. This sample uses RabbitMQ for both, so it must accept the internal intent before an order commits. MassTransit commits business data and outgoing messages in the same EF Core transaction, allowing orders to be saved during broker outages. Its Consumer Outbox combines duplicate detection within a configured window with transactional storage of follow-up messages, protecting database changes and outgoing events together, with more database setup and maintenance. Both approaches require idempotent consumers.

I recommend MassTransit when EF Core transaction ownership, consumer inbox protection and accepting orders during broker outages are priorities. Choose Dapr when configuration-driven integration, less application code and language or infrastructure portability matter more, especially when the application already uses Dapr state transactions.

Happy Learning & coding... ๐Ÿ“š