Two different failure modes appear when an ASP.NET Core MVC action publishes a domain event or webhook to a message broker after saving business state to a relational database:

  • Database commits, broker publish fails (network blip, broker restart, timeout): Your database records the state change, but downstream consumers never receive the event—causing silent data drift.
  • Broker publish succeeds before or outside the transaction, database rolls back (constraint violation, deadlock, validation failure): Downstream consumers react to an event for data that does not exist.

The Transactional Outbox Pattern eliminates dual-write inconsistency by persisting outbox messages inside the exact same database transaction as your domain changes. An EF Core SaveChangesInterceptor harvests domain events raised on tracked entities right before SaveChangesAsync commits, writes OutboxMessage rows into the same transaction, and a BackgroundService backed by a bounded Channel<T> (plus periodic polling for crash recovery) dispatches pending messages reliably with retry/backoff and idempotent consumer handling.

1. Architectural Blueprint & Delivery Flow

[MVC Controller Action]
   │  raises domain event on aggregate entity
   ▼
[AppDbContext.SaveChangesAsync()]
   │  triggers SaveChangesInterceptor.SavingChangesAsync()
   ▼
[OutboxSaveChangesInterceptor]
   │  collects domain events from ChangeTracker
   │  serializes & adds OutboxMessage rows to same DbContext transaction
   ▼
[Database COMMIT] ──(atomic: domain row + outbox row commit together)
   │
   ├─> signals ChannelWriter<Guid> (fast wake-up path)
   │
   ▼
[OutboxDispatcherBackgroundService]
   ├─ drains ChannelReader<Guid> + periodic fallback poll (catches un-notified rows after restart)
   ├─ claims batch with row-level lock / atomic status transition
   ├─ publishes via IOutboxMessagePublisher (broker / event bus)
   └─ marks ProcessedAtUtc or increments RetryCount + NextAttemptAtUtc with backoff

Component

Responsibility

Failure & Recovery Behavior

Domain Entity (AggregateRoot)

Records domain events during state transitions without knowing about EF Core or brokers.

Cleared once harvested by the interceptor.

OutboxSaveChangesInterceptor

Extracts uncommitted domain events and inserts OutboxMessage rows into the active transaction.

Rolls back automatically if the database transaction fails.

Channel<Guid> + BackgroundService

Provides near-real-time dispatch while a periodic sweep catches missed/retryable rows.

Bounded channel with DropOldest or Wait wake-up signal; DB remains the source of truth.

Outbox Worker Retry Policy

Retries transient broker errors with exponential backoff; isolates poison messages after max attempts.

Never drops unacknowledged messages silently; logs failure details and Error text.

2. Domain Model, Outbox Entity, and EF Core Configuration

Let's model a clean aggregate (Invoice), an IDomainEvent contract, and an OutboxMessage entity persisted in the same AppDbContext.

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

public interface IDomainEvent
{
    Guid EventId { get; }
    DateTimeOffset OccurredAtUtc { get; }
}

public sealed record InvoiceIssuedDomainEvent(
    Guid EventId,
    Guid InvoiceId,
    string InvoiceNumber,
    decimal GrossAmount,
    DateTimeOffset OccurredAtUtc
) : IDomainEvent;

public abstract class Entity
{
    private readonly List<IDomainEvent> _domainEvents = [];

    public IReadOnlyCollection<IDomainEvent> DomainEvents => _domainEvents.AsReadOnly();

    protected void RaiseDomainEvent(IDomainEvent domainEvent)
    {
        _domainEvents.Add(domainEvent);
    }

    public void ClearDomainEvents()
    {
        _domainEvents.Clear();
    }
}

public sealed class Invoice : Entity
{
    public Guid Id { get; private set; }
    public string InvoiceNumber { get; private set; } = string.Empty;
    public decimal GrossAmount { get; private set; }
    public string Status { get; private set; } = "Draft";
    public DateTimeOffset CreatedAtUtc { get; private set; }

    private Invoice() { }

    public static Invoice Issue(string invoiceNumber, decimal grossAmount, DateTimeOffset nowUtc)
    {
        if (string.IsNullOrWhiteSpace(invoiceNumber))
        {
            throw new ArgumentException("Invoice number is required.", nameof(invoiceNumber));
        }

        if (grossAmount <= 0m)
        {
            throw new ArgumentOutOfRangeException(nameof(grossAmount), "Gross amount must be positive.");
        }

        var invoice = new Invoice
        {
            Id = Guid.NewGuid(),
            InvoiceNumber = invoiceNumber.Trim().ToUpperInvariant(),
            GrossAmount = decimal.Round(grossAmount, 2, MidpointRounding.AwayFromZero),
            Status = "Issued",
            CreatedAtUtc = nowUtc
        };

        invoice.RaiseDomainEvent(new InvoiceIssuedDomainEvent(
            EventId: Guid.NewGuid(),
            InvoiceId: invoice.Id,
            InvoiceNumber: invoice.InvoiceNumber,
            GrossAmount: invoice.GrossAmount,
            OccurredAtUtc: nowUtc));

        return invoice;
    }
}

public sealed class OutboxMessage
{
    public Guid Id { get; set; }
    public string EventType { get; set; } = string.Empty;
    public string PayloadJson { get; set; } = string.Empty;
    public DateTimeOffset OccurredAtUtc { get; set; }
    public DateTimeOffset? ProcessedAtUtc { get; set; }
    public DateTimeOffset NextAttemptAtUtc { get; set; }
    public int RetryCount { get; set; }
    public string? LastError { get; set; }
}

public sealed class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }

    public DbSet<Invoice> Invoices => Set<Invoice>();
    public DbSet<OutboxMessage> OutboxMessages => Set<OutboxMessage>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Invoice>(builder =>
        {
            builder.HasKey(x => x.Id);
            builder.Property(x => x.InvoiceNumber).HasMaxLength(40).IsRequired();
            builder.HasIndex(x => x.InvoiceNumber).IsUnique();
            builder.Property(x => x.GrossAmount).HasColumnType("decimal(18,2)");
            builder.Property(x => x.Status).HasMaxLength(24).IsRequired();
        });

        modelBuilder.Entity<OutboxMessage>(builder =>
        {
            builder.HasKey(x => x.Id);
            builder.Property(x => x.EventType).HasMaxLength(256).IsRequired();
            builder.Property(x => x.PayloadJson).IsRequired();
            builder.Property(x => x.LastError).HasMaxLength(2000);

            // Supports fast polling of unprocessed messages eligible for retry
            builder.HasIndex(x => new { x.ProcessedAtUtc, x.NextAttemptAtUtc, x.OccurredAtUtc });
        });
    }
}


3. EF Core SaveChangesInterceptor & Wake-Up Signaler
OutboxSaveChangesInterceptor hooks into SavingChangesAsync before EF Core flushes changes to the database. Any OutboxMessage entities added here become part of the exact same DbContext transaction as the Invoice insert or update.
using System.Text.Json;
using System.Threading.Channels;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;

public sealed class OutboxNotificationQueue
{
    private readonly Channel<Guid> _channel;

    public OutboxNotificationQueue(int capacity = 4096)
    {
        var options = new BoundedChannelOptions(capacity)
        {
            FullMode = BoundedChannelFullMode.DropOldest,
            SingleReader = true,
            SingleWriter = false
        };
        _channel = Channel.CreateBounded<Guid>(options);
    }

    public ChannelReader<Guid> Reader => _channel.Reader;

    public void TryNotify(Guid outboxMessageId)
    {
        _channel.Writer.TryWrite(outboxMessageId);
    }
}

public sealed class OutboxSaveChangesInterceptor : SaveChangesInterceptor
{
    private static readonly JsonSerializerOptions SerializerOptions = new(JsonSerializerDefaults.Web);
    private readonly OutboxNotificationQueue _notificationQueue;

    public OutboxSaveChangesInterceptor(OutboxNotificationQueue notificationQueue)
    {
        _notificationQueue = notificationQueue;
    }

    public override ValueTask<InterceptionResult<int>> SavingChangesAsync(
        DbContextEventData eventData,
        InterceptionResult<int> result,
        CancellationToken cancellationToken = default)
    {
        if (eventData.Context is not null)
        {
            AppendOutboxMessages(eventData.Context);
        }

        return ValueTask.FromResult(result);
    }

    private void AppendOutboxMessages(DbContext dbContext)
    {
        var entitiesWithEvents = dbContext.ChangeTracker
            .Entries<Entity>()
            .Where(e => e.Entity.DomainEvents.Count > 0)
            .Select(e => e.Entity)
            .ToList();

        if (entitiesWithEvents.Count == 0)
        {
            return;
        }

        DateTimeOffset nowUtc = DateTimeOffset.UtcNow;
        var outboxEntries = new List<OutboxMessage>();

        foreach (Entity entity in entitiesWithEvents)
        {
            foreach (IDomainEvent domainEvent in entity.DomainEvents)
            {
                Type eventClrType = domainEvent.GetType();
                string payloadJson = JsonSerializer.Serialize(domainEvent, eventClrType, SerializerOptions);

                outboxEntries.Add(new OutboxMessage
                {
                    Id = domainEvent.EventId == Guid.Empty ? Guid.NewGuid() : domainEvent.EventId,
                    EventType = eventClrType.AssemblyQualifiedName ?? eventClrType.FullName ?? eventClrType.Name,
                    PayloadJson = payloadJson,
                    OccurredAtUtc = domainEvent.OccurredAtUtc == default ? nowUtc : domainEvent.OccurredAtUtc,
                    NextAttemptAtUtc = nowUtc,
                    RetryCount = 0
                });
            }

            entity.ClearDomainEvents();
        }

        dbContext.Set<OutboxMessage>().AddRange(outboxEntries);

        foreach (OutboxMessage msg in outboxEntries)
        {
            _notificationQueue.TryNotify(msg.Id);
        }
    }
}


4. Publisher Abstraction and BackgroundService Dispatcher

Decoupling message transport behind IOutboxMessagePublisher allows you to publish to RabbitMQ, MassTransit, Azure Service Bus, Kafka, or an internal event bus while keeping retry, backoff, and poison-message isolation centralized in the BackgroundService.

using Microsoft.EntityFrameworkCore;

public interface IOutboxMessagePublisher
{
    Task PublishAsync(OutboxMessage message, CancellationToken cancellationToken = default);
}

public sealed class LoggingBrokerOutboxPublisher : IOutboxMessagePublisher
{
    private readonly ILogger<LoggingBrokerOutboxPublisher> _logger;

    public LoggingBrokerOutboxPublisher(ILogger<LoggingBrokerOutboxPublisher> logger)
    {
        _logger = logger;
    }

    public Task PublishAsync(OutboxMessage message, CancellationToken cancellationToken = default)
    {
        // Replace with your real broker/bus producer (e.g., MassTransit IPublishEndpoint, RabbitMQ channel, Service Bus sender)
        _logger.LogInformation(
            "Published outbox message {OutboxId} of type {EventType} (Retry: {RetryCount}).",
            message.Id,
            message.EventType,
            message.RetryCount);

        return Task.CompletedTask;
    }
}

public sealed class OutboxDispatcherBackgroundService : BackgroundService
{
    private const int BatchSize = 50;
    private const int MaxRetries = 5;
    private static readonly TimeSpan FallbackPollInterval = TimeSpan.FromSeconds(10);

    private readonly IServiceScopeFactory _scopeFactory;
    private readonly OutboxNotificationQueue _notificationQueue;
    private readonly ILogger<OutboxDispatcherBackgroundService> _logger;

    public OutboxDispatcherBackgroundService(
        IServiceScopeFactory scopeFactory,
        OutboxNotificationQueue notificationQueue,
        ILogger<OutboxDispatcherBackgroundService> logger)
    {
        _scopeFactory = scopeFactory;
        _notificationQueue = notificationQueue;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("Outbox dispatcher started.");

        // Drain any backlog immediately on startup
        await ProcessPendingBatchAsync(stoppingToken);

        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                using var delayCts = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken);
                delayCts.CancelAfter(FallbackPollInterval);

                try
                {
                    await _notificationQueue.Reader.WaitToReadAsync(delayCts.Token);
                    // Drain queued wake-up signals
                    while (_notificationQueue.Reader.TryRead(out _))
                    {
                    }
                }
                catch (OperationCanceledException) when (!stoppingToken.IsCancellationRequested)
                {
                    // Fallback timer elapsed; sweep DB for pending or retryable messages
                }

                await ProcessPendingBatchAsync(stoppingToken);
            }
            catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
            {
                break;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Unexpected error in outbox dispatcher loop; backing off briefly.");
                await Task.Delay(TimeSpan.FromSeconds(2), stoppingToken);
            }
        }

        _logger.LogInformation("Outbox dispatcher stopped.");
    }

    private async Task ProcessPendingBatchAsync(CancellationToken cancellationToken)
    {
        using IServiceScope scope = _scopeFactory.CreateScope();
        var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
        var publisher = scope.ServiceProvider.GetRequiredService<IOutboxMessagePublisher>();

        DateTimeOffset nowUtc = DateTimeOffset.UtcNow;

        List<OutboxMessage> batch = await dbContext.OutboxMessages
            .Where(m => m.ProcessedAtUtc == null &&
                        m.RetryCount < MaxRetries &&
                        m.NextAttemptAtUtc <= nowUtc)
            .OrderBy(m => m.OccurredAtUtc)
            .Take(BatchSize)
            .ToListAsync(cancellationToken);

        if (batch.Count == 0)
        {
            return;
        }

        foreach (OutboxMessage message in batch)
        {
            cancellationToken.ThrowIfCancellationRequested();

            try
            {
                await publisher.PublishAsync(message, cancellationToken);

                message.ProcessedAtUtc = DateTimeOffset.UtcNow;
                message.LastError = null;
            }
            catch (Exception ex) when (!cancellationToken.IsCancellationRequested)
            {
                message.RetryCount += 1;
                string errorText = ex.Message.Length > 1900 ? ex.Message[..1900] : ex.Message;
                message.LastError = errorText;

                double backoffSeconds = Math.Min(300, Math.Pow(2, message.RetryCount) * 5);
                message.NextAttemptAtUtc = DateTimeOffset.UtcNow.AddSeconds(backoffSeconds);

                _logger.LogWarning(
                    ex,
                    "Failed publishing outbox message {OutboxId} on attempt {RetryCount}/{MaxRetries}; next attempt at {NextAttemptAtUtc}.",
                    message.Id,
                    message.RetryCount,
                    MaxRetries,
                    message.NextAttemptAtUtc);
            }
        }

        await dbContext.SaveChangesAsync(cancellationToken);
    }
}


5. Wiring into Program.cs and MVC Controller
Service & Hosted Worker Registration (Program.cs)

Register OutboxSaveChangesInterceptor as a singleton or scoped service and attach it to AddDbContext via AddInterceptors(...).
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<OutboxNotificationQueue>();
builder.Services.AddSingleton<OutboxSaveChangesInterceptor>();
builder.Services.AddSingleton<IOutboxMessagePublisher, LoggingBrokerOutboxPublisher>();

builder.Services.AddDbContext<AppDbContext>((sp, options) =>
{
    var interceptor = sp.GetRequiredService<OutboxSaveChangesInterceptor>();
    string connectionString = builder.Configuration.GetConnectionString("DefaultConnection")
        ?? throw new InvalidOperationException("Missing DefaultConnection string.");

    options.UseSqlServer(connectionString)
           .AddInterceptors(interceptor);
});

builder.Services.AddHostedService<OutboxDispatcherBackgroundService>();
builder.Services.AddControllersWithViews();

var app = builder.Build();

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.MapControllers();

app.Run();

public partial class Program { }


MVC Controller Action (InvoicesController.cs)
The controller stays focused on issuing the Invoice and calling SaveChangesAsync(). Both the Invoice row and the OutboxMessage row commit atomically in one transaction.
using Microsoft.AspNetCore.Mvc;

public sealed record IssueInvoiceRequest(
    string InvoiceNumber,
    decimal GrossAmount
);

public sealed record IssueInvoiceResponse(
    Guid InvoiceId,
    string InvoiceNumber,
    decimal GrossAmount,
    string Status
);

[ApiController]
[Route("api/invoices")]
public sealed class InvoicesController : ControllerBase
{
    private readonly AppDbContext _dbContext;

    public InvoicesController(AppDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    [HttpPost]
    public async Task<IActionResult> Issue(
        [FromBody] IssueInvoiceRequest request,
        CancellationToken cancellationToken)
    {
        try
        {
            Invoice invoice = Invoice.Issue(
                request.InvoiceNumber,
                request.GrossAmount,
                DateTimeOffset.UtcNow);

            _dbContext.Invoices.Add(invoice);
            await _dbContext.SaveChangesAsync(cancellationToken);

            var response = new IssueInvoiceResponse(
                invoice.Id,
                invoice.InvoiceNumber,
                invoice.GrossAmount,
                invoice.Status);

            return CreatedAtAction(nameof(GetById), new { id = invoice.Id }, response);
        }
        catch (ArgumentException ex)
        {
            return BadRequest(new ProblemDetails
            {
                Title = "Invalid Invoice Input",
                Detail = ex.Message,
                Status = StatusCodes.Status400BadRequest
            });
        }
    }

    [HttpGet("{id:guid}")]
    public async Task<IActionResult> GetById(Guid id, CancellationToken cancellationToken)
    {
        var invoice = await _dbContext.Invoices
            .AsNoTracking()
            .Where(x => x.Id == id)
            .Select(x => new IssueInvoiceResponse(x.Id, x.InvoiceNumber, x.GrossAmount, x.Status))
            .FirstOrDefaultAsync(cancellationToken);

        return invoice is null ? NotFound() : Ok(invoice);
    }
}

6. End-to-End Integration Testing with WebApplicationFactory<Program>
Using an in-memory/SQLite/SQL Server AppDbContext in WebApplicationFactory<Program>, you can verify that issuing an invoice writes an OutboxMessage atomically and that the BackgroundService marks it processed without losing messages on failed attempts.
using System.Collections.Concurrent;
using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Xunit;

public sealed class RecordingOutboxPublisher : IOutboxMessagePublisher
{
    public ConcurrentBag<OutboxMessage> PublishedMessages { get; } = [];

    public Task PublishAsync(OutboxMessage message, CancellationToken cancellationToken = default)
    {
        PublishedMessages.Add(message);
        return Task.CompletedTask;
    }
}

public sealed class OutboxTestFactory : WebApplicationFactory<Program>, IAsyncLifetime
{
    private readonly SqliteConnection _connection = new("DataSource=:memory:");
    public RecordingOutboxPublisher RecordingPublisher { get; } = new();

    public async Task InitializeAsync()
    {
        await _connection.OpenAsync();

        using IServiceScope scope = Services.CreateScope();
        var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
        await db.Database.EnsureCreatedAsync();
    }

    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureServices(services =>
        {
            ServiceDescriptor? dbContextDescriptor = services.SingleOrDefault(
                d => d.ServiceType == typeof(DbContextOptions<AppDbContext>));
            if (dbContextDescriptor is not null)
            {
                services.Remove(dbContextDescriptor);
            }

            ServiceDescriptor? publisherDescriptor = services.SingleOrDefault(
                d => d.ServiceType == typeof(IOutboxMessagePublisher));
            if (publisherDescriptor is not null)
            {
                services.Remove(publisherDescriptor);
            }

            services.AddSingleton<IOutboxMessagePublisher>(RecordingPublisher);
            services.AddDbContext<AppDbContext>((sp, options) =>
            {
                var interceptor = sp.GetRequiredService<OutboxSaveChangesInterceptor>();
                options.UseSqlite(_connection)
                       .AddInterceptors(interceptor);
            });
        });
    }

    public new async Task DisposeAsync()
    {
        await base.DisposeAsync();
        await _connection.DisposeAsync();
    }
}

public sealed class TransactionalOutboxTests : IClassFixture<OutboxTestFactory>
{
    private readonly OutboxTestFactory _factory;

    public TransactionalOutboxTests(OutboxTestFactory factory)
    {
        _factory = factory;
    }

    [Fact]
    public async Task IssueInvoice_PersistsInvoiceAndDispatchesOutboxMessage()
    {
        using HttpClient client = _factory.CreateClient();
        string invNumber = $"INV-{Guid.NewGuid():N}"[..14];

        HttpResponseMessage response = await client.PostAsJsonAsync(
            "/api/invoices",
            new IssueInvoiceRequest(invNumber, 1250.00m));

        Assert.Equal(HttpStatusCode.Created, response.StatusCode);
        IssueInvoiceResponse? created = await response.Content.ReadFromJsonAsync<IssueInvoiceResponse>();
        Assert.NotNull(created);

        // Allow background dispatcher a brief window to process queued item
        await Task.Delay(TimeSpan.FromMilliseconds(350));

        using IServiceScope scope = _factory.Services.CreateScope();
        var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();

        OutboxMessage? outboxRow = await db.OutboxMessages
            .AsNoTracking()
            .FirstOrDefaultAsync(m => m.PayloadJson.Contains(created.InvoiceId.ToString()));

        Assert.NotNull(outboxRow);
        Assert.NotNull(outboxRow.ProcessedAtUtc);
        Assert.Contains(_factory.RecordingPublisher.PublishedMessages, m => m.Id == outboxRow.Id);
    }
}

7. Conclusion
The Transactional Outbox Pattern—implemented with an EF Core SaveChangesInterceptor and a BackgroundService backed by a Channel<T> wake-up queue and periodic database sweep—gives ASP.NET Core MVC applications reliable, at-least-once event publication without dual-write race conditions. Domain state and outbox messages commit inside one database transaction, transient broker failures back off and retry automatically, and downstream consumers can safely deduplicate by OutboxMessage.Id / EventId.